filename
stringlengths
3
9
code
stringlengths
4
1.05M
187486.c
/* MIT License * * Copyright (c) 2016-2020 INRIA, CMU and Microsoft Corporation * * 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 "Hacl_Chacha20_Vec128.h" static inline void double_round_128(Lib_IntVector_Intrinsics_vec128 *st) { Lib_IntVector_Intrinsics_vec128 std0; Lib_IntVector_Intrinsics_vec128 std1; Lib_IntVector_Intrinsics_vec128 std2; Lib_IntVector_Intrinsics_vec128 std3; Lib_IntVector_Intrinsics_vec128 std4; Lib_IntVector_Intrinsics_vec128 std5; Lib_IntVector_Intrinsics_vec128 std6; Lib_IntVector_Intrinsics_vec128 std7; Lib_IntVector_Intrinsics_vec128 std8; Lib_IntVector_Intrinsics_vec128 std9; Lib_IntVector_Intrinsics_vec128 std10; Lib_IntVector_Intrinsics_vec128 std11; Lib_IntVector_Intrinsics_vec128 std12; Lib_IntVector_Intrinsics_vec128 std13; Lib_IntVector_Intrinsics_vec128 std14; Lib_IntVector_Intrinsics_vec128 std15; Lib_IntVector_Intrinsics_vec128 std16; Lib_IntVector_Intrinsics_vec128 std17; Lib_IntVector_Intrinsics_vec128 std18; Lib_IntVector_Intrinsics_vec128 std19; Lib_IntVector_Intrinsics_vec128 std20; Lib_IntVector_Intrinsics_vec128 std21; Lib_IntVector_Intrinsics_vec128 std22; Lib_IntVector_Intrinsics_vec128 std23; Lib_IntVector_Intrinsics_vec128 std24; Lib_IntVector_Intrinsics_vec128 std25; Lib_IntVector_Intrinsics_vec128 std26; Lib_IntVector_Intrinsics_vec128 std27; Lib_IntVector_Intrinsics_vec128 std28; Lib_IntVector_Intrinsics_vec128 std29; Lib_IntVector_Intrinsics_vec128 std30; Lib_IntVector_Intrinsics_vec128 std; st[0U] = Lib_IntVector_Intrinsics_vec128_add32(st[0U], st[4U]); std0 = Lib_IntVector_Intrinsics_vec128_xor(st[12U], st[0U]); st[12U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std0, (uint32_t)16U); st[8U] = Lib_IntVector_Intrinsics_vec128_add32(st[8U], st[12U]); std1 = Lib_IntVector_Intrinsics_vec128_xor(st[4U], st[8U]); st[4U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std1, (uint32_t)12U); st[0U] = Lib_IntVector_Intrinsics_vec128_add32(st[0U], st[4U]); std2 = Lib_IntVector_Intrinsics_vec128_xor(st[12U], st[0U]); st[12U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std2, (uint32_t)8U); st[8U] = Lib_IntVector_Intrinsics_vec128_add32(st[8U], st[12U]); std3 = Lib_IntVector_Intrinsics_vec128_xor(st[4U], st[8U]); st[4U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std3, (uint32_t)7U); st[1U] = Lib_IntVector_Intrinsics_vec128_add32(st[1U], st[5U]); std4 = Lib_IntVector_Intrinsics_vec128_xor(st[13U], st[1U]); st[13U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std4, (uint32_t)16U); st[9U] = Lib_IntVector_Intrinsics_vec128_add32(st[9U], st[13U]); std5 = Lib_IntVector_Intrinsics_vec128_xor(st[5U], st[9U]); st[5U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std5, (uint32_t)12U); st[1U] = Lib_IntVector_Intrinsics_vec128_add32(st[1U], st[5U]); std6 = Lib_IntVector_Intrinsics_vec128_xor(st[13U], st[1U]); st[13U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std6, (uint32_t)8U); st[9U] = Lib_IntVector_Intrinsics_vec128_add32(st[9U], st[13U]); std7 = Lib_IntVector_Intrinsics_vec128_xor(st[5U], st[9U]); st[5U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std7, (uint32_t)7U); st[2U] = Lib_IntVector_Intrinsics_vec128_add32(st[2U], st[6U]); std8 = Lib_IntVector_Intrinsics_vec128_xor(st[14U], st[2U]); st[14U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std8, (uint32_t)16U); st[10U] = Lib_IntVector_Intrinsics_vec128_add32(st[10U], st[14U]); std9 = Lib_IntVector_Intrinsics_vec128_xor(st[6U], st[10U]); st[6U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std9, (uint32_t)12U); st[2U] = Lib_IntVector_Intrinsics_vec128_add32(st[2U], st[6U]); std10 = Lib_IntVector_Intrinsics_vec128_xor(st[14U], st[2U]); st[14U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std10, (uint32_t)8U); st[10U] = Lib_IntVector_Intrinsics_vec128_add32(st[10U], st[14U]); std11 = Lib_IntVector_Intrinsics_vec128_xor(st[6U], st[10U]); st[6U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std11, (uint32_t)7U); st[3U] = Lib_IntVector_Intrinsics_vec128_add32(st[3U], st[7U]); std12 = Lib_IntVector_Intrinsics_vec128_xor(st[15U], st[3U]); st[15U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std12, (uint32_t)16U); st[11U] = Lib_IntVector_Intrinsics_vec128_add32(st[11U], st[15U]); std13 = Lib_IntVector_Intrinsics_vec128_xor(st[7U], st[11U]); st[7U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std13, (uint32_t)12U); st[3U] = Lib_IntVector_Intrinsics_vec128_add32(st[3U], st[7U]); std14 = Lib_IntVector_Intrinsics_vec128_xor(st[15U], st[3U]); st[15U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std14, (uint32_t)8U); st[11U] = Lib_IntVector_Intrinsics_vec128_add32(st[11U], st[15U]); std15 = Lib_IntVector_Intrinsics_vec128_xor(st[7U], st[11U]); st[7U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std15, (uint32_t)7U); st[0U] = Lib_IntVector_Intrinsics_vec128_add32(st[0U], st[5U]); std16 = Lib_IntVector_Intrinsics_vec128_xor(st[15U], st[0U]); st[15U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std16, (uint32_t)16U); st[10U] = Lib_IntVector_Intrinsics_vec128_add32(st[10U], st[15U]); std17 = Lib_IntVector_Intrinsics_vec128_xor(st[5U], st[10U]); st[5U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std17, (uint32_t)12U); st[0U] = Lib_IntVector_Intrinsics_vec128_add32(st[0U], st[5U]); std18 = Lib_IntVector_Intrinsics_vec128_xor(st[15U], st[0U]); st[15U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std18, (uint32_t)8U); st[10U] = Lib_IntVector_Intrinsics_vec128_add32(st[10U], st[15U]); std19 = Lib_IntVector_Intrinsics_vec128_xor(st[5U], st[10U]); st[5U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std19, (uint32_t)7U); st[1U] = Lib_IntVector_Intrinsics_vec128_add32(st[1U], st[6U]); std20 = Lib_IntVector_Intrinsics_vec128_xor(st[12U], st[1U]); st[12U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std20, (uint32_t)16U); st[11U] = Lib_IntVector_Intrinsics_vec128_add32(st[11U], st[12U]); std21 = Lib_IntVector_Intrinsics_vec128_xor(st[6U], st[11U]); st[6U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std21, (uint32_t)12U); st[1U] = Lib_IntVector_Intrinsics_vec128_add32(st[1U], st[6U]); std22 = Lib_IntVector_Intrinsics_vec128_xor(st[12U], st[1U]); st[12U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std22, (uint32_t)8U); st[11U] = Lib_IntVector_Intrinsics_vec128_add32(st[11U], st[12U]); std23 = Lib_IntVector_Intrinsics_vec128_xor(st[6U], st[11U]); st[6U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std23, (uint32_t)7U); st[2U] = Lib_IntVector_Intrinsics_vec128_add32(st[2U], st[7U]); std24 = Lib_IntVector_Intrinsics_vec128_xor(st[13U], st[2U]); st[13U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std24, (uint32_t)16U); st[8U] = Lib_IntVector_Intrinsics_vec128_add32(st[8U], st[13U]); std25 = Lib_IntVector_Intrinsics_vec128_xor(st[7U], st[8U]); st[7U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std25, (uint32_t)12U); st[2U] = Lib_IntVector_Intrinsics_vec128_add32(st[2U], st[7U]); std26 = Lib_IntVector_Intrinsics_vec128_xor(st[13U], st[2U]); st[13U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std26, (uint32_t)8U); st[8U] = Lib_IntVector_Intrinsics_vec128_add32(st[8U], st[13U]); std27 = Lib_IntVector_Intrinsics_vec128_xor(st[7U], st[8U]); st[7U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std27, (uint32_t)7U); st[3U] = Lib_IntVector_Intrinsics_vec128_add32(st[3U], st[4U]); std28 = Lib_IntVector_Intrinsics_vec128_xor(st[14U], st[3U]); st[14U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std28, (uint32_t)16U); st[9U] = Lib_IntVector_Intrinsics_vec128_add32(st[9U], st[14U]); std29 = Lib_IntVector_Intrinsics_vec128_xor(st[4U], st[9U]); st[4U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std29, (uint32_t)12U); st[3U] = Lib_IntVector_Intrinsics_vec128_add32(st[3U], st[4U]); std30 = Lib_IntVector_Intrinsics_vec128_xor(st[14U], st[3U]); st[14U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std30, (uint32_t)8U); st[9U] = Lib_IntVector_Intrinsics_vec128_add32(st[9U], st[14U]); std = Lib_IntVector_Intrinsics_vec128_xor(st[4U], st[9U]); st[4U] = Lib_IntVector_Intrinsics_vec128_rotate_left32(std, (uint32_t)7U); } static inline void chacha20_core_128( Lib_IntVector_Intrinsics_vec128 *k, Lib_IntVector_Intrinsics_vec128 *ctx, uint32_t ctr ) { uint32_t ctr_u32; Lib_IntVector_Intrinsics_vec128 cv; memcpy(k, ctx, (uint32_t)16U * sizeof (Lib_IntVector_Intrinsics_vec128)); ctr_u32 = (uint32_t)4U * ctr; cv = Lib_IntVector_Intrinsics_vec128_load32(ctr_u32); k[12U] = Lib_IntVector_Intrinsics_vec128_add32(k[12U], cv); double_round_128(k); double_round_128(k); double_round_128(k); double_round_128(k); double_round_128(k); double_round_128(k); double_round_128(k); double_round_128(k); double_round_128(k); double_round_128(k); { uint32_t i; for (i = (uint32_t)0U; i < (uint32_t)16U; i++) { Lib_IntVector_Intrinsics_vec128 *os = k; Lib_IntVector_Intrinsics_vec128 x = Lib_IntVector_Intrinsics_vec128_add32(k[i], ctx[i]); os[i] = x; } } k[12U] = Lib_IntVector_Intrinsics_vec128_add32(k[12U], cv); } static inline void chacha20_init_128(Lib_IntVector_Intrinsics_vec128 *ctx, uint8_t *k, uint8_t *n, uint32_t ctr) { uint32_t ctx1[16U] = { 0U }; uint32_t *uu____0 = ctx1; uint32_t *uu____1; uint32_t *uu____2; Lib_IntVector_Intrinsics_vec128 ctr1; Lib_IntVector_Intrinsics_vec128 c12; { uint32_t i; for (i = (uint32_t)0U; i < (uint32_t)4U; i++) { uint32_t *os = uu____0; uint32_t x = Hacl_Impl_Chacha20_Vec_chacha20_constants[i]; os[i] = x; } } uu____1 = ctx1 + (uint32_t)4U; { uint32_t i; for (i = (uint32_t)0U; i < (uint32_t)8U; i++) { uint32_t *os = uu____1; uint8_t *bj = k + i * (uint32_t)4U; uint32_t u = load32_le(bj); uint32_t r = u; uint32_t x = r; os[i] = x; } } ctx1[12U] = ctr; uu____2 = ctx1 + (uint32_t)13U; { uint32_t i; for (i = (uint32_t)0U; i < (uint32_t)3U; i++) { uint32_t *os = uu____2; uint8_t *bj = n + i * (uint32_t)4U; uint32_t u = load32_le(bj); uint32_t r = u; uint32_t x = r; os[i] = x; } } { uint32_t i; for (i = (uint32_t)0U; i < (uint32_t)16U; i++) { Lib_IntVector_Intrinsics_vec128 *os = ctx; uint32_t x = ctx1[i]; Lib_IntVector_Intrinsics_vec128 x0 = Lib_IntVector_Intrinsics_vec128_load32(x); os[i] = x0; } } ctr1 = Lib_IntVector_Intrinsics_vec128_load32s((uint32_t)0U, (uint32_t)1U, (uint32_t)2U, (uint32_t)3U); c12 = ctx[12U]; ctx[12U] = Lib_IntVector_Intrinsics_vec128_add32(c12, ctr1); } void Hacl_Chacha20_Vec128_chacha20_encrypt_128( uint32_t len, uint8_t *out, uint8_t *text, uint8_t *key, uint8_t *n, uint32_t ctr ) { Lib_IntVector_Intrinsics_vec128 ctx[16U]; { uint32_t _i; for (_i = 0U; _i < (uint32_t)16U; ++_i) ctx[_i] = Lib_IntVector_Intrinsics_vec128_zero; } { uint32_t rem; uint32_t nb; uint32_t rem1; chacha20_init_128(ctx, key, n, ctr); rem = len % (uint32_t)256U; nb = len / (uint32_t)256U; rem1 = len % (uint32_t)256U; { uint32_t i; for (i = (uint32_t)0U; i < nb; i++) { uint8_t *uu____0 = out + i * (uint32_t)256U; uint8_t *uu____1 = text + i * (uint32_t)256U; Lib_IntVector_Intrinsics_vec128 k[16U]; { uint32_t _i; for (_i = 0U; _i < (uint32_t)16U; ++_i) k[_i] = Lib_IntVector_Intrinsics_vec128_zero; } chacha20_core_128(k, ctx, i); { Lib_IntVector_Intrinsics_vec128 v00 = k[0U]; Lib_IntVector_Intrinsics_vec128 v16 = k[1U]; Lib_IntVector_Intrinsics_vec128 v20 = k[2U]; Lib_IntVector_Intrinsics_vec128 v30 = k[3U]; Lib_IntVector_Intrinsics_vec128 v0_ = Lib_IntVector_Intrinsics_vec128_interleave_low32(v00, v16); Lib_IntVector_Intrinsics_vec128 v1_ = Lib_IntVector_Intrinsics_vec128_interleave_high32(v00, v16); Lib_IntVector_Intrinsics_vec128 v2_ = Lib_IntVector_Intrinsics_vec128_interleave_low32(v20, v30); Lib_IntVector_Intrinsics_vec128 v3_ = Lib_IntVector_Intrinsics_vec128_interleave_high32(v20, v30); Lib_IntVector_Intrinsics_vec128 v0__ = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_, v2_); Lib_IntVector_Intrinsics_vec128 v1__ = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_, v2_); Lib_IntVector_Intrinsics_vec128 v2__ = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_, v3_); Lib_IntVector_Intrinsics_vec128 v3__ = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_, v3_); Lib_IntVector_Intrinsics_vec128 v0 = v0__; Lib_IntVector_Intrinsics_vec128 v1 = v1__; Lib_IntVector_Intrinsics_vec128 v2 = v2__; Lib_IntVector_Intrinsics_vec128 v3 = v3__; Lib_IntVector_Intrinsics_vec128 v010 = k[4U]; Lib_IntVector_Intrinsics_vec128 v110 = k[5U]; Lib_IntVector_Intrinsics_vec128 v210 = k[6U]; Lib_IntVector_Intrinsics_vec128 v310 = k[7U]; Lib_IntVector_Intrinsics_vec128 v0_0 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v010, v110); Lib_IntVector_Intrinsics_vec128 v1_0 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v010, v110); Lib_IntVector_Intrinsics_vec128 v2_0 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v210, v310); Lib_IntVector_Intrinsics_vec128 v3_0 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v210, v310); Lib_IntVector_Intrinsics_vec128 v0__0 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_0, v2_0); Lib_IntVector_Intrinsics_vec128 v1__0 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_0, v2_0); Lib_IntVector_Intrinsics_vec128 v2__0 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_0, v3_0); Lib_IntVector_Intrinsics_vec128 v3__0 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_0, v3_0); Lib_IntVector_Intrinsics_vec128 v4 = v0__0; Lib_IntVector_Intrinsics_vec128 v5 = v1__0; Lib_IntVector_Intrinsics_vec128 v6 = v2__0; Lib_IntVector_Intrinsics_vec128 v7 = v3__0; Lib_IntVector_Intrinsics_vec128 v011 = k[8U]; Lib_IntVector_Intrinsics_vec128 v111 = k[9U]; Lib_IntVector_Intrinsics_vec128 v211 = k[10U]; Lib_IntVector_Intrinsics_vec128 v311 = k[11U]; Lib_IntVector_Intrinsics_vec128 v0_1 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v011, v111); Lib_IntVector_Intrinsics_vec128 v1_1 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v011, v111); Lib_IntVector_Intrinsics_vec128 v2_1 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v211, v311); Lib_IntVector_Intrinsics_vec128 v3_1 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v211, v311); Lib_IntVector_Intrinsics_vec128 v0__1 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_1, v2_1); Lib_IntVector_Intrinsics_vec128 v1__1 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_1, v2_1); Lib_IntVector_Intrinsics_vec128 v2__1 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_1, v3_1); Lib_IntVector_Intrinsics_vec128 v3__1 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_1, v3_1); Lib_IntVector_Intrinsics_vec128 v8 = v0__1; Lib_IntVector_Intrinsics_vec128 v9 = v1__1; Lib_IntVector_Intrinsics_vec128 v10 = v2__1; Lib_IntVector_Intrinsics_vec128 v11 = v3__1; Lib_IntVector_Intrinsics_vec128 v01 = k[12U]; Lib_IntVector_Intrinsics_vec128 v120 = k[13U]; Lib_IntVector_Intrinsics_vec128 v21 = k[14U]; Lib_IntVector_Intrinsics_vec128 v31 = k[15U]; Lib_IntVector_Intrinsics_vec128 v0_2 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v01, v120); Lib_IntVector_Intrinsics_vec128 v1_2 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v01, v120); Lib_IntVector_Intrinsics_vec128 v2_2 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v21, v31); Lib_IntVector_Intrinsics_vec128 v3_2 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v21, v31); Lib_IntVector_Intrinsics_vec128 v0__2 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_2, v2_2); Lib_IntVector_Intrinsics_vec128 v1__2 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_2, v2_2); Lib_IntVector_Intrinsics_vec128 v2__2 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_2, v3_2); Lib_IntVector_Intrinsics_vec128 v3__2 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_2, v3_2); Lib_IntVector_Intrinsics_vec128 v12 = v0__2; Lib_IntVector_Intrinsics_vec128 v13 = v1__2; Lib_IntVector_Intrinsics_vec128 v14 = v2__2; Lib_IntVector_Intrinsics_vec128 v15 = v3__2; k[0U] = v0; k[1U] = v4; k[2U] = v8; k[3U] = v12; k[4U] = v1; k[5U] = v5; k[6U] = v9; k[7U] = v13; k[8U] = v2; k[9U] = v6; k[10U] = v10; k[11U] = v14; k[12U] = v3; k[13U] = v7; k[14U] = v11; k[15U] = v15; { uint32_t i0; for (i0 = (uint32_t)0U; i0 < (uint32_t)16U; i0++) { Lib_IntVector_Intrinsics_vec128 x = Lib_IntVector_Intrinsics_vec128_load32_le(uu____1 + i0 * (uint32_t)16U); Lib_IntVector_Intrinsics_vec128 y = Lib_IntVector_Intrinsics_vec128_xor(x, k[i0]); Lib_IntVector_Intrinsics_vec128_store32_le(uu____0 + i0 * (uint32_t)16U, y); } } } } } if (rem1 > (uint32_t)0U) { uint8_t *uu____2 = out + nb * (uint32_t)256U; uint8_t *uu____3 = text + nb * (uint32_t)256U; uint8_t plain[256U] = { 0U }; memcpy(plain, uu____3, rem * sizeof (uint8_t)); { Lib_IntVector_Intrinsics_vec128 k[16U]; { uint32_t _i; for (_i = 0U; _i < (uint32_t)16U; ++_i) k[_i] = Lib_IntVector_Intrinsics_vec128_zero; } chacha20_core_128(k, ctx, nb); { Lib_IntVector_Intrinsics_vec128 v00 = k[0U]; Lib_IntVector_Intrinsics_vec128 v16 = k[1U]; Lib_IntVector_Intrinsics_vec128 v20 = k[2U]; Lib_IntVector_Intrinsics_vec128 v30 = k[3U]; Lib_IntVector_Intrinsics_vec128 v0_ = Lib_IntVector_Intrinsics_vec128_interleave_low32(v00, v16); Lib_IntVector_Intrinsics_vec128 v1_ = Lib_IntVector_Intrinsics_vec128_interleave_high32(v00, v16); Lib_IntVector_Intrinsics_vec128 v2_ = Lib_IntVector_Intrinsics_vec128_interleave_low32(v20, v30); Lib_IntVector_Intrinsics_vec128 v3_ = Lib_IntVector_Intrinsics_vec128_interleave_high32(v20, v30); Lib_IntVector_Intrinsics_vec128 v0__ = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_, v2_); Lib_IntVector_Intrinsics_vec128 v1__ = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_, v2_); Lib_IntVector_Intrinsics_vec128 v2__ = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_, v3_); Lib_IntVector_Intrinsics_vec128 v3__ = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_, v3_); Lib_IntVector_Intrinsics_vec128 v0 = v0__; Lib_IntVector_Intrinsics_vec128 v1 = v1__; Lib_IntVector_Intrinsics_vec128 v2 = v2__; Lib_IntVector_Intrinsics_vec128 v3 = v3__; Lib_IntVector_Intrinsics_vec128 v010 = k[4U]; Lib_IntVector_Intrinsics_vec128 v110 = k[5U]; Lib_IntVector_Intrinsics_vec128 v210 = k[6U]; Lib_IntVector_Intrinsics_vec128 v310 = k[7U]; Lib_IntVector_Intrinsics_vec128 v0_0 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v010, v110); Lib_IntVector_Intrinsics_vec128 v1_0 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v010, v110); Lib_IntVector_Intrinsics_vec128 v2_0 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v210, v310); Lib_IntVector_Intrinsics_vec128 v3_0 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v210, v310); Lib_IntVector_Intrinsics_vec128 v0__0 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_0, v2_0); Lib_IntVector_Intrinsics_vec128 v1__0 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_0, v2_0); Lib_IntVector_Intrinsics_vec128 v2__0 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_0, v3_0); Lib_IntVector_Intrinsics_vec128 v3__0 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_0, v3_0); Lib_IntVector_Intrinsics_vec128 v4 = v0__0; Lib_IntVector_Intrinsics_vec128 v5 = v1__0; Lib_IntVector_Intrinsics_vec128 v6 = v2__0; Lib_IntVector_Intrinsics_vec128 v7 = v3__0; Lib_IntVector_Intrinsics_vec128 v011 = k[8U]; Lib_IntVector_Intrinsics_vec128 v111 = k[9U]; Lib_IntVector_Intrinsics_vec128 v211 = k[10U]; Lib_IntVector_Intrinsics_vec128 v311 = k[11U]; Lib_IntVector_Intrinsics_vec128 v0_1 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v011, v111); Lib_IntVector_Intrinsics_vec128 v1_1 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v011, v111); Lib_IntVector_Intrinsics_vec128 v2_1 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v211, v311); Lib_IntVector_Intrinsics_vec128 v3_1 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v211, v311); Lib_IntVector_Intrinsics_vec128 v0__1 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_1, v2_1); Lib_IntVector_Intrinsics_vec128 v1__1 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_1, v2_1); Lib_IntVector_Intrinsics_vec128 v2__1 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_1, v3_1); Lib_IntVector_Intrinsics_vec128 v3__1 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_1, v3_1); Lib_IntVector_Intrinsics_vec128 v8 = v0__1; Lib_IntVector_Intrinsics_vec128 v9 = v1__1; Lib_IntVector_Intrinsics_vec128 v10 = v2__1; Lib_IntVector_Intrinsics_vec128 v11 = v3__1; Lib_IntVector_Intrinsics_vec128 v01 = k[12U]; Lib_IntVector_Intrinsics_vec128 v120 = k[13U]; Lib_IntVector_Intrinsics_vec128 v21 = k[14U]; Lib_IntVector_Intrinsics_vec128 v31 = k[15U]; Lib_IntVector_Intrinsics_vec128 v0_2 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v01, v120); Lib_IntVector_Intrinsics_vec128 v1_2 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v01, v120); Lib_IntVector_Intrinsics_vec128 v2_2 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v21, v31); Lib_IntVector_Intrinsics_vec128 v3_2 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v21, v31); Lib_IntVector_Intrinsics_vec128 v0__2 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_2, v2_2); Lib_IntVector_Intrinsics_vec128 v1__2 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_2, v2_2); Lib_IntVector_Intrinsics_vec128 v2__2 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_2, v3_2); Lib_IntVector_Intrinsics_vec128 v3__2 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_2, v3_2); Lib_IntVector_Intrinsics_vec128 v12 = v0__2; Lib_IntVector_Intrinsics_vec128 v13 = v1__2; Lib_IntVector_Intrinsics_vec128 v14 = v2__2; Lib_IntVector_Intrinsics_vec128 v15 = v3__2; k[0U] = v0; k[1U] = v4; k[2U] = v8; k[3U] = v12; k[4U] = v1; k[5U] = v5; k[6U] = v9; k[7U] = v13; k[8U] = v2; k[9U] = v6; k[10U] = v10; k[11U] = v14; k[12U] = v3; k[13U] = v7; k[14U] = v11; k[15U] = v15; { uint32_t i; for (i = (uint32_t)0U; i < (uint32_t)16U; i++) { Lib_IntVector_Intrinsics_vec128 x = Lib_IntVector_Intrinsics_vec128_load32_le(plain + i * (uint32_t)16U); Lib_IntVector_Intrinsics_vec128 y = Lib_IntVector_Intrinsics_vec128_xor(x, k[i]); Lib_IntVector_Intrinsics_vec128_store32_le(plain + i * (uint32_t)16U, y); } } memcpy(uu____2, plain, rem * sizeof (uint8_t)); } } } } } void Hacl_Chacha20_Vec128_chacha20_decrypt_128( uint32_t len, uint8_t *out, uint8_t *cipher, uint8_t *key, uint8_t *n, uint32_t ctr ) { Lib_IntVector_Intrinsics_vec128 ctx[16U]; { uint32_t _i; for (_i = 0U; _i < (uint32_t)16U; ++_i) ctx[_i] = Lib_IntVector_Intrinsics_vec128_zero; } { uint32_t rem; uint32_t nb; uint32_t rem1; chacha20_init_128(ctx, key, n, ctr); rem = len % (uint32_t)256U; nb = len / (uint32_t)256U; rem1 = len % (uint32_t)256U; { uint32_t i; for (i = (uint32_t)0U; i < nb; i++) { uint8_t *uu____0 = out + i * (uint32_t)256U; uint8_t *uu____1 = cipher + i * (uint32_t)256U; Lib_IntVector_Intrinsics_vec128 k[16U]; { uint32_t _i; for (_i = 0U; _i < (uint32_t)16U; ++_i) k[_i] = Lib_IntVector_Intrinsics_vec128_zero; } chacha20_core_128(k, ctx, i); { Lib_IntVector_Intrinsics_vec128 v00 = k[0U]; Lib_IntVector_Intrinsics_vec128 v16 = k[1U]; Lib_IntVector_Intrinsics_vec128 v20 = k[2U]; Lib_IntVector_Intrinsics_vec128 v30 = k[3U]; Lib_IntVector_Intrinsics_vec128 v0_ = Lib_IntVector_Intrinsics_vec128_interleave_low32(v00, v16); Lib_IntVector_Intrinsics_vec128 v1_ = Lib_IntVector_Intrinsics_vec128_interleave_high32(v00, v16); Lib_IntVector_Intrinsics_vec128 v2_ = Lib_IntVector_Intrinsics_vec128_interleave_low32(v20, v30); Lib_IntVector_Intrinsics_vec128 v3_ = Lib_IntVector_Intrinsics_vec128_interleave_high32(v20, v30); Lib_IntVector_Intrinsics_vec128 v0__ = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_, v2_); Lib_IntVector_Intrinsics_vec128 v1__ = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_, v2_); Lib_IntVector_Intrinsics_vec128 v2__ = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_, v3_); Lib_IntVector_Intrinsics_vec128 v3__ = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_, v3_); Lib_IntVector_Intrinsics_vec128 v0 = v0__; Lib_IntVector_Intrinsics_vec128 v1 = v1__; Lib_IntVector_Intrinsics_vec128 v2 = v2__; Lib_IntVector_Intrinsics_vec128 v3 = v3__; Lib_IntVector_Intrinsics_vec128 v010 = k[4U]; Lib_IntVector_Intrinsics_vec128 v110 = k[5U]; Lib_IntVector_Intrinsics_vec128 v210 = k[6U]; Lib_IntVector_Intrinsics_vec128 v310 = k[7U]; Lib_IntVector_Intrinsics_vec128 v0_0 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v010, v110); Lib_IntVector_Intrinsics_vec128 v1_0 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v010, v110); Lib_IntVector_Intrinsics_vec128 v2_0 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v210, v310); Lib_IntVector_Intrinsics_vec128 v3_0 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v210, v310); Lib_IntVector_Intrinsics_vec128 v0__0 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_0, v2_0); Lib_IntVector_Intrinsics_vec128 v1__0 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_0, v2_0); Lib_IntVector_Intrinsics_vec128 v2__0 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_0, v3_0); Lib_IntVector_Intrinsics_vec128 v3__0 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_0, v3_0); Lib_IntVector_Intrinsics_vec128 v4 = v0__0; Lib_IntVector_Intrinsics_vec128 v5 = v1__0; Lib_IntVector_Intrinsics_vec128 v6 = v2__0; Lib_IntVector_Intrinsics_vec128 v7 = v3__0; Lib_IntVector_Intrinsics_vec128 v011 = k[8U]; Lib_IntVector_Intrinsics_vec128 v111 = k[9U]; Lib_IntVector_Intrinsics_vec128 v211 = k[10U]; Lib_IntVector_Intrinsics_vec128 v311 = k[11U]; Lib_IntVector_Intrinsics_vec128 v0_1 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v011, v111); Lib_IntVector_Intrinsics_vec128 v1_1 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v011, v111); Lib_IntVector_Intrinsics_vec128 v2_1 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v211, v311); Lib_IntVector_Intrinsics_vec128 v3_1 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v211, v311); Lib_IntVector_Intrinsics_vec128 v0__1 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_1, v2_1); Lib_IntVector_Intrinsics_vec128 v1__1 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_1, v2_1); Lib_IntVector_Intrinsics_vec128 v2__1 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_1, v3_1); Lib_IntVector_Intrinsics_vec128 v3__1 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_1, v3_1); Lib_IntVector_Intrinsics_vec128 v8 = v0__1; Lib_IntVector_Intrinsics_vec128 v9 = v1__1; Lib_IntVector_Intrinsics_vec128 v10 = v2__1; Lib_IntVector_Intrinsics_vec128 v11 = v3__1; Lib_IntVector_Intrinsics_vec128 v01 = k[12U]; Lib_IntVector_Intrinsics_vec128 v120 = k[13U]; Lib_IntVector_Intrinsics_vec128 v21 = k[14U]; Lib_IntVector_Intrinsics_vec128 v31 = k[15U]; Lib_IntVector_Intrinsics_vec128 v0_2 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v01, v120); Lib_IntVector_Intrinsics_vec128 v1_2 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v01, v120); Lib_IntVector_Intrinsics_vec128 v2_2 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v21, v31); Lib_IntVector_Intrinsics_vec128 v3_2 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v21, v31); Lib_IntVector_Intrinsics_vec128 v0__2 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_2, v2_2); Lib_IntVector_Intrinsics_vec128 v1__2 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_2, v2_2); Lib_IntVector_Intrinsics_vec128 v2__2 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_2, v3_2); Lib_IntVector_Intrinsics_vec128 v3__2 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_2, v3_2); Lib_IntVector_Intrinsics_vec128 v12 = v0__2; Lib_IntVector_Intrinsics_vec128 v13 = v1__2; Lib_IntVector_Intrinsics_vec128 v14 = v2__2; Lib_IntVector_Intrinsics_vec128 v15 = v3__2; k[0U] = v0; k[1U] = v4; k[2U] = v8; k[3U] = v12; k[4U] = v1; k[5U] = v5; k[6U] = v9; k[7U] = v13; k[8U] = v2; k[9U] = v6; k[10U] = v10; k[11U] = v14; k[12U] = v3; k[13U] = v7; k[14U] = v11; k[15U] = v15; { uint32_t i0; for (i0 = (uint32_t)0U; i0 < (uint32_t)16U; i0++) { Lib_IntVector_Intrinsics_vec128 x = Lib_IntVector_Intrinsics_vec128_load32_le(uu____1 + i0 * (uint32_t)16U); Lib_IntVector_Intrinsics_vec128 y = Lib_IntVector_Intrinsics_vec128_xor(x, k[i0]); Lib_IntVector_Intrinsics_vec128_store32_le(uu____0 + i0 * (uint32_t)16U, y); } } } } } if (rem1 > (uint32_t)0U) { uint8_t *uu____2 = out + nb * (uint32_t)256U; uint8_t *uu____3 = cipher + nb * (uint32_t)256U; uint8_t plain[256U] = { 0U }; memcpy(plain, uu____3, rem * sizeof (uint8_t)); { Lib_IntVector_Intrinsics_vec128 k[16U]; { uint32_t _i; for (_i = 0U; _i < (uint32_t)16U; ++_i) k[_i] = Lib_IntVector_Intrinsics_vec128_zero; } chacha20_core_128(k, ctx, nb); { Lib_IntVector_Intrinsics_vec128 v00 = k[0U]; Lib_IntVector_Intrinsics_vec128 v16 = k[1U]; Lib_IntVector_Intrinsics_vec128 v20 = k[2U]; Lib_IntVector_Intrinsics_vec128 v30 = k[3U]; Lib_IntVector_Intrinsics_vec128 v0_ = Lib_IntVector_Intrinsics_vec128_interleave_low32(v00, v16); Lib_IntVector_Intrinsics_vec128 v1_ = Lib_IntVector_Intrinsics_vec128_interleave_high32(v00, v16); Lib_IntVector_Intrinsics_vec128 v2_ = Lib_IntVector_Intrinsics_vec128_interleave_low32(v20, v30); Lib_IntVector_Intrinsics_vec128 v3_ = Lib_IntVector_Intrinsics_vec128_interleave_high32(v20, v30); Lib_IntVector_Intrinsics_vec128 v0__ = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_, v2_); Lib_IntVector_Intrinsics_vec128 v1__ = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_, v2_); Lib_IntVector_Intrinsics_vec128 v2__ = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_, v3_); Lib_IntVector_Intrinsics_vec128 v3__ = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_, v3_); Lib_IntVector_Intrinsics_vec128 v0 = v0__; Lib_IntVector_Intrinsics_vec128 v1 = v1__; Lib_IntVector_Intrinsics_vec128 v2 = v2__; Lib_IntVector_Intrinsics_vec128 v3 = v3__; Lib_IntVector_Intrinsics_vec128 v010 = k[4U]; Lib_IntVector_Intrinsics_vec128 v110 = k[5U]; Lib_IntVector_Intrinsics_vec128 v210 = k[6U]; Lib_IntVector_Intrinsics_vec128 v310 = k[7U]; Lib_IntVector_Intrinsics_vec128 v0_0 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v010, v110); Lib_IntVector_Intrinsics_vec128 v1_0 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v010, v110); Lib_IntVector_Intrinsics_vec128 v2_0 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v210, v310); Lib_IntVector_Intrinsics_vec128 v3_0 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v210, v310); Lib_IntVector_Intrinsics_vec128 v0__0 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_0, v2_0); Lib_IntVector_Intrinsics_vec128 v1__0 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_0, v2_0); Lib_IntVector_Intrinsics_vec128 v2__0 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_0, v3_0); Lib_IntVector_Intrinsics_vec128 v3__0 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_0, v3_0); Lib_IntVector_Intrinsics_vec128 v4 = v0__0; Lib_IntVector_Intrinsics_vec128 v5 = v1__0; Lib_IntVector_Intrinsics_vec128 v6 = v2__0; Lib_IntVector_Intrinsics_vec128 v7 = v3__0; Lib_IntVector_Intrinsics_vec128 v011 = k[8U]; Lib_IntVector_Intrinsics_vec128 v111 = k[9U]; Lib_IntVector_Intrinsics_vec128 v211 = k[10U]; Lib_IntVector_Intrinsics_vec128 v311 = k[11U]; Lib_IntVector_Intrinsics_vec128 v0_1 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v011, v111); Lib_IntVector_Intrinsics_vec128 v1_1 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v011, v111); Lib_IntVector_Intrinsics_vec128 v2_1 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v211, v311); Lib_IntVector_Intrinsics_vec128 v3_1 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v211, v311); Lib_IntVector_Intrinsics_vec128 v0__1 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_1, v2_1); Lib_IntVector_Intrinsics_vec128 v1__1 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_1, v2_1); Lib_IntVector_Intrinsics_vec128 v2__1 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_1, v3_1); Lib_IntVector_Intrinsics_vec128 v3__1 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_1, v3_1); Lib_IntVector_Intrinsics_vec128 v8 = v0__1; Lib_IntVector_Intrinsics_vec128 v9 = v1__1; Lib_IntVector_Intrinsics_vec128 v10 = v2__1; Lib_IntVector_Intrinsics_vec128 v11 = v3__1; Lib_IntVector_Intrinsics_vec128 v01 = k[12U]; Lib_IntVector_Intrinsics_vec128 v120 = k[13U]; Lib_IntVector_Intrinsics_vec128 v21 = k[14U]; Lib_IntVector_Intrinsics_vec128 v31 = k[15U]; Lib_IntVector_Intrinsics_vec128 v0_2 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v01, v120); Lib_IntVector_Intrinsics_vec128 v1_2 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v01, v120); Lib_IntVector_Intrinsics_vec128 v2_2 = Lib_IntVector_Intrinsics_vec128_interleave_low32(v21, v31); Lib_IntVector_Intrinsics_vec128 v3_2 = Lib_IntVector_Intrinsics_vec128_interleave_high32(v21, v31); Lib_IntVector_Intrinsics_vec128 v0__2 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v0_2, v2_2); Lib_IntVector_Intrinsics_vec128 v1__2 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v0_2, v2_2); Lib_IntVector_Intrinsics_vec128 v2__2 = Lib_IntVector_Intrinsics_vec128_interleave_low64(v1_2, v3_2); Lib_IntVector_Intrinsics_vec128 v3__2 = Lib_IntVector_Intrinsics_vec128_interleave_high64(v1_2, v3_2); Lib_IntVector_Intrinsics_vec128 v12 = v0__2; Lib_IntVector_Intrinsics_vec128 v13 = v1__2; Lib_IntVector_Intrinsics_vec128 v14 = v2__2; Lib_IntVector_Intrinsics_vec128 v15 = v3__2; k[0U] = v0; k[1U] = v4; k[2U] = v8; k[3U] = v12; k[4U] = v1; k[5U] = v5; k[6U] = v9; k[7U] = v13; k[8U] = v2; k[9U] = v6; k[10U] = v10; k[11U] = v14; k[12U] = v3; k[13U] = v7; k[14U] = v11; k[15U] = v15; { uint32_t i; for (i = (uint32_t)0U; i < (uint32_t)16U; i++) { Lib_IntVector_Intrinsics_vec128 x = Lib_IntVector_Intrinsics_vec128_load32_le(plain + i * (uint32_t)16U); Lib_IntVector_Intrinsics_vec128 y = Lib_IntVector_Intrinsics_vec128_xor(x, k[i]); Lib_IntVector_Intrinsics_vec128_store32_le(plain + i * (uint32_t)16U, y); } } memcpy(uu____2, plain, rem * sizeof (uint8_t)); } } } } }
389858.c
#include "nix.h" ssize_t console_read(void *buf, size_t n) { return cdev_read(buf, n, uart_getc); } ssize_t console_write(const void *buf, size_t n) { return cdev_write(buf, n, uart_putc); }
70052.c
/* * Copyright (c) 2012-2013 The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * This file was originally distributed by Qualcomm Atheros, Inc. * under proprietary terms before Copyright ownership was assigned * to the Linux Foundation. */ /**========================================================================= \file vos_threads.c \brief virtual Operating System Services (vOSS) Threading APIs ========================================================================*/ /* $Header$ */ /*-------------------------------------------------------------------------- Include Files ------------------------------------------------------------------------*/ #include <vos_threads.h> #include <vos_trace.h> #include <linux/jiffies.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/interrupt.h> #if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 14, 0)) #include <linux/sched/signal.h> #endif /*-------------------------------------------------------------------------- Preprocessor definitions and constants ------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------- Type declarations ------------------------------------------------------------------------*/ /*------------------------------------------------------------------------- Function declarations and documenation ------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- \brief vos_sleep() - sleep The \a vos_sleep() function suspends the execution of the current thread until the specified time out interval elapses. \param msInterval - the number of milliseconds to suspend the current thread. A value of 0 may or may not cause the current thread to yield. \return Nothing. \sa --------------------------------------------------------------------------*/ v_VOID_t vos_sleep( v_U32_t msInterval ) { if (in_interrupt()) { VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR, "%s cannot be called from interrupt context!!!", __func__); return; } msleep_interruptible(msInterval); } /*---------------------------------------------------------------------------- \brief vos_sleep_us() - sleep The \a vos_sleep_us() function suspends the execution of the current thread until the specified time out interval elapses. \param usInterval - the number of microseconds to suspend the current thread. A value of 0 may or may not cause the current thread to yield. \return Nothing. \sa --------------------------------------------------------------------------*/ v_VOID_t vos_sleep_us( v_U32_t usInterval ) { unsigned long timeout = usecs_to_jiffies(usInterval) + 1; if (in_interrupt()) { VOS_TRACE(VOS_MODULE_ID_VOSS, VOS_TRACE_LEVEL_ERROR, "%s cannot be called from interrupt context!!!", __func__); return; } while (timeout && !signal_pending(current)) timeout = schedule_timeout_interruptible(timeout); } /*---------------------------------------------------------------------------- \brief vos_busy_wait() - busy wait The \a vos_busy_wait() function places the current thread in busy wait until the specified time out interval elapses. If the interval is greater than 50us on WM, the behaviour is undefined. \param usInterval - the number of microseconds to busy wait. \return Nothing. \sa --------------------------------------------------------------------------*/ v_VOID_t vos_busy_wait( v_U32_t usInterval ) { udelay(usInterval); }
208729.c
/* See LICENSE file for copyright and license details. */ #include "libsimple.h" #ifndef TEST int libsimple_vputenvf(const char *fmt, va_list ap) { va_list ap2; int n, r; char *s, *p; va_copy(ap2, ap); n = vsnprintf(NULL, 0, fmt, ap2); va_end(ap2); if (n < 0) return -1; s = malloc((size_t)n + 1); if (!s) return -1; vsprintf(s, fmt, ap); p = strchr(s, '='); if (p) { *p++ = '\0'; r = setenv(s, p, 1); free(s); } else { r = putenv(s); } return r; } #else #include "test.h" int main(void) { unsetenv("X"); assert(!getenv("X")); unsetenv("Y"); assert(!getenv("Y")); putenvf("X=xyz"); assert(!strcmpnul(getenv("X"), "xyz")); putenvf("Y=xyz"); assert(!strcmpnul(getenv("Y"), "xyz")); putenvf("X=x%sz", "abc"); assert(!strcmpnul(getenv("X"), "xabcz")); putenvf("Y=x%sz", "abc"); assert(!strcmpnul(getenv("Y"), "xabcz")); putenvf("X=%ix%sz%i", 10, "abc", -11); assert(!strcmpnul(getenv("X"), "10xabcz-11")); putenvf("Y=%ix%sz%i", 10, "abc", -11); assert(!strcmpnul(getenv("Y"), "10xabcz-11")); return 0; } #endif
507022.c
/* v3_purp.c */ /* * Written by Dr Stephen N Henson ([email protected]) for the OpenSSL project * 2001. */ /* ==================================================================== * Copyright (c) 1999-2004 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * ([email protected]). This product includes software written by Tim * Hudson ([email protected]). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/x509v3.h> #include <openssl/x509_vfy.h> static void x509v3_cache_extensions(X509 *x); static int check_ssl_ca(const X509 *x); static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x, int ca); static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca); static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca); static int purpose_smime(const X509 *x, int ca); static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x, int ca); static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x, int ca); static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x, int ca); static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x, int ca); static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca); static int ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int ca); static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b); static void xptable_free(X509_PURPOSE *p); static X509_PURPOSE xstandard[] = { {X509_PURPOSE_SSL_CLIENT, X509_TRUST_SSL_CLIENT, 0, check_purpose_ssl_client, "SSL client", "sslclient", NULL}, {X509_PURPOSE_SSL_SERVER, X509_TRUST_SSL_SERVER, 0, check_purpose_ssl_server, "SSL server", "sslserver", NULL}, {X509_PURPOSE_NS_SSL_SERVER, X509_TRUST_SSL_SERVER, 0, check_purpose_ns_ssl_server, "Netscape SSL server", "nssslserver", NULL}, {X509_PURPOSE_SMIME_SIGN, X509_TRUST_EMAIL, 0, check_purpose_smime_sign, "S/MIME signing", "smimesign", NULL}, {X509_PURPOSE_SMIME_ENCRYPT, X509_TRUST_EMAIL, 0, check_purpose_smime_encrypt, "S/MIME encryption", "smimeencrypt", NULL}, {X509_PURPOSE_CRL_SIGN, X509_TRUST_COMPAT, 0, check_purpose_crl_sign, "CRL signing", "crlsign", NULL}, {X509_PURPOSE_ANY, X509_TRUST_DEFAULT, 0, no_check, "Any Purpose", "any", NULL}, {X509_PURPOSE_OCSP_HELPER, X509_TRUST_COMPAT, 0, ocsp_helper, "OCSP helper", "ocsphelper", NULL}, {X509_PURPOSE_TIMESTAMP_SIGN, X509_TRUST_TSA, 0, check_purpose_timestamp_sign, "Time Stamp signing", "timestampsign", NULL}, }; #define X509_PURPOSE_COUNT (sizeof(xstandard)/sizeof(X509_PURPOSE)) static STACK_OF(X509_PURPOSE) *xptable = NULL; static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b) { return (*a)->purpose - (*b)->purpose; } /* * As much as I'd like to make X509_check_purpose use a "const" X509* I * really can't because it does recalculate hashes and do other non-const * things. */ int X509_check_purpose(X509 *x, int id, int ca) { int idx; const X509_PURPOSE *pt; if (!(x->ex_flags & EXFLAG_SET)) { CRYPTO_w_lock(CRYPTO_LOCK_X509); x509v3_cache_extensions(x); CRYPTO_w_unlock(CRYPTO_LOCK_X509); } if (id == -1) return 1; idx = X509_PURPOSE_get_by_id(id); if (idx == -1) return -1; pt = X509_PURPOSE_get0(idx); return pt->check_purpose(pt, x, ca); } int X509_PURPOSE_set(int *p, int purpose) { if (X509_PURPOSE_get_by_id(purpose) == -1) { X509V3err(X509V3_F_X509_PURPOSE_SET, X509V3_R_INVALID_PURPOSE); return 0; } *p = purpose; return 1; } int X509_PURPOSE_get_count(void) { if (!xptable) return X509_PURPOSE_COUNT; return sk_X509_PURPOSE_num(xptable) + X509_PURPOSE_COUNT; } X509_PURPOSE *X509_PURPOSE_get0(int idx) { if (idx < 0) return NULL; if (idx < (int)X509_PURPOSE_COUNT) return xstandard + idx; return sk_X509_PURPOSE_value(xptable, idx - X509_PURPOSE_COUNT); } int X509_PURPOSE_get_by_sname(char *sname) { int i; X509_PURPOSE *xptmp; for (i = 0; i < X509_PURPOSE_get_count(); i++) { xptmp = X509_PURPOSE_get0(i); if (!strcmp(xptmp->sname, sname)) return i; } return -1; } int X509_PURPOSE_get_by_id(int purpose) { X509_PURPOSE tmp; int idx; if ((purpose >= X509_PURPOSE_MIN) && (purpose <= X509_PURPOSE_MAX)) return purpose - X509_PURPOSE_MIN; tmp.purpose = purpose; if (!xptable) return -1; idx = sk_X509_PURPOSE_find(xptable, &tmp); if (idx == -1) return -1; return idx + X509_PURPOSE_COUNT; } int X509_PURPOSE_add(int id, int trust, int flags, int (*ck) (const X509_PURPOSE *, const X509 *, int), char *name, char *sname, void *arg) { int idx; X509_PURPOSE *ptmp; /* * This is set according to what we change: application can't set it */ flags &= ~X509_PURPOSE_DYNAMIC; /* This will always be set for application modified trust entries */ flags |= X509_PURPOSE_DYNAMIC_NAME; /* Get existing entry if any */ idx = X509_PURPOSE_get_by_id(id); /* Need a new entry */ if (idx == -1) { if (!(ptmp = OPENSSL_malloc(sizeof(X509_PURPOSE)))) { X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE); return 0; } ptmp->flags = X509_PURPOSE_DYNAMIC; } else ptmp = X509_PURPOSE_get0(idx); /* OPENSSL_free existing name if dynamic */ if (ptmp->flags & X509_PURPOSE_DYNAMIC_NAME) { OPENSSL_free(ptmp->name); OPENSSL_free(ptmp->sname); } /* dup supplied name */ ptmp->name = BUF_strdup(name); ptmp->sname = BUF_strdup(sname); if (!ptmp->name || !ptmp->sname) { X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE); return 0; } /* Keep the dynamic flag of existing entry */ ptmp->flags &= X509_PURPOSE_DYNAMIC; /* Set all other flags */ ptmp->flags |= flags; ptmp->purpose = id; ptmp->trust = trust; ptmp->check_purpose = ck; ptmp->usr_data = arg; /* If its a new entry manage the dynamic table */ if (idx == -1) { if (!xptable && !(xptable = sk_X509_PURPOSE_new(xp_cmp))) { X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE); return 0; } if (!sk_X509_PURPOSE_push(xptable, ptmp)) { X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE); return 0; } } return 1; } static void xptable_free(X509_PURPOSE *p) { if (!p) return; if (p->flags & X509_PURPOSE_DYNAMIC) { if (p->flags & X509_PURPOSE_DYNAMIC_NAME) { OPENSSL_free(p->name); OPENSSL_free(p->sname); } OPENSSL_free(p); } } void X509_PURPOSE_cleanup(void) { unsigned int i; sk_X509_PURPOSE_pop_free(xptable, xptable_free); for (i = 0; i < X509_PURPOSE_COUNT; i++) xptable_free(xstandard + i); xptable = NULL; } int X509_PURPOSE_get_id(X509_PURPOSE *xp) { return xp->purpose; } char *X509_PURPOSE_get0_name(X509_PURPOSE *xp) { return xp->name; } char *X509_PURPOSE_get0_sname(X509_PURPOSE *xp) { return xp->sname; } int X509_PURPOSE_get_trust(X509_PURPOSE *xp) { return xp->trust; } static int nid_cmp(const int *a, const int *b) { return *a - *b; } DECLARE_OBJ_BSEARCH_CMP_FN(int, int, nid); IMPLEMENT_OBJ_BSEARCH_CMP_FN(int, int, nid); int X509_supported_extension(X509_EXTENSION *ex) { /* * This table is a list of the NIDs of supported extensions: that is * those which are used by the verify process. If an extension is * critical and doesn't appear in this list then the verify process will * normally reject the certificate. The list must be kept in numerical * order because it will be searched using bsearch. */ static const int supported_nids[] = { NID_netscape_cert_type, /* 71 */ NID_key_usage, /* 83 */ NID_subject_alt_name, /* 85 */ NID_basic_constraints, /* 87 */ NID_certificate_policies, /* 89 */ NID_ext_key_usage, /* 126 */ NID_sbgp_ipAddrBlock, /* 290 */ NID_sbgp_autonomousSysNum, /* 291 */ NID_policy_constraints, /* 401 */ NID_proxyCertInfo, /* 663 */ NID_name_constraints, /* 666 */ NID_policy_mappings, /* 747 */ NID_inhibit_any_policy /* 748 */ }; int ex_nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex)); if (ex_nid == NID_undef) return 0; if (OBJ_bsearch_nid(&ex_nid, supported_nids, sizeof(supported_nids) / sizeof(int))) return 1; return 0; } static void setup_dp(X509 *x, DIST_POINT *dp) { X509_NAME *iname = NULL; int i; if (dp->reasons) { if (dp->reasons->length > 0) dp->dp_reasons = dp->reasons->data[0]; if (dp->reasons->length > 1) dp->dp_reasons |= (dp->reasons->data[1] << 8); dp->dp_reasons &= CRLDP_ALL_REASONS; } else dp->dp_reasons = CRLDP_ALL_REASONS; if (!dp->distpoint || (dp->distpoint->type != 1)) return; for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) { GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i); if (gen->type == GEN_DIRNAME) { iname = gen->d.directoryName; break; } } if (!iname) iname = X509_get_issuer_name(x); DIST_POINT_set_dpname(dp->distpoint, iname); } static void setup_crldp(X509 *x) { int i; x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL); for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) setup_dp(x, sk_DIST_POINT_value(x->crldp, i)); } static void x509v3_cache_extensions(X509 *x) { BASIC_CONSTRAINTS *bs; PROXY_CERT_INFO_EXTENSION *pci; ASN1_BIT_STRING *usage; ASN1_BIT_STRING *ns; EXTENDED_KEY_USAGE *extusage; X509_EXTENSION *ex; int i; if (x->ex_flags & EXFLAG_SET) return; X509_digest(x, EVP_sha1(), x->sha1_hash, NULL); /* V1 should mean no extensions ... */ if (!X509_get_version(x)) x->ex_flags |= EXFLAG_V1; /* Handle basic constraints */ if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, NULL, NULL))) { if (bs->ca) x->ex_flags |= EXFLAG_CA; if (bs->pathlen) { if ((bs->pathlen->type == V_ASN1_NEG_INTEGER) || !bs->ca) { x->ex_flags |= EXFLAG_INVALID; x->ex_pathlen = 0; } else x->ex_pathlen = ASN1_INTEGER_get(bs->pathlen); } else x->ex_pathlen = -1; BASIC_CONSTRAINTS_free(bs); x->ex_flags |= EXFLAG_BCONS; } /* Handle proxy certificates */ if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, NULL, NULL))) { if (x->ex_flags & EXFLAG_CA || X509_get_ext_by_NID(x, NID_subject_alt_name, -1) >= 0 || X509_get_ext_by_NID(x, NID_issuer_alt_name, -1) >= 0) { x->ex_flags |= EXFLAG_INVALID; } if (pci->pcPathLengthConstraint) { x->ex_pcpathlen = ASN1_INTEGER_get(pci->pcPathLengthConstraint); } else x->ex_pcpathlen = -1; PROXY_CERT_INFO_EXTENSION_free(pci); x->ex_flags |= EXFLAG_PROXY; } /* Handle key usage */ if ((usage = X509_get_ext_d2i(x, NID_key_usage, NULL, NULL))) { if (usage->length > 0) { x->ex_kusage = usage->data[0]; if (usage->length > 1) x->ex_kusage |= usage->data[1] << 8; } else x->ex_kusage = 0; x->ex_flags |= EXFLAG_KUSAGE; ASN1_BIT_STRING_free(usage); } x->ex_xkusage = 0; if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL))) { x->ex_flags |= EXFLAG_XKUSAGE; for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) { switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) { case NID_server_auth: x->ex_xkusage |= XKU_SSL_SERVER; break; case NID_client_auth: x->ex_xkusage |= XKU_SSL_CLIENT; break; case NID_email_protect: x->ex_xkusage |= XKU_SMIME; break; case NID_code_sign: x->ex_xkusage |= XKU_CODE_SIGN; break; case NID_ms_sgc: case NID_ns_sgc: x->ex_xkusage |= XKU_SGC; break; case NID_OCSP_sign: x->ex_xkusage |= XKU_OCSP_SIGN; break; case NID_time_stamp: x->ex_xkusage |= XKU_TIMESTAMP; break; case NID_dvcs: x->ex_xkusage |= XKU_DVCS; break; case NID_anyExtendedKeyUsage: x->ex_xkusage |= XKU_ANYEKU; break; } } sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free); } if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, NULL, NULL))) { if (ns->length > 0) x->ex_nscert = ns->data[0]; else x->ex_nscert = 0; x->ex_flags |= EXFLAG_NSCERT; ASN1_BIT_STRING_free(ns); } x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, NULL, NULL); x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, NULL, NULL); /* Does subject name match issuer ? */ if (!X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x))) { x->ex_flags |= EXFLAG_SI; /* If SKID matches AKID also indicate self signed */ if (X509_check_akid(x, x->akid) == X509_V_OK) x->ex_flags |= EXFLAG_SS; } x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL); x->nc = X509_get_ext_d2i(x, NID_name_constraints, &i, NULL); if (!x->nc && (i != -1)) x->ex_flags |= EXFLAG_INVALID; setup_crldp(x); x->rfc3779_addr = X509_get_ext_d2i(x, NID_sbgp_ipAddrBlock, NULL, NULL); x->rfc3779_asid = X509_get_ext_d2i(x, NID_sbgp_autonomousSysNum, NULL, NULL); for (i = 0; i < X509_get_ext_count(x); i++) { ex = X509_get_ext(x, i); if (OBJ_obj2nid(X509_EXTENSION_get_object(ex)) == NID_freshest_crl) x->ex_flags |= EXFLAG_FRESHEST; if (!X509_EXTENSION_get_critical(ex)) continue; if (!X509_supported_extension(ex)) { x->ex_flags |= EXFLAG_CRITICAL; break; } } x->ex_flags |= EXFLAG_SET; } /*- * CA checks common to all purposes * return codes: * 0 not a CA * 1 is a CA * 2 basicConstraints absent so "maybe" a CA * 3 basicConstraints absent but self signed V1. * 4 basicConstraints absent but keyUsage present and keyCertSign asserted. */ #define V1_ROOT (EXFLAG_V1|EXFLAG_SS) #define ku_reject(x, usage) \ (((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage))) #define xku_reject(x, usage) \ (((x)->ex_flags & EXFLAG_XKUSAGE) && !((x)->ex_xkusage & (usage))) #define ns_reject(x, usage) \ (((x)->ex_flags & EXFLAG_NSCERT) && !((x)->ex_nscert & (usage))) static int check_ca(const X509 *x) { /* keyUsage if present should allow cert signing */ if (ku_reject(x, KU_KEY_CERT_SIGN)) return 0; if (x->ex_flags & EXFLAG_BCONS) { if (x->ex_flags & EXFLAG_CA) return 1; /* If basicConstraints says not a CA then say so */ else return 0; } else { /* we support V1 roots for... uh, I don't really know why. */ if ((x->ex_flags & V1_ROOT) == V1_ROOT) return 3; /* * If key usage present it must have certSign so tolerate it */ else if (x->ex_flags & EXFLAG_KUSAGE) return 4; /* Older certificates could have Netscape-specific CA types */ else if (x->ex_flags & EXFLAG_NSCERT && x->ex_nscert & NS_ANY_CA) return 5; /* can this still be regarded a CA certificate? I doubt it */ return 0; } } int X509_check_ca(X509 *x) { if (!(x->ex_flags & EXFLAG_SET)) { CRYPTO_w_lock(CRYPTO_LOCK_X509); x509v3_cache_extensions(x); CRYPTO_w_unlock(CRYPTO_LOCK_X509); } return check_ca(x); } /* Check SSL CA: common checks for SSL client and server */ static int check_ssl_ca(const X509 *x) { int ca_ret; ca_ret = check_ca(x); if (!ca_ret) return 0; /* check nsCertType if present */ if (ca_ret != 5 || x->ex_nscert & NS_SSL_CA) return ca_ret; else return 0; } static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x, int ca) { if (xku_reject(x, XKU_SSL_CLIENT)) return 0; if (ca) return check_ssl_ca(x); /* We need to do digital signatures or key agreement */ if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT)) return 0; /* nsCertType if present should allow SSL client use */ if (ns_reject(x, NS_SSL_CLIENT)) return 0; return 1; } /* * Key usage needed for TLS/SSL server: digital signature, encipherment or * key agreement. The ssl code can check this more thoroughly for individual * key types. */ #define KU_TLS \ KU_DIGITAL_SIGNATURE|KU_KEY_ENCIPHERMENT|KU_KEY_AGREEMENT static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca) { if (xku_reject(x, XKU_SSL_SERVER | XKU_SGC)) return 0; if (ca) return check_ssl_ca(x); if (ns_reject(x, NS_SSL_SERVER)) return 0; if (ku_reject(x, KU_TLS)) return 0; return 1; } static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca) { int ret; ret = check_purpose_ssl_server(xp, x, ca); if (!ret || ca) return ret; /* We need to encipher or Netscape complains */ if (ku_reject(x, KU_KEY_ENCIPHERMENT)) return 0; return ret; } /* common S/MIME checks */ static int purpose_smime(const X509 *x, int ca) { if (xku_reject(x, XKU_SMIME)) return 0; if (ca) { int ca_ret; ca_ret = check_ca(x); if (!ca_ret) return 0; /* check nsCertType if present */ if (ca_ret != 5 || x->ex_nscert & NS_SMIME_CA) return ca_ret; else return 0; } if (x->ex_flags & EXFLAG_NSCERT) { if (x->ex_nscert & NS_SMIME) return 1; /* Workaround for some buggy certificates */ if (x->ex_nscert & NS_SSL_CLIENT) return 2; return 0; } return 1; } static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x, int ca) { int ret; ret = purpose_smime(x, ca); if (!ret || ca) return ret; if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION)) return 0; return ret; } static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x, int ca) { int ret; ret = purpose_smime(x, ca); if (!ret || ca) return ret; if (ku_reject(x, KU_KEY_ENCIPHERMENT)) return 0; return ret; } static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x, int ca) { if (ca) { int ca_ret; if ((ca_ret = check_ca(x)) != 2) return ca_ret; else return 0; } if (ku_reject(x, KU_CRL_SIGN)) return 0; return 1; } /* * OCSP helper: this is *not* a full OCSP check. It just checks that each CA * is valid. Additional checks must be made on the chain. */ static int ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int ca) { /* * Must be a valid CA. Should we really support the "I don't know" value * (2)? */ if (ca) return check_ca(x); /* leaf certificate is checked in OCSP_verify() */ return 1; } static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x, int ca) { int i_ext; /* If ca is true we must return if this is a valid CA certificate. */ if (ca) return check_ca(x); /* * Check the optional key usage field: * if Key Usage is present, it must be one of digitalSignature * and/or nonRepudiation (other values are not consistent and shall * be rejected). */ if ((x->ex_flags & EXFLAG_KUSAGE) && ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) || !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)))) return 0; /* Only time stamp key usage is permitted and it's required. */ if (!(x->ex_flags & EXFLAG_XKUSAGE) || x->ex_xkusage != XKU_TIMESTAMP) return 0; /* Extended Key Usage MUST be critical */ i_ext = X509_get_ext_by_NID((X509 *)x, NID_ext_key_usage, -1); if (i_ext >= 0) { X509_EXTENSION *ext = X509_get_ext((X509 *)x, i_ext); if (!X509_EXTENSION_get_critical(ext)) return 0; } return 1; } static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca) { return 1; } /*- * Various checks to see if one certificate issued the second. * This can be used to prune a set of possible issuer certificates * which have been looked up using some simple method such as by * subject name. * These are: * 1. Check issuer_name(subject) == subject_name(issuer) * 2. If akid(subject) exists check it matches issuer * 3. If key_usage(issuer) exists check it supports certificate signing * returns 0 for OK, positive for reason for mismatch, reasons match * codes for X509_verify_cert() */ int X509_check_issued(X509 *issuer, X509 *subject) { if (X509_NAME_cmp(X509_get_subject_name(issuer), X509_get_issuer_name(subject))) return X509_V_ERR_SUBJECT_ISSUER_MISMATCH; x509v3_cache_extensions(issuer); x509v3_cache_extensions(subject); if (subject->akid) { int ret = X509_check_akid(issuer, subject->akid); if (ret != X509_V_OK) return ret; } if (subject->ex_flags & EXFLAG_PROXY) { if (ku_reject(issuer, KU_DIGITAL_SIGNATURE)) return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE; } else if (ku_reject(issuer, KU_KEY_CERT_SIGN)) return X509_V_ERR_KEYUSAGE_NO_CERTSIGN; return X509_V_OK; } int X509_check_akid(X509 *issuer, AUTHORITY_KEYID *akid) { if (!akid) return X509_V_OK; /* Check key ids (if present) */ if (akid->keyid && issuer->skid && ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid)) return X509_V_ERR_AKID_SKID_MISMATCH; /* Check serial number */ if (akid->serial && ASN1_INTEGER_cmp(X509_get_serialNumber(issuer), akid->serial)) return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH; /* Check issuer name */ if (akid->issuer) { /* * Ugh, for some peculiar reason AKID includes SEQUENCE OF * GeneralName. So look for a DirName. There may be more than one but * we only take any notice of the first. */ GENERAL_NAMES *gens; GENERAL_NAME *gen; X509_NAME *nm = NULL; int i; gens = akid->issuer; for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { gen = sk_GENERAL_NAME_value(gens, i); if (gen->type == GEN_DIRNAME) { nm = gen->d.dirn; break; } } if (nm && X509_NAME_cmp(nm, X509_get_issuer_name(issuer))) return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH; } return X509_V_OK; }
520764.c
/** * jacobi-1d-imper.c: This file is part of the PolyBench/C 3.2 test suite. * * * Contact: Louis-Noel Pouchet <[email protected]> * Web address: http://polybench.sourceforge.net */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> #include <polybench.h>\n # 1 "jacobi-1d-imper.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "jacobi-1d-imper.c" # 1 "utilities/polybench.h" 1 # 26 "utilities/polybench.h" # 1 "/usr/include/stdlib.h" 1 3 4 # 61 "/usr/include/stdlib.h" 3 4 # 1 "/usr/include/Availability.h" 1 3 4 # 202 "/usr/include/Availability.h" 3 4 # 1 "/usr/include/AvailabilityInternal.h" 1 3 4 # 203 "/usr/include/Availability.h" 2 3 4 # 62 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/include/_types.h" 1 3 4 # 27 "/usr/include/_types.h" 3 4 # 1 "/usr/include/sys/_types.h" 1 3 4 # 32 "/usr/include/sys/_types.h" 3 4 # 1 "/usr/include/sys/cdefs.h" 1 3 4 # 587 "/usr/include/sys/cdefs.h" 3 4 # 1 "/usr/include/sys/_symbol_aliasing.h" 1 3 4 # 588 "/usr/include/sys/cdefs.h" 2 3 4 # 653 "/usr/include/sys/cdefs.h" 3 4 # 1 "/usr/include/sys/_posix_availability.h" 1 3 4 # 654 "/usr/include/sys/cdefs.h" 2 3 4 # 33 "/usr/include/sys/_types.h" 2 3 4 # 1 "/usr/include/machine/_types.h" 1 3 4 # 32 "/usr/include/machine/_types.h" 3 4 # 1 "/usr/include/i386/_types.h" 1 3 4 # 37 "/usr/include/i386/_types.h" 3 4 # 37 "/usr/include/i386/_types.h" 3 4 typedef signed char __int8_t; typedef unsigned char __uint8_t; typedef short __int16_t; typedef unsigned short __uint16_t; typedef int __int32_t; typedef unsigned int __uint32_t; typedef long long __int64_t; typedef unsigned long long __uint64_t; typedef long __darwin_intptr_t; typedef unsigned int __darwin_natural_t; # 70 "/usr/include/i386/_types.h" 3 4 typedef int __darwin_ct_rune_t; typedef union { char __mbstate8[128]; long long _mbstateL; } __mbstate_t; typedef __mbstate_t __darwin_mbstate_t; typedef long int __darwin_ptrdiff_t; typedef long unsigned int __darwin_size_t; typedef __builtin_va_list __darwin_va_list; typedef int __darwin_wchar_t; typedef __darwin_wchar_t __darwin_rune_t; typedef int __darwin_wint_t; typedef unsigned long __darwin_clock_t; typedef __uint32_t __darwin_socklen_t; typedef long __darwin_ssize_t; typedef long __darwin_time_t; # 33 "/usr/include/machine/_types.h" 2 3 4 # 34 "/usr/include/sys/_types.h" 2 3 4 # 55 "/usr/include/sys/_types.h" 3 4 typedef __int64_t __darwin_blkcnt_t; typedef __int32_t __darwin_blksize_t; typedef __int32_t __darwin_dev_t; typedef unsigned int __darwin_fsblkcnt_t; typedef unsigned int __darwin_fsfilcnt_t; typedef __uint32_t __darwin_gid_t; typedef __uint32_t __darwin_id_t; typedef __uint64_t __darwin_ino64_t; typedef __darwin_ino64_t __darwin_ino_t; typedef __darwin_natural_t __darwin_mach_port_name_t; typedef __darwin_mach_port_name_t __darwin_mach_port_t; typedef __uint16_t __darwin_mode_t; typedef __int64_t __darwin_off_t; typedef __int32_t __darwin_pid_t; typedef __uint32_t __darwin_sigset_t; typedef __int32_t __darwin_suseconds_t; typedef __uint32_t __darwin_uid_t; typedef __uint32_t __darwin_useconds_t; typedef unsigned char __darwin_uuid_t[16]; typedef char __darwin_uuid_string_t[37]; # 1 "/usr/include/sys/_pthread/_pthread_types.h" 1 3 4 # 57 "/usr/include/sys/_pthread/_pthread_types.h" 3 4 struct __darwin_pthread_handler_rec { void (*__routine)(void *); void *__arg; struct __darwin_pthread_handler_rec *__next; }; struct _opaque_pthread_attr_t { long __sig; char __opaque[56]; }; struct _opaque_pthread_cond_t { long __sig; char __opaque[40]; }; struct _opaque_pthread_condattr_t { long __sig; char __opaque[8]; }; struct _opaque_pthread_mutex_t { long __sig; char __opaque[56]; }; struct _opaque_pthread_mutexattr_t { long __sig; char __opaque[8]; }; struct _opaque_pthread_once_t { long __sig; char __opaque[8]; }; struct _opaque_pthread_rwlock_t { long __sig; char __opaque[192]; }; struct _opaque_pthread_rwlockattr_t { long __sig; char __opaque[16]; }; struct _opaque_pthread_t { long __sig; struct __darwin_pthread_handler_rec *__cleanup_stack; char __opaque[8176]; }; typedef struct _opaque_pthread_attr_t __darwin_pthread_attr_t; typedef struct _opaque_pthread_cond_t __darwin_pthread_cond_t; typedef struct _opaque_pthread_condattr_t __darwin_pthread_condattr_t; typedef unsigned long __darwin_pthread_key_t; typedef struct _opaque_pthread_mutex_t __darwin_pthread_mutex_t; typedef struct _opaque_pthread_mutexattr_t __darwin_pthread_mutexattr_t; typedef struct _opaque_pthread_once_t __darwin_pthread_once_t; typedef struct _opaque_pthread_rwlock_t __darwin_pthread_rwlock_t; typedef struct _opaque_pthread_rwlockattr_t __darwin_pthread_rwlockattr_t; typedef struct _opaque_pthread_t *__darwin_pthread_t; # 81 "/usr/include/sys/_types.h" 2 3 4 # 28 "/usr/include/_types.h" 2 3 4 # 40 "/usr/include/_types.h" 3 4 typedef int __darwin_nl_item; typedef int __darwin_wctrans_t; typedef __uint32_t __darwin_wctype_t; # 64 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/include/sys/wait.h" 1 3 4 # 79 "/usr/include/sys/wait.h" 3 4 typedef enum { P_ALL, P_PID, P_PGID } idtype_t; # 1 "/usr/include/sys/_types/_pid_t.h" 1 3 4 # 31 "/usr/include/sys/_types/_pid_t.h" 3 4 typedef __darwin_pid_t pid_t; # 90 "/usr/include/sys/wait.h" 2 3 4 # 1 "/usr/include/sys/_types/_id_t.h" 1 3 4 # 31 "/usr/include/sys/_types/_id_t.h" 3 4 typedef __darwin_id_t id_t; # 91 "/usr/include/sys/wait.h" 2 3 4 # 109 "/usr/include/sys/wait.h" 3 4 # 1 "/usr/include/sys/signal.h" 1 3 4 # 73 "/usr/include/sys/signal.h" 3 4 # 1 "/usr/include/sys/appleapiopts.h" 1 3 4 # 74 "/usr/include/sys/signal.h" 2 3 4 # 82 "/usr/include/sys/signal.h" 3 4 # 1 "/usr/include/machine/signal.h" 1 3 4 # 32 "/usr/include/machine/signal.h" 3 4 # 1 "/usr/include/i386/signal.h" 1 3 4 # 39 "/usr/include/i386/signal.h" 3 4 typedef int sig_atomic_t; # 33 "/usr/include/machine/signal.h" 2 3 4 # 83 "/usr/include/sys/signal.h" 2 3 4 # 146 "/usr/include/sys/signal.h" 3 4 # 1 "/usr/include/machine/_mcontext.h" 1 3 4 # 29 "/usr/include/machine/_mcontext.h" 3 4 # 1 "/usr/include/i386/_mcontext.h" 1 3 4 # 34 "/usr/include/i386/_mcontext.h" 3 4 # 1 "/usr/include/mach/machine/_structs.h" 1 3 4 # 33 "/usr/include/mach/machine/_structs.h" 3 4 # 1 "/usr/include/mach/i386/_structs.h" 1 3 4 # 36 "/usr/include/mach/i386/_structs.h" 3 4 # 1 "/usr/include/machine/types.h" 1 3 4 # 35 "/usr/include/machine/types.h" 3 4 # 1 "/usr/include/i386/types.h" 1 3 4 # 76 "/usr/include/i386/types.h" 3 4 # 1 "/usr/include/sys/_types/_int8_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_int8_t.h" 3 4 typedef signed char int8_t; # 77 "/usr/include/i386/types.h" 2 3 4 # 1 "/usr/include/sys/_types/_int16_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_int16_t.h" 3 4 typedef short int16_t; # 78 "/usr/include/i386/types.h" 2 3 4 # 1 "/usr/include/sys/_types/_int32_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_int32_t.h" 3 4 typedef int int32_t; # 79 "/usr/include/i386/types.h" 2 3 4 # 1 "/usr/include/sys/_types/_int64_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_int64_t.h" 3 4 typedef long long int64_t; # 80 "/usr/include/i386/types.h" 2 3 4 # 1 "/usr/include/sys/_types/_u_int8_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_u_int8_t.h" 3 4 typedef unsigned char u_int8_t; # 82 "/usr/include/i386/types.h" 2 3 4 # 1 "/usr/include/sys/_types/_u_int16_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_u_int16_t.h" 3 4 typedef unsigned short u_int16_t; # 83 "/usr/include/i386/types.h" 2 3 4 # 1 "/usr/include/sys/_types/_u_int32_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_u_int32_t.h" 3 4 typedef unsigned int u_int32_t; # 84 "/usr/include/i386/types.h" 2 3 4 # 1 "/usr/include/sys/_types/_u_int64_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_u_int64_t.h" 3 4 typedef unsigned long long u_int64_t; # 85 "/usr/include/i386/types.h" 2 3 4 typedef int64_t register_t; # 1 "/usr/include/sys/_types/_intptr_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_intptr_t.h" 3 4 # 1 "/usr/include/machine/types.h" 1 3 4 # 31 "/usr/include/sys/_types/_intptr_t.h" 2 3 4 typedef __darwin_intptr_t intptr_t; # 93 "/usr/include/i386/types.h" 2 3 4 # 1 "/usr/include/sys/_types/_uintptr_t.h" 1 3 4 # 30 "/usr/include/sys/_types/_uintptr_t.h" 3 4 typedef unsigned long uintptr_t; # 94 "/usr/include/i386/types.h" 2 3 4 typedef u_int64_t user_addr_t; typedef u_int64_t user_size_t; typedef int64_t user_ssize_t; typedef int64_t user_long_t; typedef u_int64_t user_ulong_t; typedef int64_t user_time_t; typedef int64_t user_off_t; typedef u_int64_t syscall_arg_t; # 36 "/usr/include/machine/types.h" 2 3 4 # 37 "/usr/include/mach/i386/_structs.h" 2 3 4 # 46 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_i386_thread_state { unsigned int __eax; unsigned int __ebx; unsigned int __ecx; unsigned int __edx; unsigned int __edi; unsigned int __esi; unsigned int __ebp; unsigned int __esp; unsigned int __ss; unsigned int __eflags; unsigned int __eip; unsigned int __cs; unsigned int __ds; unsigned int __es; unsigned int __fs; unsigned int __gs; }; # 92 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_fp_control { unsigned short __invalid :1, __denorm :1, __zdiv :1, __ovrfl :1, __undfl :1, __precis :1, :2, __pc :2, __rc :2, :1, :3; }; typedef struct __darwin_fp_control __darwin_fp_control_t; # 150 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_fp_status { unsigned short __invalid :1, __denorm :1, __zdiv :1, __ovrfl :1, __undfl :1, __precis :1, __stkflt :1, __errsumm :1, __c0 :1, __c1 :1, __c2 :1, __tos :3, __c3 :1, __busy :1; }; typedef struct __darwin_fp_status __darwin_fp_status_t; # 194 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_mmst_reg { char __mmst_reg[10]; char __mmst_rsrv[6]; }; # 213 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_xmm_reg { char __xmm_reg[16]; }; # 229 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_ymm_reg { char __ymm_reg[32]; }; # 245 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_zmm_reg { char __zmm_reg[64]; }; # 259 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_opmask_reg { char __opmask_reg[8]; }; # 281 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_i386_float_state { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; char __fpu_rsrv4[14*16]; int __fpu_reserved1; }; struct __darwin_i386_avx_state { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; char __fpu_rsrv4[14*16]; int __fpu_reserved1; char __avx_reserved1[64]; struct __darwin_xmm_reg __fpu_ymmh0; struct __darwin_xmm_reg __fpu_ymmh1; struct __darwin_xmm_reg __fpu_ymmh2; struct __darwin_xmm_reg __fpu_ymmh3; struct __darwin_xmm_reg __fpu_ymmh4; struct __darwin_xmm_reg __fpu_ymmh5; struct __darwin_xmm_reg __fpu_ymmh6; struct __darwin_xmm_reg __fpu_ymmh7; }; struct __darwin_i386_avx512_state { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; char __fpu_rsrv4[14*16]; int __fpu_reserved1; char __avx_reserved1[64]; struct __darwin_xmm_reg __fpu_ymmh0; struct __darwin_xmm_reg __fpu_ymmh1; struct __darwin_xmm_reg __fpu_ymmh2; struct __darwin_xmm_reg __fpu_ymmh3; struct __darwin_xmm_reg __fpu_ymmh4; struct __darwin_xmm_reg __fpu_ymmh5; struct __darwin_xmm_reg __fpu_ymmh6; struct __darwin_xmm_reg __fpu_ymmh7; struct __darwin_opmask_reg __fpu_k0; struct __darwin_opmask_reg __fpu_k1; struct __darwin_opmask_reg __fpu_k2; struct __darwin_opmask_reg __fpu_k3; struct __darwin_opmask_reg __fpu_k4; struct __darwin_opmask_reg __fpu_k5; struct __darwin_opmask_reg __fpu_k6; struct __darwin_opmask_reg __fpu_k7; struct __darwin_ymm_reg __fpu_zmmh0; struct __darwin_ymm_reg __fpu_zmmh1; struct __darwin_ymm_reg __fpu_zmmh2; struct __darwin_ymm_reg __fpu_zmmh3; struct __darwin_ymm_reg __fpu_zmmh4; struct __darwin_ymm_reg __fpu_zmmh5; struct __darwin_ymm_reg __fpu_zmmh6; struct __darwin_ymm_reg __fpu_zmmh7; }; # 575 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_i386_exception_state { __uint16_t __trapno; __uint16_t __cpu; __uint32_t __err; __uint32_t __faultvaddr; }; # 595 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_x86_debug_state32 { unsigned int __dr0; unsigned int __dr1; unsigned int __dr2; unsigned int __dr3; unsigned int __dr4; unsigned int __dr5; unsigned int __dr6; unsigned int __dr7; }; # 627 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_x86_thread_state64 { __uint64_t __rax; __uint64_t __rbx; __uint64_t __rcx; __uint64_t __rdx; __uint64_t __rdi; __uint64_t __rsi; __uint64_t __rbp; __uint64_t __rsp; __uint64_t __r8; __uint64_t __r9; __uint64_t __r10; __uint64_t __r11; __uint64_t __r12; __uint64_t __r13; __uint64_t __r14; __uint64_t __r15; __uint64_t __rip; __uint64_t __rflags; __uint64_t __cs; __uint64_t __fs; __uint64_t __gs; }; # 682 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_x86_float_state64 { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; struct __darwin_xmm_reg __fpu_xmm8; struct __darwin_xmm_reg __fpu_xmm9; struct __darwin_xmm_reg __fpu_xmm10; struct __darwin_xmm_reg __fpu_xmm11; struct __darwin_xmm_reg __fpu_xmm12; struct __darwin_xmm_reg __fpu_xmm13; struct __darwin_xmm_reg __fpu_xmm14; struct __darwin_xmm_reg __fpu_xmm15; char __fpu_rsrv4[6*16]; int __fpu_reserved1; }; struct __darwin_x86_avx_state64 { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; struct __darwin_xmm_reg __fpu_xmm8; struct __darwin_xmm_reg __fpu_xmm9; struct __darwin_xmm_reg __fpu_xmm10; struct __darwin_xmm_reg __fpu_xmm11; struct __darwin_xmm_reg __fpu_xmm12; struct __darwin_xmm_reg __fpu_xmm13; struct __darwin_xmm_reg __fpu_xmm14; struct __darwin_xmm_reg __fpu_xmm15; char __fpu_rsrv4[6*16]; int __fpu_reserved1; char __avx_reserved1[64]; struct __darwin_xmm_reg __fpu_ymmh0; struct __darwin_xmm_reg __fpu_ymmh1; struct __darwin_xmm_reg __fpu_ymmh2; struct __darwin_xmm_reg __fpu_ymmh3; struct __darwin_xmm_reg __fpu_ymmh4; struct __darwin_xmm_reg __fpu_ymmh5; struct __darwin_xmm_reg __fpu_ymmh6; struct __darwin_xmm_reg __fpu_ymmh7; struct __darwin_xmm_reg __fpu_ymmh8; struct __darwin_xmm_reg __fpu_ymmh9; struct __darwin_xmm_reg __fpu_ymmh10; struct __darwin_xmm_reg __fpu_ymmh11; struct __darwin_xmm_reg __fpu_ymmh12; struct __darwin_xmm_reg __fpu_ymmh13; struct __darwin_xmm_reg __fpu_ymmh14; struct __darwin_xmm_reg __fpu_ymmh15; }; struct __darwin_x86_avx512_state64 { int __fpu_reserved[2]; struct __darwin_fp_control __fpu_fcw; struct __darwin_fp_status __fpu_fsw; __uint8_t __fpu_ftw; __uint8_t __fpu_rsrv1; __uint16_t __fpu_fop; __uint32_t __fpu_ip; __uint16_t __fpu_cs; __uint16_t __fpu_rsrv2; __uint32_t __fpu_dp; __uint16_t __fpu_ds; __uint16_t __fpu_rsrv3; __uint32_t __fpu_mxcsr; __uint32_t __fpu_mxcsrmask; struct __darwin_mmst_reg __fpu_stmm0; struct __darwin_mmst_reg __fpu_stmm1; struct __darwin_mmst_reg __fpu_stmm2; struct __darwin_mmst_reg __fpu_stmm3; struct __darwin_mmst_reg __fpu_stmm4; struct __darwin_mmst_reg __fpu_stmm5; struct __darwin_mmst_reg __fpu_stmm6; struct __darwin_mmst_reg __fpu_stmm7; struct __darwin_xmm_reg __fpu_xmm0; struct __darwin_xmm_reg __fpu_xmm1; struct __darwin_xmm_reg __fpu_xmm2; struct __darwin_xmm_reg __fpu_xmm3; struct __darwin_xmm_reg __fpu_xmm4; struct __darwin_xmm_reg __fpu_xmm5; struct __darwin_xmm_reg __fpu_xmm6; struct __darwin_xmm_reg __fpu_xmm7; struct __darwin_xmm_reg __fpu_xmm8; struct __darwin_xmm_reg __fpu_xmm9; struct __darwin_xmm_reg __fpu_xmm10; struct __darwin_xmm_reg __fpu_xmm11; struct __darwin_xmm_reg __fpu_xmm12; struct __darwin_xmm_reg __fpu_xmm13; struct __darwin_xmm_reg __fpu_xmm14; struct __darwin_xmm_reg __fpu_xmm15; char __fpu_rsrv4[6*16]; int __fpu_reserved1; char __avx_reserved1[64]; struct __darwin_xmm_reg __fpu_ymmh0; struct __darwin_xmm_reg __fpu_ymmh1; struct __darwin_xmm_reg __fpu_ymmh2; struct __darwin_xmm_reg __fpu_ymmh3; struct __darwin_xmm_reg __fpu_ymmh4; struct __darwin_xmm_reg __fpu_ymmh5; struct __darwin_xmm_reg __fpu_ymmh6; struct __darwin_xmm_reg __fpu_ymmh7; struct __darwin_xmm_reg __fpu_ymmh8; struct __darwin_xmm_reg __fpu_ymmh9; struct __darwin_xmm_reg __fpu_ymmh10; struct __darwin_xmm_reg __fpu_ymmh11; struct __darwin_xmm_reg __fpu_ymmh12; struct __darwin_xmm_reg __fpu_ymmh13; struct __darwin_xmm_reg __fpu_ymmh14; struct __darwin_xmm_reg __fpu_ymmh15; struct __darwin_opmask_reg __fpu_k0; struct __darwin_opmask_reg __fpu_k1; struct __darwin_opmask_reg __fpu_k2; struct __darwin_opmask_reg __fpu_k3; struct __darwin_opmask_reg __fpu_k4; struct __darwin_opmask_reg __fpu_k5; struct __darwin_opmask_reg __fpu_k6; struct __darwin_opmask_reg __fpu_k7; struct __darwin_ymm_reg __fpu_zmmh0; struct __darwin_ymm_reg __fpu_zmmh1; struct __darwin_ymm_reg __fpu_zmmh2; struct __darwin_ymm_reg __fpu_zmmh3; struct __darwin_ymm_reg __fpu_zmmh4; struct __darwin_ymm_reg __fpu_zmmh5; struct __darwin_ymm_reg __fpu_zmmh6; struct __darwin_ymm_reg __fpu_zmmh7; struct __darwin_ymm_reg __fpu_zmmh8; struct __darwin_ymm_reg __fpu_zmmh9; struct __darwin_ymm_reg __fpu_zmmh10; struct __darwin_ymm_reg __fpu_zmmh11; struct __darwin_ymm_reg __fpu_zmmh12; struct __darwin_ymm_reg __fpu_zmmh13; struct __darwin_ymm_reg __fpu_zmmh14; struct __darwin_ymm_reg __fpu_zmmh15; struct __darwin_zmm_reg __fpu_zmm16; struct __darwin_zmm_reg __fpu_zmm17; struct __darwin_zmm_reg __fpu_zmm18; struct __darwin_zmm_reg __fpu_zmm19; struct __darwin_zmm_reg __fpu_zmm20; struct __darwin_zmm_reg __fpu_zmm21; struct __darwin_zmm_reg __fpu_zmm22; struct __darwin_zmm_reg __fpu_zmm23; struct __darwin_zmm_reg __fpu_zmm24; struct __darwin_zmm_reg __fpu_zmm25; struct __darwin_zmm_reg __fpu_zmm26; struct __darwin_zmm_reg __fpu_zmm27; struct __darwin_zmm_reg __fpu_zmm28; struct __darwin_zmm_reg __fpu_zmm29; struct __darwin_zmm_reg __fpu_zmm30; struct __darwin_zmm_reg __fpu_zmm31; }; # 1140 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_x86_exception_state64 { __uint16_t __trapno; __uint16_t __cpu; __uint32_t __err; __uint64_t __faultvaddr; }; # 1160 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_x86_debug_state64 { __uint64_t __dr0; __uint64_t __dr1; __uint64_t __dr2; __uint64_t __dr3; __uint64_t __dr4; __uint64_t __dr5; __uint64_t __dr6; __uint64_t __dr7; }; # 1188 "/usr/include/mach/i386/_structs.h" 3 4 struct __darwin_x86_cpmu_state64 { __uint64_t __ctrs[16]; }; # 34 "/usr/include/mach/machine/_structs.h" 2 3 4 # 35 "/usr/include/i386/_mcontext.h" 2 3 4 struct __darwin_mcontext32 { struct __darwin_i386_exception_state __es; struct __darwin_i386_thread_state __ss; struct __darwin_i386_float_state __fs; }; struct __darwin_mcontext_avx32 { struct __darwin_i386_exception_state __es; struct __darwin_i386_thread_state __ss; struct __darwin_i386_avx_state __fs; }; struct __darwin_mcontext_avx512_32 { struct __darwin_i386_exception_state __es; struct __darwin_i386_thread_state __ss; struct __darwin_i386_avx512_state __fs; }; # 97 "/usr/include/i386/_mcontext.h" 3 4 struct __darwin_mcontext64 { struct __darwin_x86_exception_state64 __es; struct __darwin_x86_thread_state64 __ss; struct __darwin_x86_float_state64 __fs; }; struct __darwin_mcontext_avx64 { struct __darwin_x86_exception_state64 __es; struct __darwin_x86_thread_state64 __ss; struct __darwin_x86_avx_state64 __fs; }; struct __darwin_mcontext_avx512_64 { struct __darwin_x86_exception_state64 __es; struct __darwin_x86_thread_state64 __ss; struct __darwin_x86_avx512_state64 __fs; }; # 156 "/usr/include/i386/_mcontext.h" 3 4 typedef struct __darwin_mcontext64 *mcontext_t; # 30 "/usr/include/machine/_mcontext.h" 2 3 4 # 147 "/usr/include/sys/signal.h" 2 3 4 # 1 "/usr/include/sys/_pthread/_pthread_attr_t.h" 1 3 4 # 31 "/usr/include/sys/_pthread/_pthread_attr_t.h" 3 4 typedef __darwin_pthread_attr_t pthread_attr_t; # 149 "/usr/include/sys/signal.h" 2 3 4 # 1 "/usr/include/sys/_types/_sigaltstack.h" 1 3 4 # 42 "/usr/include/sys/_types/_sigaltstack.h" 3 4 struct __darwin_sigaltstack { void *ss_sp; __darwin_size_t ss_size; int ss_flags; }; typedef struct __darwin_sigaltstack stack_t; # 151 "/usr/include/sys/signal.h" 2 3 4 # 1 "/usr/include/sys/_types/_ucontext.h" 1 3 4 # 39 "/usr/include/sys/_types/_ucontext.h" 3 4 # 1 "/usr/include/machine/_mcontext.h" 1 3 4 # 40 "/usr/include/sys/_types/_ucontext.h" 2 3 4 struct __darwin_ucontext { int uc_onstack; __darwin_sigset_t uc_sigmask; struct __darwin_sigaltstack uc_stack; struct __darwin_ucontext *uc_link; __darwin_size_t uc_mcsize; struct __darwin_mcontext64 *uc_mcontext; }; typedef struct __darwin_ucontext ucontext_t; # 152 "/usr/include/sys/signal.h" 2 3 4 # 1 "/usr/include/sys/_types/_sigset_t.h" 1 3 4 # 31 "/usr/include/sys/_types/_sigset_t.h" 3 4 typedef __darwin_sigset_t sigset_t; # 155 "/usr/include/sys/signal.h" 2 3 4 # 1 "/usr/include/sys/_types/_size_t.h" 1 3 4 # 31 "/usr/include/sys/_types/_size_t.h" 3 4 typedef __darwin_size_t size_t; # 156 "/usr/include/sys/signal.h" 2 3 4 # 1 "/usr/include/sys/_types/_uid_t.h" 1 3 4 # 31 "/usr/include/sys/_types/_uid_t.h" 3 4 typedef __darwin_uid_t uid_t; # 157 "/usr/include/sys/signal.h" 2 3 4 union sigval { int sival_int; void *sival_ptr; }; struct sigevent { int sigev_notify; int sigev_signo; union sigval sigev_value; void (*sigev_notify_function)(union sigval); pthread_attr_t *sigev_notify_attributes; }; typedef struct __siginfo { int si_signo; int si_errno; int si_code; pid_t si_pid; uid_t si_uid; int si_status; void *si_addr; union sigval si_value; long si_band; unsigned long __pad[7]; } siginfo_t; # 269 "/usr/include/sys/signal.h" 3 4 union __sigaction_u { void (*__sa_handler)(int); void (*__sa_sigaction)(int, struct __siginfo *, void *); }; struct __sigaction { union __sigaction_u __sigaction_u; void (*sa_tramp)(void *, int, int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; }; struct sigaction { union __sigaction_u __sigaction_u; sigset_t sa_mask; int sa_flags; }; # 331 "/usr/include/sys/signal.h" 3 4 typedef void (*sig_t)(int); # 348 "/usr/include/sys/signal.h" 3 4 struct sigvec { void (*sv_handler)(int); int sv_mask; int sv_flags; }; # 367 "/usr/include/sys/signal.h" 3 4 struct sigstack { char *ss_sp; int ss_onstack; }; # 389 "/usr/include/sys/signal.h" 3 4 void (*signal(int, void (*)(int)))(int); # 110 "/usr/include/sys/wait.h" 2 3 4 # 1 "/usr/include/sys/resource.h" 1 3 4 # 72 "/usr/include/sys/resource.h" 3 4 # 1 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include/stdint.h" 1 3 4 # 9 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include/stdint.h" 3 4 # 1 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 1 3 4 # 32 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 3 4 # 1 "/usr/include/_types/_uint8_t.h" 1 3 4 # 31 "/usr/include/_types/_uint8_t.h" 3 4 typedef unsigned char uint8_t; # 33 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 2 3 4 # 1 "/usr/include/_types/_uint16_t.h" 1 3 4 # 31 "/usr/include/_types/_uint16_t.h" 3 4 typedef unsigned short uint16_t; # 34 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 2 3 4 # 1 "/usr/include/_types/_uint32_t.h" 1 3 4 # 31 "/usr/include/_types/_uint32_t.h" 3 4 typedef unsigned int uint32_t; # 35 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 2 3 4 # 1 "/usr/include/_types/_uint64_t.h" 1 3 4 # 31 "/usr/include/_types/_uint64_t.h" 3 4 typedef unsigned long long uint64_t; # 36 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 2 3 4 typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; # 67 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 3 4 # 1 "/usr/include/_types/_intmax_t.h" 1 3 4 # 32 "/usr/include/_types/_intmax_t.h" 3 4 typedef long int intmax_t; # 68 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 2 3 4 # 1 "/usr/include/_types/_uintmax_t.h" 1 3 4 # 32 "/usr/include/_types/_uintmax_t.h" 3 4 typedef long unsigned int uintmax_t; # 69 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include-fixed/stdint.h" 2 3 4 # 10 "/opt/local/lib/gcc6/gcc/x86_64-apple-darwin16/6.2.0/include/stdint.h" 2 3 4 # 73 "/usr/include/sys/resource.h" 2 3 4 # 1 "/usr/include/sys/_types/_timeval.h" 1 3 4 # 34 "/usr/include/sys/_types/_timeval.h" 3 4 struct timeval { __darwin_time_t tv_sec; __darwin_suseconds_t tv_usec; }; # 81 "/usr/include/sys/resource.h" 2 3 4 # 89 "/usr/include/sys/resource.h" 3 4 typedef __uint64_t rlim_t; # 152 "/usr/include/sys/resource.h" 3 4 struct rusage { struct timeval ru_utime; struct timeval ru_stime; # 163 "/usr/include/sys/resource.h" 3 4 long ru_maxrss; long ru_ixrss; long ru_idrss; long ru_isrss; long ru_minflt; long ru_majflt; long ru_nswap; long ru_inblock; long ru_oublock; long ru_msgsnd; long ru_msgrcv; long ru_nsignals; long ru_nvcsw; long ru_nivcsw; }; # 193 "/usr/include/sys/resource.h" 3 4 typedef void *rusage_info_t; struct rusage_info_v0 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; }; struct rusage_info_v1 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; uint64_t ri_child_user_time; uint64_t ri_child_system_time; uint64_t ri_child_pkg_idle_wkups; uint64_t ri_child_interrupt_wkups; uint64_t ri_child_pageins; uint64_t ri_child_elapsed_abstime; }; struct rusage_info_v2 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; uint64_t ri_child_user_time; uint64_t ri_child_system_time; uint64_t ri_child_pkg_idle_wkups; uint64_t ri_child_interrupt_wkups; uint64_t ri_child_pageins; uint64_t ri_child_elapsed_abstime; uint64_t ri_diskio_bytesread; uint64_t ri_diskio_byteswritten; }; struct rusage_info_v3 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; uint64_t ri_child_user_time; uint64_t ri_child_system_time; uint64_t ri_child_pkg_idle_wkups; uint64_t ri_child_interrupt_wkups; uint64_t ri_child_pageins; uint64_t ri_child_elapsed_abstime; uint64_t ri_diskio_bytesread; uint64_t ri_diskio_byteswritten; uint64_t ri_cpu_time_qos_default; uint64_t ri_cpu_time_qos_maintenance; uint64_t ri_cpu_time_qos_background; uint64_t ri_cpu_time_qos_utility; uint64_t ri_cpu_time_qos_legacy; uint64_t ri_cpu_time_qos_user_initiated; uint64_t ri_cpu_time_qos_user_interactive; uint64_t ri_billed_system_time; uint64_t ri_serviced_system_time; }; struct rusage_info_v4 { uint8_t ri_uuid[16]; uint64_t ri_user_time; uint64_t ri_system_time; uint64_t ri_pkg_idle_wkups; uint64_t ri_interrupt_wkups; uint64_t ri_pageins; uint64_t ri_wired_size; uint64_t ri_resident_size; uint64_t ri_phys_footprint; uint64_t ri_proc_start_abstime; uint64_t ri_proc_exit_abstime; uint64_t ri_child_user_time; uint64_t ri_child_system_time; uint64_t ri_child_pkg_idle_wkups; uint64_t ri_child_interrupt_wkups; uint64_t ri_child_pageins; uint64_t ri_child_elapsed_abstime; uint64_t ri_diskio_bytesread; uint64_t ri_diskio_byteswritten; uint64_t ri_cpu_time_qos_default; uint64_t ri_cpu_time_qos_maintenance; uint64_t ri_cpu_time_qos_background; uint64_t ri_cpu_time_qos_utility; uint64_t ri_cpu_time_qos_legacy; uint64_t ri_cpu_time_qos_user_initiated; uint64_t ri_cpu_time_qos_user_interactive; uint64_t ri_billed_system_time; uint64_t ri_serviced_system_time; uint64_t ri_logical_writes; uint64_t ri_lifetime_max_phys_footprint; uint64_t ri_instructions; uint64_t ri_cycles; uint64_t ri_billed_energy; uint64_t ri_serviced_energy; uint64_t ri_unused[2]; }; typedef struct rusage_info_v4 rusage_info_current; # 365 "/usr/include/sys/resource.h" 3 4 struct rlimit { rlim_t rlim_cur; rlim_t rlim_max; }; # 393 "/usr/include/sys/resource.h" 3 4 struct proc_rlimit_control_wakeupmon { uint32_t wm_flags; int32_t wm_rate; }; # 424 "/usr/include/sys/resource.h" 3 4 int getpriority(int, id_t); int getiopolicy_np(int, int) ; int getrlimit(int, struct rlimit *) __asm("_" "getrlimit" ); int getrusage(int, struct rusage *); int setpriority(int, id_t, int); int setiopolicy_np(int, int, int) ; int setrlimit(int, const struct rlimit *) __asm("_" "setrlimit" ); # 111 "/usr/include/sys/wait.h" 2 3 4 # 186 "/usr/include/sys/wait.h" 3 4 # 1 "/usr/include/machine/endian.h" 1 3 4 # 35 "/usr/include/machine/endian.h" 3 4 # 1 "/usr/include/i386/endian.h" 1 3 4 # 99 "/usr/include/i386/endian.h" 3 4 # 1 "/usr/include/sys/_endian.h" 1 3 4 # 130 "/usr/include/sys/_endian.h" 3 4 # 1 "/usr/include/libkern/_OSByteOrder.h" 1 3 4 # 66 "/usr/include/libkern/_OSByteOrder.h" 3 4 # 1 "/usr/include/libkern/i386/_OSByteOrder.h" 1 3 4 # 44 "/usr/include/libkern/i386/_OSByteOrder.h" 3 4 static inline __uint16_t _OSSwapInt16( __uint16_t _data ) { return ((__uint16_t)((_data << 8) | (_data >> 8))); } static inline __uint32_t _OSSwapInt32( __uint32_t _data ) { __asm__ ("bswap %0" : "+r" (_data)); return _data; } # 91 "/usr/include/libkern/i386/_OSByteOrder.h" 3 4 static inline __uint64_t _OSSwapInt64( __uint64_t _data ) { __asm__ ("bswap %0" : "+r" (_data)); return _data; } # 67 "/usr/include/libkern/_OSByteOrder.h" 2 3 4 # 131 "/usr/include/sys/_endian.h" 2 3 4 # 100 "/usr/include/i386/endian.h" 2 3 4 # 36 "/usr/include/machine/endian.h" 2 3 4 # 187 "/usr/include/sys/wait.h" 2 3 4 union wait { int w_status; struct { unsigned int w_Termsig:7, w_Coredump:1, w_Retcode:8, w_Filler:16; } w_T; struct { unsigned int w_Stopval:8, w_Stopsig:8, w_Filler:16; } w_S; }; # 247 "/usr/include/sys/wait.h" 3 4 pid_t wait(int *) __asm("_" "wait" ); pid_t waitpid(pid_t, int *, int) __asm("_" "waitpid" ); int waitid(idtype_t, id_t, siginfo_t *, int) __asm("_" "waitid" ); pid_t wait3(int *, int, struct rusage *); pid_t wait4(pid_t, int *, int, struct rusage *); # 66 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/include/alloca.h" 1 3 4 # 31 "/usr/include/alloca.h" 3 4 void *alloca(size_t); # 68 "/usr/include/stdlib.h" 2 3 4 # 76 "/usr/include/stdlib.h" 3 4 # 1 "/usr/include/sys/_types/_ct_rune_t.h" 1 3 4 # 32 "/usr/include/sys/_types/_ct_rune_t.h" 3 4 typedef __darwin_ct_rune_t ct_rune_t; # 77 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/include/sys/_types/_rune_t.h" 1 3 4 # 31 "/usr/include/sys/_types/_rune_t.h" 3 4 typedef __darwin_rune_t rune_t; # 78 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/include/sys/_types/_wchar_t.h" 1 3 4 # 34 "/usr/include/sys/_types/_wchar_t.h" 3 4 typedef __darwin_wchar_t wchar_t; # 81 "/usr/include/stdlib.h" 2 3 4 typedef struct { int quot; int rem; } div_t; typedef struct { long quot; long rem; } ldiv_t; typedef struct { long long quot; long long rem; } lldiv_t; # 1 "/usr/include/sys/_types/_null.h" 1 3 4 # 100 "/usr/include/stdlib.h" 2 3 4 # 117 "/usr/include/stdlib.h" 3 4 extern int __mb_cur_max; # 135 "/usr/include/stdlib.h" 3 4 void abort(void) __attribute__((noreturn)); int abs(int) __attribute__((const)); int atexit(void (* )(void)); double atof(const char *); int atoi(const char *); long atol(const char *); long long atoll(const char *); void *bsearch(const void *__key, const void *__base, size_t __nel, size_t __width, int (* __compar)(const void *, const void *)); void *calloc(size_t __count, size_t __size) __attribute__((__warn_unused_result__)) __attribute__((alloc_size(1,2))); div_t div(int, int) __attribute__((const)); void exit(int) __attribute__((noreturn)); void free(void *); char *getenv(const char *); long labs(long) __attribute__((const)); ldiv_t ldiv(long, long) __attribute__((const)); long long llabs(long long); lldiv_t lldiv(long long, long long); void *malloc(size_t __size) __attribute__((__warn_unused_result__)) __attribute__((alloc_size(1))); int mblen(const char *__s, size_t __n); size_t mbstowcs(wchar_t * restrict , const char * restrict, size_t); int mbtowc(wchar_t * restrict, const char * restrict, size_t); int posix_memalign(void **__memptr, size_t __alignment, size_t __size) ; void qsort(void *__base, size_t __nel, size_t __width, int (* __compar)(const void *, const void *)); int rand(void) ; void *realloc(void *__ptr, size_t __size) __attribute__((__warn_unused_result__)) __attribute__((alloc_size(2))); void srand(unsigned) ; double strtod(const char *, char **) __asm("_" "strtod" ); float strtof(const char *, char **) __asm("_" "strtof" ); long strtol(const char *__str, char **__endptr, int __base); long double strtold(const char *, char **); long long strtoll(const char *__str, char **__endptr, int __base); unsigned long strtoul(const char *__str, char **__endptr, int __base); unsigned long long strtoull(const char *__str, char **__endptr, int __base); # 192 "/usr/include/stdlib.h" 3 4 int system(const char *) __asm("_" "system" ); size_t wcstombs(char * restrict, const wchar_t * restrict, size_t); int wctomb(char *, wchar_t); void _Exit(int) __attribute__((noreturn)); long a64l(const char *); double drand48(void); char *ecvt(double, int, int *restrict, int *restrict); double erand48(unsigned short[3]); char *fcvt(double, int, int *restrict, int *restrict); char *gcvt(double, int, char *); int getsubopt(char **, char * const *, char **); int grantpt(int); char *initstate(unsigned, char *, size_t); long jrand48(unsigned short[3]) ; char *l64a(long); void lcong48(unsigned short[7]); long lrand48(void) ; char *mktemp(char *); int mkstemp(char *); long mrand48(void) ; long nrand48(unsigned short[3]) ; int posix_openpt(int); char *ptsname(int); int putenv(char *) __asm("_" "putenv" ); long random(void) ; int rand_r(unsigned *) ; char *realpath(const char * restrict, char * restrict) __asm("_" "realpath" "$DARWIN_EXTSN"); unsigned short *seed48(unsigned short[3]); int setenv(const char * __name, const char * __value, int __overwrite) __asm("_" "setenv" ); void setkey(const char *) __asm("_" "setkey" ); char *setstate(const char *); void srand48(long); void srandom(unsigned); int unlockpt(int); int unsetenv(const char *) __asm("_" "unsetenv" ); # 261 "/usr/include/stdlib.h" 3 4 # 1 "/usr/include/sys/_types/_dev_t.h" 1 3 4 # 31 "/usr/include/sys/_types/_dev_t.h" 3 4 typedef __darwin_dev_t dev_t; # 262 "/usr/include/stdlib.h" 2 3 4 # 1 "/usr/include/sys/_types/_mode_t.h" 1 3 4 # 31 "/usr/include/sys/_types/_mode_t.h" 3 4 typedef __darwin_mode_t mode_t; # 263 "/usr/include/stdlib.h" 2 3 4 uint32_t arc4random(void); void arc4random_addrandom(unsigned char * , int ) void arc4random_buf(void * __buf, size_t __nbytes) ; void arc4random_stir(void); uint32_t arc4random_uniform(uint32_t __upper_bound) ; char *cgetcap(char *, const char *, int); int cgetclose(void); int cgetent(char **, char **, const char *); int cgetfirst(char **, char **); int cgetmatch(const char *, const char *); int cgetnext(char **, char **); int cgetnum(char *, const char *, long *); int cgetset(const char *); int cgetstr(char *, const char *, char **); int cgetustr(char *, const char *, char **); int daemon(int, int) __asm("_" "daemon" "$1050") __attribute__((deprecated("Use posix_spawn APIs instead."))) ; char *devname(dev_t, mode_t); char *devname_r(dev_t, mode_t, char *buf, int len); char *getbsize(int *, long *); int getloadavg(double [], int); const char *getprogname(void); int heapsort(void *__base, size_t __nel, size_t __width, int (* __compar)(const void *, const void *)); int mergesort(void *__base, size_t __nel, size_t __width, int (* __compar)(const void *, const void *)); void psort(void *__base, size_t __nel, size_t __width, int (* __compar)(const void *, const void *)) ; void psort_r(void *__base, size_t __nel, size_t __width, void *, int (* __compar)(void *, const void *, const void *)) ; void qsort_r(void *__base, size_t __nel, size_t __width, void *, int (* __compar)(void *, const void *, const void *)); int radixsort(const unsigned char **__base, int __nel, const unsigned char *__table, unsigned __endbyte); void setprogname(const char *); int sradixsort(const unsigned char **__base, int __nel, const unsigned char *__table, unsigned __endbyte); void sranddev(void); void srandomdev(void); void *reallocf(void *__ptr, size_t __size) __attribute__((alloc_size(2))); long long strtoq(const char *__str, char **__endptr, int __base); unsigned long long strtouq(const char *__str, char **__endptr, int __base); extern char *suboptarg; void *valloc(size_t) __attribute__((alloc_size(1))); # 27 "utilities/polybench.h" 2 # 176 "utilities/polybench.h" # 176 "utilities/polybench.h" extern double polybench_program_total_flops; extern void polybench_timer_start(); extern void polybench_timer_stop(); extern void polybench_timer_print(); extern void polybench_timer_start(); extern void polybench_timer_stop(); extern void polybench_timer_print(); # 199 "utilities/polybench.h" extern void* polybench_alloc_data(unsigned long long int n, int elt_size); # 4 "jacobi-1d-imper.c" 2 # 1 "./stencils/jacobi-1d-imper/jacobi-1d-imper.h" 1 # 8 "jacobi-1d-imper.c" 2 static void init_array (int n, double A[10000 + 0], double B[10000 + 0]) { int i; for (i = 0; i < n; i++) { A[i] = ((double) i+ 2) / n; B[i] = ((double) i+ 3) / n; } } static void print_array(int n, double A[10000 + 0]) { int i; for (i = 0; i < n; i++) { fprintf(stderr, "%0.2lf ", A[i]); if (i % 20 == 0) fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } static void kernel_jacobi_1d_imper(int tsteps, int n, double A[10000 + 0], double B[10000 + 0]) { int t, i, j; #pragma scop for (t = 0; t < tsteps; t++) { for (i = 1; i < n - 1; i++) B[i] = 0.33333 * (A[i-1] + A[i] + A[i + 1]); for (j = 1; j < n - 1; j++) A[j] = B[j]; } #pragma endscop } int main(int argc, char** argv) { int n = 10000; int tsteps = 100; double (*A)[10000 + 0]; A = (double(*)[10000 + 0])polybench_alloc_data (10000 + 0, sizeof(double));; double (*B)[10000 + 0]; B = (double(*)[10000 + 0])polybench_alloc_data (10000 + 0, sizeof(double));; init_array (n, *A, *B); polybench_timer_start();; kernel_jacobi_1d_imper (tsteps, n, *A, *B); polybench_timer_stop();; polybench_timer_print();; if (argc > 42 && ! strcmp(argv[0], "")) print_array(n, *A); free((void*)A);; free((void*)B);; return 0; }
57714.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2019, Vladimir Oltean <[email protected]> */ #include <linux/spi/spi.h> #include "sja1105.h" /* The adjfine API clamps ppb between [-32,768,000, 32,768,000], and * therefore scaled_ppm between [-2,147,483,648, 2,147,483,647]. * Set the maximum supported ppb to a round value smaller than the maximum. * * Percentually speaking, this is a +/- 0.032x adjustment of the * free-running counter (0.968x to 1.032x). */ #define SJA1105_MAX_ADJ_PPB 32000000 #define SJA1105_SIZE_PTP_CMD 4 /* PTPSYNCTS has no interrupt or update mechanism, because the intended * hardware use case is for the timestamp to be collected synchronously, * immediately after the CAS_MASTER SJA1105 switch has performed a CASSYNC * one-shot toggle (no return to level) on the PTP_CLK pin. When used as a * generic extts source, the PTPSYNCTS register needs polling and a comparison * with the old value. The polling interval is configured as the Nyquist rate * of a signal with 50% duty cycle and 1Hz frequency, which is sadly all that * this hardware can do (but may be enough for some setups). Anything of higher * frequency than 1 Hz will be lost, since there is no timestamp FIFO. */ #define SJA1105_EXTTS_INTERVAL (HZ / 6) /* This range is actually +/- SJA1105_MAX_ADJ_PPB * divided by 1000 (ppb -> ppm) and with a 16-bit * "fractional" part (actually fixed point). * | * v * Convert scaled_ppm from the +/- ((10^6) << 16) range * into the +/- (1 << 31) range. * * This forgoes a "ppb" numeric representation (up to NSEC_PER_SEC) * and defines the scaling factor between scaled_ppm and the actual * frequency adjustments of the PHC. * * ptpclkrate = scaled_ppm * 2^31 / (10^6 * 2^16) * simplifies to * ptpclkrate = scaled_ppm * 2^9 / 5^6 */ #define SJA1105_CC_MULT_NUM (1 << 9) #define SJA1105_CC_MULT_DEM 15625 #define SJA1105_CC_MULT 0x80000000 enum sja1105_ptp_clk_mode { PTP_ADD_MODE = 1, PTP_SET_MODE = 0, }; #define extts_to_data(t) \ container_of((t), struct sja1105_ptp_data, extts_timer) #define ptp_caps_to_data(d) \ container_of((d), struct sja1105_ptp_data, caps) #define ptp_data_to_sja1105(d) \ container_of((d), struct sja1105_private, ptp_data) /* Must be called only with priv->tagger_data.state bit * SJA1105_HWTS_RX_EN cleared */ static int sja1105_change_rxtstamping(struct sja1105_private *priv, bool on) { struct sja1105_ptp_data *ptp_data = &priv->ptp_data; struct sja1105_general_params_entry *general_params; struct sja1105_table *table; table = &priv->static_config.tables[BLK_IDX_GENERAL_PARAMS]; general_params = table->entries; general_params->send_meta1 = on; general_params->send_meta0 = on; /* Initialize the meta state machine to a known state */ if (priv->tagger_data.stampable_skb) { kfree_skb(priv->tagger_data.stampable_skb); priv->tagger_data.stampable_skb = NULL; } ptp_cancel_worker_sync(ptp_data->clock); skb_queue_purge(&ptp_data->skb_rxtstamp_queue); return sja1105_static_config_reload(priv, SJA1105_RX_HWTSTAMPING); } int sja1105_hwtstamp_set(struct dsa_switch *ds, int port, struct ifreq *ifr) { struct sja1105_private *priv = ds->priv; struct hwtstamp_config config; bool rx_on; int rc; if (copy_from_user(&config, ifr->ifr_data, sizeof(config))) return -EFAULT; switch (config.tx_type) { case HWTSTAMP_TX_OFF: priv->ports[port].hwts_tx_en = false; break; case HWTSTAMP_TX_ON: priv->ports[port].hwts_tx_en = true; break; default: return -ERANGE; } switch (config.rx_filter) { case HWTSTAMP_FILTER_NONE: rx_on = false; break; default: rx_on = true; break; } if (rx_on != test_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state)) { clear_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state); rc = sja1105_change_rxtstamping(priv, rx_on); if (rc < 0) { dev_err(ds->dev, "Failed to change RX timestamping: %d\n", rc); return rc; } if (rx_on) set_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state); } if (copy_to_user(ifr->ifr_data, &config, sizeof(config))) return -EFAULT; return 0; } int sja1105_hwtstamp_get(struct dsa_switch *ds, int port, struct ifreq *ifr) { struct sja1105_private *priv = ds->priv; struct hwtstamp_config config; config.flags = 0; if (priv->ports[port].hwts_tx_en) config.tx_type = HWTSTAMP_TX_ON; else config.tx_type = HWTSTAMP_TX_OFF; if (test_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state)) config.rx_filter = HWTSTAMP_FILTER_PTP_V2_L2_EVENT; else config.rx_filter = HWTSTAMP_FILTER_NONE; return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ? -EFAULT : 0; } int sja1105_get_ts_info(struct dsa_switch *ds, int port, struct ethtool_ts_info *info) { struct sja1105_private *priv = ds->priv; struct sja1105_ptp_data *ptp_data = &priv->ptp_data; /* Called during cleanup */ if (!ptp_data->clock) return -ENODEV; info->so_timestamping = SOF_TIMESTAMPING_TX_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_RAW_HARDWARE; info->tx_types = (1 << HWTSTAMP_TX_OFF) | (1 << HWTSTAMP_TX_ON); info->rx_filters = (1 << HWTSTAMP_FILTER_NONE) | (1 << HWTSTAMP_FILTER_PTP_V2_L2_EVENT); info->phc_index = ptp_clock_index(ptp_data->clock); return 0; } void sja1105et_ptp_cmd_packing(u8 *buf, struct sja1105_ptp_cmd *cmd, enum packing_op op) { const int size = SJA1105_SIZE_PTP_CMD; /* No need to keep this as part of the structure */ u64 valid = 1; sja1105_packing(buf, &valid, 31, 31, size, op); sja1105_packing(buf, &cmd->ptpstrtsch, 30, 30, size, op); sja1105_packing(buf, &cmd->ptpstopsch, 29, 29, size, op); sja1105_packing(buf, &cmd->startptpcp, 28, 28, size, op); sja1105_packing(buf, &cmd->stopptpcp, 27, 27, size, op); sja1105_packing(buf, &cmd->resptp, 2, 2, size, op); sja1105_packing(buf, &cmd->corrclk4ts, 1, 1, size, op); sja1105_packing(buf, &cmd->ptpclkadd, 0, 0, size, op); } void sja1105pqrs_ptp_cmd_packing(u8 *buf, struct sja1105_ptp_cmd *cmd, enum packing_op op) { const int size = SJA1105_SIZE_PTP_CMD; /* No need to keep this as part of the structure */ u64 valid = 1; sja1105_packing(buf, &valid, 31, 31, size, op); sja1105_packing(buf, &cmd->ptpstrtsch, 30, 30, size, op); sja1105_packing(buf, &cmd->ptpstopsch, 29, 29, size, op); sja1105_packing(buf, &cmd->startptpcp, 28, 28, size, op); sja1105_packing(buf, &cmd->stopptpcp, 27, 27, size, op); sja1105_packing(buf, &cmd->resptp, 3, 3, size, op); sja1105_packing(buf, &cmd->corrclk4ts, 2, 2, size, op); sja1105_packing(buf, &cmd->ptpclkadd, 0, 0, size, op); } int sja1105_ptp_commit(struct dsa_switch *ds, struct sja1105_ptp_cmd *cmd, sja1105_spi_rw_mode_t rw) { const struct sja1105_private *priv = ds->priv; const struct sja1105_regs *regs = priv->info->regs; u8 buf[SJA1105_SIZE_PTP_CMD] = {0}; int rc; if (rw == SPI_WRITE) priv->info->ptp_cmd_packing(buf, cmd, PACK); rc = sja1105_xfer_buf(priv, rw, regs->ptp_control, buf, SJA1105_SIZE_PTP_CMD); if (rw == SPI_READ) priv->info->ptp_cmd_packing(buf, cmd, UNPACK); return rc; } /* The switch returns partial timestamps (24 bits for SJA1105 E/T, which wrap * around in 0.135 seconds, and 32 bits for P/Q/R/S, wrapping around in 34.35 * seconds). * * This receives the RX or TX MAC timestamps, provided by hardware as * the lower bits of the cycle counter, sampled at the time the timestamp was * collected. * * To reconstruct into a full 64-bit-wide timestamp, the cycle counter is * read and the high-order bits are filled in. * * Must be called within one wraparound period of the partial timestamp since * it was generated by the MAC. */ static u64 sja1105_tstamp_reconstruct(struct dsa_switch *ds, u64 now, u64 ts_partial) { struct sja1105_private *priv = ds->priv; u64 partial_tstamp_mask = CYCLECOUNTER_MASK(priv->info->ptp_ts_bits); u64 ts_reconstructed; ts_reconstructed = (now & ~partial_tstamp_mask) | ts_partial; /* Check lower bits of current cycle counter against the timestamp. * If the current cycle counter is lower than the partial timestamp, * then wraparound surely occurred and must be accounted for. */ if ((now & partial_tstamp_mask) <= ts_partial) ts_reconstructed -= (partial_tstamp_mask + 1); return ts_reconstructed; } /* Reads the SPI interface for an egress timestamp generated by the switch * for frames sent using management routes. * * SJA1105 E/T layout of the 4-byte SPI payload: * * 31 23 15 7 0 * | | | | | * +-----+-----+-----+ ^ * ^ | * | | * 24-bit timestamp Update bit * * * SJA1105 P/Q/R/S layout of the 8-byte SPI payload: * * 31 23 15 7 0 63 55 47 39 32 * | | | | | | | | | | * ^ +-----+-----+-----+-----+ * | ^ * | | * Update bit 32-bit timestamp * * Notice that the update bit is in the same place. * To have common code for E/T and P/Q/R/S for reading the timestamp, * we need to juggle with the offset and the bit indices. */ static int sja1105_ptpegr_ts_poll(struct dsa_switch *ds, int port, u64 *ts) { struct sja1105_private *priv = ds->priv; const struct sja1105_regs *regs = priv->info->regs; int tstamp_bit_start, tstamp_bit_end; int timeout = 10; u8 packed_buf[8]; u64 update; int rc; do { rc = sja1105_xfer_buf(priv, SPI_READ, regs->ptpegr_ts[port], packed_buf, priv->info->ptpegr_ts_bytes); if (rc < 0) return rc; sja1105_unpack(packed_buf, &update, 0, 0, priv->info->ptpegr_ts_bytes); if (update) break; usleep_range(10, 50); } while (--timeout); if (!timeout) return -ETIMEDOUT; /* Point the end bit to the second 32-bit word on P/Q/R/S, * no-op on E/T. */ tstamp_bit_end = (priv->info->ptpegr_ts_bytes - 4) * 8; /* Shift the 24-bit timestamp on E/T to be collected from 31:8. * No-op on P/Q/R/S. */ tstamp_bit_end += 32 - priv->info->ptp_ts_bits; tstamp_bit_start = tstamp_bit_end + priv->info->ptp_ts_bits - 1; *ts = 0; sja1105_unpack(packed_buf, ts, tstamp_bit_start, tstamp_bit_end, priv->info->ptpegr_ts_bytes); return 0; } /* Caller must hold ptp_data->lock */ static int sja1105_ptpclkval_read(struct sja1105_private *priv, u64 *ticks, struct ptp_system_timestamp *ptp_sts) { const struct sja1105_regs *regs = priv->info->regs; return sja1105_xfer_u64(priv, SPI_READ, regs->ptpclkval, ticks, ptp_sts); } /* Caller must hold ptp_data->lock */ static int sja1105_ptpclkval_write(struct sja1105_private *priv, u64 ticks, struct ptp_system_timestamp *ptp_sts) { const struct sja1105_regs *regs = priv->info->regs; return sja1105_xfer_u64(priv, SPI_WRITE, regs->ptpclkval, &ticks, ptp_sts); } static void sja1105_extts_poll(struct sja1105_private *priv) { struct sja1105_ptp_data *ptp_data = &priv->ptp_data; const struct sja1105_regs *regs = priv->info->regs; struct ptp_clock_event event; u64 ptpsyncts = 0; int rc; rc = sja1105_xfer_u64(priv, SPI_READ, regs->ptpsyncts, &ptpsyncts, NULL); if (rc < 0) dev_err_ratelimited(priv->ds->dev, "Failed to read PTPSYNCTS: %d\n", rc); if (ptpsyncts && ptp_data->ptpsyncts != ptpsyncts) { event.index = 0; event.type = PTP_CLOCK_EXTTS; event.timestamp = ns_to_ktime(sja1105_ticks_to_ns(ptpsyncts)); ptp_clock_event(ptp_data->clock, &event); ptp_data->ptpsyncts = ptpsyncts; } } static long sja1105_rxtstamp_work(struct ptp_clock_info *ptp) { struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp); struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data); struct dsa_switch *ds = priv->ds; struct sk_buff *skb; mutex_lock(&ptp_data->lock); while ((skb = skb_dequeue(&ptp_data->skb_rxtstamp_queue)) != NULL) { struct skb_shared_hwtstamps *shwt = skb_hwtstamps(skb); u64 ticks, ts; int rc; rc = sja1105_ptpclkval_read(priv, &ticks, NULL); if (rc < 0) { dev_err(ds->dev, "Failed to read PTP clock: %d\n", rc); kfree_skb(skb); continue; } *shwt = (struct skb_shared_hwtstamps) {0}; ts = SJA1105_SKB_CB(skb)->meta_tstamp; ts = sja1105_tstamp_reconstruct(ds, ticks, ts); shwt->hwtstamp = ns_to_ktime(sja1105_ticks_to_ns(ts)); netif_rx_ni(skb); } if (ptp_data->extts_enabled) sja1105_extts_poll(priv); mutex_unlock(&ptp_data->lock); /* Don't restart */ return -1; } /* Called from dsa_skb_defer_rx_timestamp */ bool sja1105_port_rxtstamp(struct dsa_switch *ds, int port, struct sk_buff *skb, unsigned int type) { struct sja1105_private *priv = ds->priv; struct sja1105_ptp_data *ptp_data = &priv->ptp_data; if (!test_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state)) return false; /* We need to read the full PTP clock to reconstruct the Rx * timestamp. For that we need a sleepable context. */ skb_queue_tail(&ptp_data->skb_rxtstamp_queue, skb); ptp_schedule_worker(ptp_data->clock, 0); return true; } /* Called from dsa_skb_tx_timestamp. This callback is just to clone * the skb and have it available in SJA1105_SKB_CB in the .port_deferred_xmit * callback, where we will timestamp it synchronously. */ void sja1105_port_txtstamp(struct dsa_switch *ds, int port, struct sk_buff *skb) { struct sja1105_private *priv = ds->priv; struct sja1105_port *sp = &priv->ports[port]; struct sk_buff *clone; if (!sp->hwts_tx_en) return; clone = skb_clone_sk(skb); if (!clone) return; SJA1105_SKB_CB(skb)->clone = clone; } static int sja1105_ptp_reset(struct dsa_switch *ds) { struct sja1105_private *priv = ds->priv; struct sja1105_ptp_data *ptp_data = &priv->ptp_data; struct sja1105_ptp_cmd cmd = ptp_data->cmd; int rc; mutex_lock(&ptp_data->lock); cmd.resptp = 1; dev_dbg(ds->dev, "Resetting PTP clock\n"); rc = sja1105_ptp_commit(ds, &cmd, SPI_WRITE); sja1105_tas_clockstep(priv->ds); mutex_unlock(&ptp_data->lock); return rc; } /* Caller must hold ptp_data->lock */ int __sja1105_ptp_gettimex(struct dsa_switch *ds, u64 *ns, struct ptp_system_timestamp *ptp_sts) { struct sja1105_private *priv = ds->priv; u64 ticks; int rc; rc = sja1105_ptpclkval_read(priv, &ticks, ptp_sts); if (rc < 0) { dev_err(ds->dev, "Failed to read PTP clock: %d\n", rc); return rc; } *ns = sja1105_ticks_to_ns(ticks); return 0; } static int sja1105_ptp_gettimex(struct ptp_clock_info *ptp, struct timespec64 *ts, struct ptp_system_timestamp *ptp_sts) { struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp); struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data); u64 now = 0; int rc; mutex_lock(&ptp_data->lock); rc = __sja1105_ptp_gettimex(priv->ds, &now, ptp_sts); *ts = ns_to_timespec64(now); mutex_unlock(&ptp_data->lock); return rc; } /* Caller must hold ptp_data->lock */ static int sja1105_ptp_mode_set(struct sja1105_private *priv, enum sja1105_ptp_clk_mode mode) { struct sja1105_ptp_data *ptp_data = &priv->ptp_data; if (ptp_data->cmd.ptpclkadd == mode) return 0; ptp_data->cmd.ptpclkadd = mode; return sja1105_ptp_commit(priv->ds, &ptp_data->cmd, SPI_WRITE); } /* Write to PTPCLKVAL while PTPCLKADD is 0 */ int __sja1105_ptp_settime(struct dsa_switch *ds, u64 ns, struct ptp_system_timestamp *ptp_sts) { struct sja1105_private *priv = ds->priv; u64 ticks = ns_to_sja1105_ticks(ns); int rc; rc = sja1105_ptp_mode_set(priv, PTP_SET_MODE); if (rc < 0) { dev_err(priv->ds->dev, "Failed to put PTPCLK in set mode\n"); return rc; } rc = sja1105_ptpclkval_write(priv, ticks, ptp_sts); sja1105_tas_clockstep(priv->ds); return rc; } static int sja1105_ptp_settime(struct ptp_clock_info *ptp, const struct timespec64 *ts) { struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp); struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data); u64 ns = timespec64_to_ns(ts); int rc; mutex_lock(&ptp_data->lock); rc = __sja1105_ptp_settime(priv->ds, ns, NULL); mutex_unlock(&ptp_data->lock); return rc; } static int sja1105_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) { struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp); struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data); const struct sja1105_regs *regs = priv->info->regs; u32 clkrate32; s64 clkrate; int rc; clkrate = (s64)scaled_ppm * SJA1105_CC_MULT_NUM; clkrate = div_s64(clkrate, SJA1105_CC_MULT_DEM); /* Take a +/- value and re-center it around 2^31. */ clkrate = SJA1105_CC_MULT + clkrate; WARN_ON(abs(clkrate) >= GENMASK_ULL(31, 0)); clkrate32 = clkrate; mutex_lock(&ptp_data->lock); rc = sja1105_xfer_u32(priv, SPI_WRITE, regs->ptpclkrate, &clkrate32, NULL); sja1105_tas_adjfreq(priv->ds); mutex_unlock(&ptp_data->lock); return rc; } /* Write to PTPCLKVAL while PTPCLKADD is 1 */ int __sja1105_ptp_adjtime(struct dsa_switch *ds, s64 delta) { struct sja1105_private *priv = ds->priv; s64 ticks = ns_to_sja1105_ticks(delta); int rc; rc = sja1105_ptp_mode_set(priv, PTP_ADD_MODE); if (rc < 0) { dev_err(priv->ds->dev, "Failed to put PTPCLK in add mode\n"); return rc; } rc = sja1105_ptpclkval_write(priv, ticks, NULL); sja1105_tas_clockstep(priv->ds); return rc; } static int sja1105_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta) { struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp); struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data); int rc; mutex_lock(&ptp_data->lock); rc = __sja1105_ptp_adjtime(priv->ds, delta); mutex_unlock(&ptp_data->lock); return rc; } static void sja1105_ptp_extts_setup_timer(struct sja1105_ptp_data *ptp_data) { unsigned long expires = ((jiffies / SJA1105_EXTTS_INTERVAL) + 1) * SJA1105_EXTTS_INTERVAL; mod_timer(&ptp_data->extts_timer, expires); } static void sja1105_ptp_extts_timer(struct timer_list *t) { struct sja1105_ptp_data *ptp_data = extts_to_data(t); ptp_schedule_worker(ptp_data->clock, 0); sja1105_ptp_extts_setup_timer(ptp_data); } static int sja1105_change_ptp_clk_pin_func(struct sja1105_private *priv, enum ptp_pin_function func) { struct sja1105_avb_params_entry *avb; enum ptp_pin_function old_func; avb = priv->static_config.tables[BLK_IDX_AVB_PARAMS].entries; if (priv->info->device_id == SJA1105E_DEVICE_ID || priv->info->device_id == SJA1105T_DEVICE_ID || avb->cas_master) old_func = PTP_PF_PEROUT; else old_func = PTP_PF_EXTTS; if (func == old_func) return 0; avb->cas_master = (func == PTP_PF_PEROUT); return sja1105_dynamic_config_write(priv, BLK_IDX_AVB_PARAMS, 0, avb, true); } /* The PTP_CLK pin may be configured to toggle with a 50% duty cycle and a * frequency f: * * NSEC_PER_SEC * f = ---------------------- * (PTPPINDUR * 8 ns) * 2 */ static int sja1105_per_out_enable(struct sja1105_private *priv, struct ptp_perout_request *perout, bool on) { struct sja1105_ptp_data *ptp_data = &priv->ptp_data; const struct sja1105_regs *regs = priv->info->regs; struct sja1105_ptp_cmd cmd = ptp_data->cmd; int rc; /* We only support one channel */ if (perout->index != 0) return -EOPNOTSUPP; /* Reject requests with unsupported flags */ if (perout->flags) return -EOPNOTSUPP; mutex_lock(&ptp_data->lock); rc = sja1105_change_ptp_clk_pin_func(priv, PTP_PF_PEROUT); if (rc) goto out; if (on) { struct timespec64 pin_duration_ts = { .tv_sec = perout->period.sec, .tv_nsec = perout->period.nsec, }; struct timespec64 pin_start_ts = { .tv_sec = perout->start.sec, .tv_nsec = perout->start.nsec, }; u64 pin_duration = timespec64_to_ns(&pin_duration_ts); u64 pin_start = timespec64_to_ns(&pin_start_ts); u32 pin_duration32; u64 now; /* ptppindur: 32 bit register which holds the interval between * 2 edges on PTP_CLK. So check for truncation which happens * at periods larger than around 68.7 seconds. */ pin_duration = ns_to_sja1105_ticks(pin_duration / 2); if (pin_duration > U32_MAX) { rc = -ERANGE; goto out; } pin_duration32 = pin_duration; /* ptppins: 64 bit register which needs to hold a PTP time * larger than the current time, otherwise the startptpcp * command won't do anything. So advance the current time * by a number of periods in a way that won't alter the * phase offset. */ rc = __sja1105_ptp_gettimex(priv->ds, &now, NULL); if (rc < 0) goto out; pin_start = future_base_time(pin_start, pin_duration, now + 1ull * NSEC_PER_SEC); pin_start = ns_to_sja1105_ticks(pin_start); rc = sja1105_xfer_u64(priv, SPI_WRITE, regs->ptppinst, &pin_start, NULL); if (rc < 0) goto out; rc = sja1105_xfer_u32(priv, SPI_WRITE, regs->ptppindur, &pin_duration32, NULL); if (rc < 0) goto out; } if (on) cmd.startptpcp = true; else cmd.stopptpcp = true; rc = sja1105_ptp_commit(priv->ds, &cmd, SPI_WRITE); out: mutex_unlock(&ptp_data->lock); return rc; } static int sja1105_extts_enable(struct sja1105_private *priv, struct ptp_extts_request *extts, bool on) { int rc; /* We only support one channel */ if (extts->index != 0) return -EOPNOTSUPP; /* Reject requests with unsupported flags */ if (extts->flags & ~(PTP_ENABLE_FEATURE | PTP_RISING_EDGE | PTP_FALLING_EDGE | PTP_STRICT_FLAGS)) return -EOPNOTSUPP; /* We can only enable time stamping on both edges, sadly. */ if ((extts->flags & PTP_STRICT_FLAGS) && (extts->flags & PTP_ENABLE_FEATURE) && (extts->flags & PTP_EXTTS_EDGES) != PTP_EXTTS_EDGES) return -EOPNOTSUPP; rc = sja1105_change_ptp_clk_pin_func(priv, PTP_PF_EXTTS); if (rc) return rc; priv->ptp_data.extts_enabled = on; if (on) sja1105_ptp_extts_setup_timer(&priv->ptp_data); else del_timer_sync(&priv->ptp_data.extts_timer); return 0; } static int sja1105_ptp_enable(struct ptp_clock_info *ptp, struct ptp_clock_request *req, int on) { struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp); struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data); int rc = -EOPNOTSUPP; if (req->type == PTP_CLK_REQ_PEROUT) rc = sja1105_per_out_enable(priv, &req->perout, on); else if (req->type == PTP_CLK_REQ_EXTTS) rc = sja1105_extts_enable(priv, &req->extts, on); return rc; } static int sja1105_ptp_verify_pin(struct ptp_clock_info *ptp, unsigned int pin, enum ptp_pin_function func, unsigned int chan) { struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp); struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data); if (chan != 0 || pin != 0) return -1; switch (func) { case PTP_PF_NONE: case PTP_PF_PEROUT: break; case PTP_PF_EXTTS: if (priv->info->device_id == SJA1105E_DEVICE_ID || priv->info->device_id == SJA1105T_DEVICE_ID) return -1; break; default: return -1; } return 0; } static struct ptp_pin_desc sja1105_ptp_pin = { .name = "ptp_clk", .index = 0, .func = PTP_PF_NONE, }; int sja1105_ptp_clock_register(struct dsa_switch *ds) { struct sja1105_private *priv = ds->priv; struct sja1105_tagger_data *tagger_data = &priv->tagger_data; struct sja1105_ptp_data *ptp_data = &priv->ptp_data; ptp_data->caps = (struct ptp_clock_info) { .owner = THIS_MODULE, .name = "SJA1105 PHC", .adjfine = sja1105_ptp_adjfine, .adjtime = sja1105_ptp_adjtime, .gettimex64 = sja1105_ptp_gettimex, .settime64 = sja1105_ptp_settime, .enable = sja1105_ptp_enable, .verify = sja1105_ptp_verify_pin, .do_aux_work = sja1105_rxtstamp_work, .max_adj = SJA1105_MAX_ADJ_PPB, .pin_config = &sja1105_ptp_pin, .n_pins = 1, .n_ext_ts = 1, .n_per_out = 1, }; skb_queue_head_init(&ptp_data->skb_rxtstamp_queue); spin_lock_init(&tagger_data->meta_lock); ptp_data->clock = ptp_clock_register(&ptp_data->caps, ds->dev); if (IS_ERR_OR_NULL(ptp_data->clock)) return PTR_ERR(ptp_data->clock); ptp_data->cmd.corrclk4ts = true; ptp_data->cmd.ptpclkadd = PTP_SET_MODE; timer_setup(&ptp_data->extts_timer, sja1105_ptp_extts_timer, 0); return sja1105_ptp_reset(ds); } void sja1105_ptp_clock_unregister(struct dsa_switch *ds) { struct sja1105_private *priv = ds->priv; struct sja1105_ptp_data *ptp_data = &priv->ptp_data; if (IS_ERR_OR_NULL(ptp_data->clock)) return; del_timer_sync(&ptp_data->extts_timer); ptp_cancel_worker_sync(ptp_data->clock); skb_queue_purge(&ptp_data->skb_rxtstamp_queue); ptp_clock_unregister(ptp_data->clock); ptp_data->clock = NULL; } void sja1105_ptp_txtstamp_skb(struct dsa_switch *ds, int port, struct sk_buff *skb) { struct sja1105_private *priv = ds->priv; struct sja1105_ptp_data *ptp_data = &priv->ptp_data; struct skb_shared_hwtstamps shwt = {0}; u64 ticks, ts; int rc; skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS; mutex_lock(&ptp_data->lock); rc = sja1105_ptpegr_ts_poll(ds, port, &ts); if (rc < 0) { dev_err(ds->dev, "timed out polling for tstamp\n"); kfree_skb(skb); goto out; } rc = sja1105_ptpclkval_read(priv, &ticks, NULL); if (rc < 0) { dev_err(ds->dev, "Failed to read PTP clock: %d\n", rc); kfree_skb(skb); goto out; } ts = sja1105_tstamp_reconstruct(ds, ticks, ts); shwt.hwtstamp = ns_to_ktime(sja1105_ticks_to_ns(ts)); skb_complete_tx_timestamp(skb, &shwt); out: mutex_unlock(&ptp_data->lock); }
760536.c
/*************************************************************************** Time Limit (c) 1983 Chuo Progress (c) 1984 Chuo driver by Ernesto Corvi ***************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" /* from vidhrdw */ extern VIDEO_START( timelimt ); extern PALETTE_INIT( timelimt ); extern VIDEO_UPDATE( timelimt ); extern WRITE_HANDLER( timelimt_videoram_w ); extern WRITE_HANDLER( timelimt_bg_videoram_w ); extern WRITE_HANDLER( timelimt_scroll_y_w ); extern WRITE_HANDLER( timelimt_scroll_x_msb_w ); extern WRITE_HANDLER( timelimt_scroll_x_lsb_w ); extern data8_t *timelimt_bg_videoram; extern size_t timelimt_bg_videoram_size; /***************************************************************************/ static int nmi_enabled = 0; static MACHINE_INIT( timelimt ) { soundlatch_setclearedvalue( 0 ); nmi_enabled = 0; } static WRITE_HANDLER( nmi_enable_w ) { nmi_enabled = data & 1; /* bit 0 = nmi enable */ } static WRITE_HANDLER( sound_reset_w ) { if ( data & 1 ) cpu_set_reset_line( 1, PULSE_LINE ); } static MEMORY_READ_START( readmem ) { 0x0000, 0x7fff, MRA_ROM }, /* rom */ { 0x8000, 0x87ff, MRA_RAM }, /* ram */ { 0x8800, 0x8bff, MRA_RAM }, /* video ram */ { 0x9000, 0x97ff, MRA_RAM }, /* background ram */ { 0x9800, 0x98ff, MRA_RAM }, /* sprite ram */ { 0xa000, 0xa000, input_port_0_r }, /* input port */ { 0xa800, 0xa800, input_port_1_r }, /* input port */ { 0xb000, 0xb000, input_port_2_r }, /* DSW */ { 0xb800, 0xb800, MRA_NOP }, /* NMI ack? */ MEMORY_END static MEMORY_WRITE_START( writemem ) { 0x0000, 0x7fff, MWA_ROM }, /* rom */ { 0x8000, 0x87ff, MWA_RAM }, /* ram */ { 0x8800, 0x8bff, timelimt_videoram_w, &videoram, &videoram_size }, /* video ram */ { 0x9000, 0x97ff, timelimt_bg_videoram_w, &timelimt_bg_videoram, &timelimt_bg_videoram_size },/* background ram */ { 0x9800, 0x98ff, MWA_RAM, &spriteram, &spriteram_size }, /* sprite ram */ { 0xb000, 0xb000, nmi_enable_w }, /* nmi enable */ { 0xb003, 0xb003, sound_reset_w }, /* sound reset ? */ { 0xb800, 0xb800, soundlatch_w }, /* sound write */ { 0xc800, 0xc800, timelimt_scroll_x_lsb_w }, { 0xc801, 0xc801, timelimt_scroll_x_msb_w }, { 0xc802, 0xc802, timelimt_scroll_y_w }, { 0xc803, 0xc803, MWA_NOP }, /* ???? bit 0 used only */ { 0xc804, 0xc804, MWA_NOP }, /* ???? not used */ MEMORY_END static PORT_READ_START( readport ) { 0x00, 0x00, watchdog_reset_r }, PORT_END static MEMORY_READ_START( readmem_sound ) { 0x0000, 0x1fff, MRA_ROM }, /* rom */ { 0x3800, 0x3bff, MRA_RAM }, /* ram */ MEMORY_END static MEMORY_WRITE_START( writemem_sound ) { 0x0000, 0x1fff, MWA_ROM }, /* rom */ { 0x3800, 0x3bff, MWA_RAM }, /* ram */ MEMORY_END static PORT_READ_START( readport_sound ) { 0x8c, 0x8d, AY8910_read_port_0_r }, { 0x8e, 0x8f, AY8910_read_port_1_r }, PORT_END static PORT_WRITE_START( writeport_sound ) { 0x00, 0x00, soundlatch_clear_w }, { 0x8c, 0x8c, AY8910_control_port_0_w }, { 0x8d, 0x8d, AY8910_write_port_0_w }, { 0x8e, 0x8e, AY8910_control_port_1_w }, { 0x8f, 0x8f, AY8910_write_port_1_w }, PORT_END /***************************************************************************/ INPUT_PORTS_START( timelimt ) PORT_START /* IN0 */ PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT | IPF_4WAY ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT | IPF_4WAY ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN | IPF_4WAY ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP | IPF_4WAY ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_START /* IN1 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_START /* DSW1 */ PORT_DIPNAME( 0x07, 0x01, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x03, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x05, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 1C_7C ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x10, "5" ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_BITX( 0x80, 0x00, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invincibility", IP_KEY_NONE, IP_JOY_NONE ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) INPUT_PORTS_END INPUT_PORTS_START( progress ) PORT_START /* IN0 */ PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_START /* IN1 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* probably unused */ PORT_START /* DSW1 */ PORT_DIPNAME( 0x07, 0x01, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x03, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x05, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 1C_7C ) ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPSETTING( 0x10, "5" ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x40, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) INPUT_PORTS_END /***************************************************************************/ static struct GfxLayout charlayout = { 8,8, RGN_FRAC(1,2), 4, { RGN_FRAC(0,2)+0, RGN_FRAC(0,2)+4, RGN_FRAC(1,2)+0, RGN_FRAC(1,2)+4 }, { 0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3 }, { 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16 }, 16*8 }; static struct GfxLayout spritelayout = { 16,16, RGN_FRAC(1,3), 3, { RGN_FRAC(0,3), RGN_FRAC(1,3), RGN_FRAC(2,3) }, { 0, 1, 2, 3, 4, 5, 6, 7, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 8*8+4, 8*8+5, 8*8+6, 8*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 16*8, 17*8, 18*8, 19*8, 20*8, 21*8, 22*8, 23*8 }, 32*8 }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { REGION_GFX1, 0, &charlayout, 32, 1 }, /* seems correct */ { REGION_GFX2, 0, &charlayout, 0, 1 }, /* seems correct */ { REGION_GFX3, 0, &spritelayout, 64, 4 }, /* seems correct */ { -1 } /* end of array */ }; /***************************************************************************/ static struct AY8910interface ay8910_interface = { 2, /* 2 chips */ 18432000/12, { 25, 25 }, { 0, soundlatch_r }, { 0 }, { 0 }, { 0 } }; static INTERRUPT_GEN( timelimt_irq ) { if ( nmi_enabled ) cpu_set_irq_line(0, IRQ_LINE_NMI, PULSE_LINE); } /***************************************************************************/ static MACHINE_DRIVER_START( timelimt ) /* basic machine hardware */ MDRV_CPU_ADD(Z80, 5000000) /* 5.000 MHz */ MDRV_CPU_MEMORY(readmem,writemem) MDRV_CPU_PORTS(readport,0) MDRV_CPU_VBLANK_INT(timelimt_irq,1) MDRV_CPU_ADD(Z80,18432000/6) MDRV_CPU_FLAGS(CPU_AUDIO_CPU) /* 3.072 MHz */ MDRV_CPU_MEMORY(readmem_sound,writemem_sound) MDRV_CPU_PORTS(readport_sound,writeport_sound) MDRV_CPU_VBLANK_INT(irq0_line_hold,1) /* ? */ MDRV_FRAMES_PER_SECOND(60) MDRV_VBLANK_DURATION(DEFAULT_60HZ_VBLANK_DURATION) MDRV_INTERLEAVE(50) MDRV_MACHINE_INIT(timelimt) /* video hardware */ MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER) MDRV_SCREEN_SIZE(32*8, 32*8) MDRV_VISIBLE_AREA(0*8, 32*8-1, 2*8, 30*8-1) MDRV_GFXDECODE(gfxdecodeinfo) MDRV_PALETTE_LENGTH(96) MDRV_COLORTABLE_LENGTH(96) MDRV_PALETTE_INIT(timelimt) MDRV_VIDEO_START(timelimt) MDRV_VIDEO_UPDATE(timelimt) /* sound hardware */ MDRV_SOUND_ADD(AY8910, ay8910_interface) MACHINE_DRIVER_END /*************************************************************************** Game ROM(s) ***************************************************************************/ ROM_START( timelimt ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* ROMs */ ROM_LOAD( "t8", 0x0000, 0x2000, CRC(006767ca) SHA1(a5d528c58cd73c0101ffa9ab783ec870668256db) ) ROM_LOAD( "t7", 0x2000, 0x2000, CRC(cbe7cd86) SHA1(502a78c14c9717a466ea24cdc63da4c0f3bec1f9) ) ROM_LOAD( "t6", 0x4000, 0x2000, CRC(f5f17e39) SHA1(7d78f551ce73276725c349703a790f2a63bb5503) ) ROM_LOAD( "t9", 0x6000, 0x2000, CRC(2d72ab45) SHA1(01d4afacc01b9e7c49355123efd5f5ad4d79a9cd) ) ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* ROMs */ ROM_LOAD( "tl5", 0x0000, 0x1000, CRC(5b782e4a) SHA1(2f4fe2beb8efa5a636fefc1ee172d0200d1c9497) ) ROM_LOAD( "tl4", 0x1000, 0x1000, CRC(a32883a9) SHA1(26e1725b67be87db28855672facb1504b8ac84d6) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) /* tiles */ ROM_LOAD( "tl11", 0x0000, 0x1000, CRC(46676307) SHA1(38fe80722972b6b3ba32705469a0dcb868fb76a9) ) ROM_LOAD( "tl10", 0x1000, 0x1000, CRC(2336908a) SHA1(345fc209ce891cc6f8f111c6d3a9e0f65ee6d818) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) /* tiles */ ROM_LOAD( "tl13", 0x0000, 0x1000, CRC(072e4053) SHA1(209edf7b371078e38d1c2812fa6a3d1a78193b3f) ) ROM_LOAD( "tl12", 0x1000, 0x1000, CRC(ce960389) SHA1(57ee52cfa1b5a3832b362b38c8b7aa411dfc782b) ) ROM_REGION( 0x6000, REGION_GFX3, ROMREGION_DISPOSE ) /* sprites */ ROM_LOAD( "tl3", 0x4000, 0x2000, CRC(01a9fd95) SHA1(cd1078700c97a3539c9d9447c55efbd27540a1b3) ) ROM_LOAD( "tl2", 0x2000, 0x2000, CRC(4693b849) SHA1(fbebedde53599fb1eaedc648bd704b321ab096b5) ) ROM_LOAD( "tl1", 0x0000, 0x2000, CRC(c4007caf) SHA1(ae05af3319545d5ca98a046bfc100138a5a3ed96) ) ROM_REGION( 0x0060, REGION_PROMS, 0 ) ROM_LOAD( "clr.35", 0x0000, 0x0020, CRC(9c9e6073) SHA1(98496175bf19a8cdb0018705bc1a2193b8a782e1) ) ROM_LOAD( "clr.48", 0x0020, 0x0020, CRC(a0bcac59) SHA1(e5832831b21981363509b79d89766757bd9273b0) ) /* FIXED BITS (xxxxxx1x) */ ROM_LOAD( "clr.57", 0x0040, 0x0020, CRC(3a9f5394) SHA1(0b501f81ce1df722cf7ef982c03e0be337bfe9ee) ) ROM_END ROM_START( progress ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* ROMs */ ROM_LOAD( "pg8.bin", 0x0000, 0x2000, CRC(e8779658) SHA1(3eca574d7328d54e544e663f58be789dbf151e77) ) ROM_LOAD( "pg7.bin", 0x2000, 0x2000, CRC(5dcf6b6f) SHA1(550f02ff5ed2935f4c3c9055c5742fea46f42351) ) ROM_LOAD( "pg6.bin", 0x4000, 0x2000, CRC(f21d2a08) SHA1(b2542e895d6d011895abec641b056ad8d7dc0d15) ) ROM_LOAD( "pg9.bin", 0x6000, 0x2000, CRC(052ab4ac) SHA1(a2bfb575f2dfde862f9b1e8a4378f9b6b6200831) ) ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* ROMs */ ROM_LOAD( "pg4.bin", 0x0000, 0x1000, CRC(b1cc2fe8) SHA1(c9045e7b65311b052c337ad3bedadf108d1c24c3) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) /* tiles */ ROM_LOAD( "pg11.bin", 0x0000, 0x1000, CRC(bd8462e4) SHA1(91b1bd2d69aa1b1a84ee8e642b2c1131a7697dd9) ) ROM_LOAD( "pg10.bin", 0x1000, 0x1000, CRC(c4bbf0b8) SHA1(d149eda9637474febdafd565a60eb2940702f162) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) /* tiles */ ROM_LOAD( "pg13.bin", 0x0000, 0x1000, CRC(25ec45be) SHA1(1271b7a5632934a82ccae35de8c2968247a233bb) ) ROM_LOAD( "pg12.bin", 0x1000, 0x1000, CRC(c837c5f5) SHA1(dbfc0d8afe0a8e9dd213cb4095b23b7aa8e2b6f4) ) ROM_REGION( 0x6000, REGION_GFX3, ROMREGION_DISPOSE ) /* sprites */ ROM_LOAD( "pg1.bin", 0x0000, 0x2000, CRC(155c8f7f) SHA1(0d32ebceb9b2a0b3faf1f91b7a6800999889b331) ) ROM_LOAD( "pg2.bin", 0x2000, 0x2000, CRC(a6ca4dfc) SHA1(4243c9ea98e365bf342cf928ff97cafb35cdc7b6) ) ROM_LOAD( "pg3.bin", 0x4000, 0x2000, CRC(2b21c2fb) SHA1(8c95889a19057d32790c9ccddc0977980eddbd0e) ) ROM_REGION( 0x0060, REGION_PROMS, 0 ) ROM_LOAD( "35.bin", 0x0000, 0x0020, CRC(8c5ca730) SHA1(be2554e1aa4a74d976919e2c37bce5fb4d40352b) ) ROM_LOAD( "48.bin", 0x0020, 0x0020, CRC(12dd62cd) SHA1(8322b02d73c3eb44b587f76daeaabe6beea58456) ) ROM_LOAD( "57.bin", 0x0040, 0x0020, CRC(18455a79) SHA1(e4d64368560e3116a922588129f5f91a4c520f7d) ) ROM_END GAME ( 1983, timelimt, 0, timelimt, timelimt, 0, ROT90, "Chuo Co. Ltd", "Time Limit" ) GAME ( 1984, progress, 0, timelimt, progress, 0, ROT90, "Chuo Co. Ltd", "Progress" )
19998.c
//***************************************************************************** // // qei.c - Driver for the Quadrature Encoder with Index. // // Copyright (c) 2005,2006 Luminary Micro, Inc. All rights reserved. // // Software License Agreement // // Luminary Micro, Inc. (LMI) is supplying this software for use solely and // exclusively on LMI's Stellaris Family of microcontroller products. // // The software is owned by LMI and/or its suppliers, and is protected under // applicable copyright laws. All rights are reserved. Any use in violation // of the foregoing restrictions may subject the user to criminal sanctions // under applicable laws, as well as to civil liability for the breach of the // terms and conditions of this license. // // THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED // OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. // LMI SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR // CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 991 of the Stellaris Driver Library. // //***************************************************************************** //***************************************************************************** // //! \addtogroup qei_api //! @{ // //***************************************************************************** #include "../hw_ints.h" #include "../hw_memmap.h" #include "../hw_qei.h" #include "../hw_types.h" #include "debug.h" #include "interrupt.h" #include "qei.h" //***************************************************************************** // //! Enables the quadrature encoder. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This will enable operation of the quadrature encoder module. It must be //! configured before it is enabled. //! //! \sa QEIConfigure() //! //! \return None. // //***************************************************************************** #if defined(GROUP_enable) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIEnable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Enable the QEI module. // HWREG(ulBase + QEI_O_CTL) |= QEI_CTL_ENABLE; } #endif //***************************************************************************** // //! Disables the quadrature encoder. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This will disable operation of the quadrature encoder module. //! //! \return None. // //***************************************************************************** #if defined(GROUP_disable) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIDisable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Disable the QEI module. // HWREG(ulBase + QEI_O_CTL) &= ~(QEI_CTL_ENABLE); } #endif //***************************************************************************** // //! Configures the quadrature encoder. //! //! \param ulBase is the base address of the quadrature encoder module. //! \param ulConfig is the configuration for the quadrature encoder. See below //! for a description of this parameter. //! \param ulMaxPosition specifies the maximum position value. //! //! This will configure the operation of the quadrature encoder. The //! \e ulConfig parameter provides the configuration of the encoder and is the //! logical OR of several values: //! //! - \b QEI_CONFIG_CAPTURE_A or \b QEI_CONFIG_CAPTURE_A_B to specify if edges //! on channel A or on both channels A and B should be counted by the //! position integrator and velocity accumulator. //! - \b QEI_CONFIG_NO_RESET or \b QEI_CONFIG_RESET_IDX to specify if the //! position integrator should be reset when the index pulse is detected. //! - \b QEI_CONFIG_QUADRATURE or \b QEI_CONFIG_CLOCK_DIR to specify if //! quadrature signals are being provided on ChA and ChB, or if a direction //! signal and a clock are being provided instead. //! - \b QEI_CONFIG_NO_SWAP or \b QEI_CONFIG_SWAP to specify if the signals //! provided on ChA and ChB should be swapped before being processed. //! //! \e ulMaxPosition is the maximum value of the position integrator, and is //! the value used to reset the position capture when in index reset mode and //! moving in the reverse (negative) direction. //! //! \return None. // //***************************************************************************** #if defined(GROUP_configure) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIConfigure(unsigned long ulBase, unsigned long ulConfig, unsigned long ulMaxPosition) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Write the new configuration to the hardware. // HWREG(ulBase + QEI_O_CTL) = ((HWREG(ulBase + QEI_O_CTL) & ~(QEI_CTL_CAPMODE | QEI_CTL_RESMODE | QEI_CTL_SIGMODE | QEI_CTL_SWAP)) | ulConfig); // // Set the maximum position. // HWREG(ulBase + QEI_O_MAXPOS) = ulMaxPosition; } #endif //***************************************************************************** // //! Gets the current encoder position. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This returns the current position of the encoder. Depending upon the //! configuration of the encoder, and the incident of an index pulse, this //! value may or may not contain the expected data (i.e. if in reset on index //! mode, if an index pulse has not been encountered, the position counter will //! not be aligned with the index pulse yet). //! //! \return The current position of the encoder. // //***************************************************************************** #if defined(GROUP_positionget) || defined(BUILD_ALL) || defined(DOXYGEN) unsigned long QEIPositionGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Return the current position counter. // return(HWREG(ulBase + QEI_O_POS)); } #endif //***************************************************************************** // //! Sets the current encoder position. //! //! \param ulBase is the base address of the quadrature encoder module. //! \param ulPosition is the new position for the encoder. //! //! This sets the current position of the encoder; the encoder position will //! then be measured relative to this value. //! //! \return None. // //***************************************************************************** #if defined(GROUP_positionset) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIPositionSet(unsigned long ulBase, unsigned long ulPosition) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Set the position counter. // HWREG(ulBase + QEI_O_POS) = ulPosition; } #endif //***************************************************************************** // //! Gets the current direction of rotation. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This returns the current direction of rotation. In this case, current //! means the most recently detected direction of the encoder; it may not be //! presently moving but this is the direction it last moved before it stopped. //! //! \return 1 if moving in the forward direction or -1 if moving in the reverse //! direction. // //***************************************************************************** #if defined(GROUP_directionget) || defined(BUILD_ALL) || defined(DOXYGEN) long QEIDirectionGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Return the direction of rotation. // return((HWREG(ulBase + QEI_O_STAT) & QEI_STAT_DIRECTION) ? -1 : 1); } #endif //***************************************************************************** // //! Gets the encoder error indicator. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This returns the error indicator for the quadrature encoder. It is an //! error for both of the signals of the quadrature input to change at the same //! time. //! //! \return true if an error has occurred and false otherwise. // //***************************************************************************** #if defined(GROUP_errorget) || defined(BUILD_ALL) || defined(DOXYGEN) tBoolean QEIErrorGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Return the error indicator. // return((HWREG(ulBase + QEI_O_STAT) & QEI_STAT_ERROR) ? true : false); } #endif //***************************************************************************** // //! Enables the velocity capture. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This will enable operation of the velocity capture in the quadrature //! encoder module. It must be configured before it is enabled. Velocity //! capture will not occur if the quadrature encoder is not enabled. //! //! \sa QEIVelocityConfigure() and QEIEnable() //! //! \return None. // //***************************************************************************** #if defined(GROUP_velocityenable) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIVelocityEnable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Enable the velocity capture. // HWREG(ulBase + QEI_O_CTL) |= QEI_CTL_VELEN; } #endif //***************************************************************************** // //! Disables the velocity capture. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This will disable operation of the velocity capture in the quadrature //! encoder module. //! //! \return None. // //***************************************************************************** #if defined(GROUP_velocitydisable) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIVelocityDisable(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Disable the velocity capture. // HWREG(ulBase + QEI_O_CTL) &= ~(QEI_CTL_VELEN); } #endif //***************************************************************************** // //! Configures the velocity capture. //! //! \param ulBase is the base address of the quadrature encoder module. //! \param ulPreDiv specifies the predivider applied to the input quadrature //! signal before it is counted; can be one of QEI_VELDIV_1, QEI_VELDIV_2, //! QEI_VELDIV_4, QEI_VELDIV_8, QEI_VELDIV_16, QEI_VELDIV_32, QEI_VELDIV_64, or //! QEI_VELDIV_128. //! \param ulPeriod specifies the number of clock ticks over which to measure //! the velocity; must be non-zero. //! //! This will configure the operation of the velocity capture portion of the //! quadrature encoder. The position increment signal is predivided as //! specified by \e ulPreDiv before being accumulated by the velocity capture. //! The divided signal is accumulated over \e ulPeriod system clock before //! being saved and resetting the accumulator. //! //! \return None. // //***************************************************************************** #if defined(GROUP_velocityconfigure) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIVelocityConfigure(unsigned long ulBase, unsigned long ulPreDiv, unsigned long ulPeriod) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); ASSERT(!(ulPreDiv & ~(QEI_CTL_VELDIV_M))); ASSERT(ulPeriod != 0); // // Set the velocity predivider. // HWREG(ulBase + QEI_O_CTL) = ((HWREG(ulBase + QEI_O_CTL) & ~(QEI_CTL_VELDIV_M)) | ulPreDiv); // // Set the timer period. // HWREG(ulBase + QEI_O_LOAD) = ulPeriod - 1; } #endif //***************************************************************************** // //! Gets the current encoder speed. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This returns the current speed of the encoder. The value returned is the //! number of pulses detected in the specified time period; this number can be //! multiplied by the number of time periods per second and divided by the //! number of pulses per revolution to obtain the number of revolutions per //! second. //! //! \return The number of pulses captured in the given time period. // //***************************************************************************** #if defined(GROUP_velocityget) || defined(BUILD_ALL) || defined(DOXYGEN) unsigned long QEIVelocityGet(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Return the speed capture value. // return(HWREG(ulBase + QEI_O_SPEED)); } #endif //***************************************************************************** // //! Registers an interrupt handler for the quadrature encoder interrupt. //! //! \param ulBase is the base address of the quadrature encoder module. //! \param pfnHandler is a pointer to the function to be called when the //! quadrature encoder interrupt occurs. //! //! This sets the handler to be called when a quadrature encoder interrupt //! occurs. This will enable the global interrupt in the interrupt controller; //! specific quadrature encoder interrupts must be enabled via QEIIntEnable(). //! It is the interrupt handler's responsibility to clear the interrupt source //! via QEIIntClear(). //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** #if defined(GROUP_intregister) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIIntRegister(unsigned long ulBase, void (*pfnHandler)(void)) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Register the interrupt handler, returning an error if an error occurs. // IntRegister(INT_QEI, pfnHandler); // // Enable the quadrature encoder interrupt. // IntEnable(INT_QEI); } #endif //***************************************************************************** // //! Unregisters an interrupt handler for the quadrature encoder interrupt. //! //! \param ulBase is the base address of the quadrature encoder module. //! //! This function will clear the handler to be called when a quadrature encoder //! interrupt occurs. This will also mask off the interrupt in the interrupt //! controller so that the interrupt handler no longer is called. //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** #if defined(GROUP_intunregister) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIIntUnregister(unsigned long ulBase) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Disable the interrupt. // IntDisable(INT_QEI); // // Unregister the interrupt handler. // IntUnregister(INT_QEI); } #endif //***************************************************************************** // //! Enables individual quadrature encoder interrupt sources. //! //! \param ulBase is the base address of the quadrature encoder module. //! \param ulIntFlags is a bit mask of the interrupt sources to be enabled. //! Can be any of the QEI_INTERROR, QEI_INTDIR, QEI_INTTIMER, or QEI_INTINDEX //! values. //! //! Enables the indicated quadrature encoder interrupt sources. Only the //! sources that are enabled can be reflected to the processor interrupt; //! disabled sources have no effect on the processor. //! //! \return None. // //***************************************************************************** #if defined(GROUP_intenable) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIIntEnable(unsigned long ulBase, unsigned long ulIntFlags) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Enable the specified interrupts. // HWREG(ulBase + QEI_O_INTEN) |= ulIntFlags; } #endif //***************************************************************************** // //! Disables individual quadrature encoder interrupt sources. //! //! \param ulBase is the base address of the quadrature encoder module. //! \param ulIntFlags is a bit mask of the interrupt sources to be disabled. //! Can be any of the QEI_INTERROR, QEI_INTDIR, QEI_INTTIMER, or QEI_INTINDEX //! values. //! //! Disables the indicated quadrature encoder interrupt sources. Only the //! sources that are enabled can be reflected to the processor interrupt; //! disabled sources have no effect on the processor. //! //! \return None. // //***************************************************************************** #if defined(GROUP_intdisable) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIIntDisable(unsigned long ulBase, unsigned long ulIntFlags) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Disable the specified interrupts. // HWREG(ulBase + QEI_O_INTEN) &= ~(ulIntFlags); } #endif //***************************************************************************** // //! Gets the current interrupt status. //! //! \param ulBase is the base address of the quadrature encoder module. //! \param bMasked is false if the raw interrupt status is required and true if //! the masked interrupt status is required. //! //! This returns the interrupt status for the quadrature encoder module. //! Either the raw interrupt status or the status of interrupts that are //! allowed to reflect to the processor can be returned. //! //! \return The current interrupt status, enumerated as a bit field of //! QEI_INTERROR, QEI_INTDIR, QEI_INTTIMER, and QEI_INTINDEX. // //***************************************************************************** #if defined(GROUP_intstatus) || defined(BUILD_ALL) || defined(DOXYGEN) unsigned long QEIIntStatus(unsigned long ulBase, tBoolean bMasked) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Return either the interrupt status or the raw interrupt status as // requested. // if(bMasked) { return(HWREG(ulBase + QEI_O_ISC)); } else { return(HWREG(ulBase + QEI_O_RIS)); } } #endif //***************************************************************************** // //! Clears quadrature encoder interrupt sources. //! //! \param ulBase is the base address of the quadrature encoder module. //! \param ulIntFlags is a bit mask of the interrupt sources to be cleared. //! Can be any of the QEI_INTERROR, QEI_INTDIR, QEI_INTTIMER, or QEI_INTINDEX //! values. //! //! The specified quadrature encoder interrupt sources are cleared, so that //! they no longer assert. This must be done in the interrupt handler to keep //! it from being called again immediately upon exit. //! //! \return None. // //***************************************************************************** #if defined(GROUP_intclear) || defined(BUILD_ALL) || defined(DOXYGEN) void QEIIntClear(unsigned long ulBase, unsigned long ulIntFlags) { // // Check the arguments. // ASSERT(ulBase == QEI_BASE); // // Clear the requested interrupt sources. // HWREG(ulBase + QEI_O_ISC) = ulIntFlags; } #endif //***************************************************************************** // // Close the Doxygen group. //! @} // //*****************************************************************************
747270.c
/* Copyright (c) 2010 Stefan Kurtz <[email protected]> Copyright (c) 2010 Center for Bioinformatics, University of Hamburg Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "core/divmodmul_api.h" #include "eis-voiditf.h" #include "pckdfs.h" typedef struct { union { struct { GtUword lowerbound, upperbound; GtUchar inchar; } pckitv; GtUword remainingspecial; } either; GtUword depth, lcpnodedepth; bool isinterval; } Dfs_Boundsatdepth; GT_DECLAREARRAYSTRUCT(Dfs_Boundsatdepth); static GtUword dfsnonspecialwidth(const GtArrayBoundswithchar *bwci) { GtUword idx, addwidth = 0; for (idx = 0; idx < bwci->nextfreeBoundswithchar; idx++) { addwidth += bwci->spaceBoundswithchar[idx].rbound - bwci->spaceBoundswithchar[idx].lbound; } return addwidth; } #undef SKDEBUG #ifdef SKDEBUG static void showcurrentpath(const GtArrayGtUchar *currentpath) { GtUword idx; printf("path="); for (idx = 0; idx < currentpath->nextfreeGtUchar; idx++) { printf("%u ",(unsigned int) currentpath->spaceGtUchar[idx]); } printf("\n"); } static void showDfs_Boundsatdepth(const char *kind,const Dfs_Boundsatdepth *bd) { printf("%s ",kind); if (bd->isinterval) { printf("l="GT_WU" u="GT_WU" i=%u d="GT_WU"\n",bd->either.pckitv.lowerbound, bd->either.pckitv.upperbound, (unsigned int) bd->either.pckitv.inchar, bd->depth); } else { printf("w="GT_WU" d="GT_WU"\n",bd->either.remainingspecial,bd->depth); } } #endif int gt_fmindex_dfstraverse(const FMindex *fmindex, unsigned int numofchars, GtUword totallength, Processlcp processlcp, void *processlcpdata, GtError *err) { GtArrayDfs_Boundsatdepth stack; GtArrayBoundswithchar bwci; Boundswithchar *bwciptr; Dfs_Boundsatdepth parent, child; GtArrayGtUchar currentpath; GtUword nonspecialwidth, parentwidth, *rangeOccs; bool haserr = false, firstleaf = true; GT_INITARRAY(&stack,Dfs_Boundsatdepth); GT_INITARRAY(&currentpath,GtUchar); bwci.spaceBoundswithchar = gt_malloc(sizeof (*bwci.spaceBoundswithchar) * (numofchars+1)); bwci.nextfreeBoundswithchar = 0; bwci.allocatedBoundswithchar = (GtUword) (numofchars+1); child.isinterval = true; child.depth = 0; child.lcpnodedepth = 0; child.either.pckitv.lowerbound = 0; child.either.pckitv.upperbound = totallength+1; child.either.pckitv.inchar = (GtUchar) numofchars; /* undefined */ #ifdef SKDEBUG showDfs_Boundsatdepth("push",&child); #endif GT_STOREINARRAY(&stack,Dfs_Boundsatdepth,128,child); rangeOccs = gt_malloc(sizeof (*rangeOccs) * GT_MULT2(numofchars)); while (!haserr && stack.nextfreeDfs_Boundsatdepth > 0) { parent = stack.spaceDfs_Boundsatdepth[--stack.nextfreeDfs_Boundsatdepth]; #ifdef SKDEBUG showDfs_Boundsatdepth("pop",&parent); #endif if (!parent.isinterval) { gt_assert(parent.depth > 0); if (processlcp != NULL) { GtUword idx; for (idx = 0; idx<parent.either.remainingspecial; idx++) { if (!firstleaf) { if (processlcp(processlcpdata,(idx == 0) ? parent.lcpnodedepth : parent.depth - 1, err) != 0) { haserr = true; break; } } else { firstleaf = false; } } } } else { gt_assert(parent.either.pckitv.lowerbound < parent.either.pckitv.upperbound); if (parent.depth > 0) { gt_assert(parent.either.pckitv.inchar < (GtUchar) numofchars); if (parent.depth - 1 >= currentpath.allocatedGtUchar) { currentpath.allocatedGtUchar += 32UL; currentpath.spaceGtUchar = gt_realloc(currentpath.spaceGtUchar, sizeof (*currentpath.spaceGtUchar) * currentpath.allocatedGtUchar); } gt_assert(currentpath.spaceGtUchar != NULL); currentpath.spaceGtUchar[parent.depth - 1] = parent.either.pckitv.inchar; currentpath.nextfreeGtUchar = parent.depth; #ifdef SKDEBUG showcurrentpath(&currentpath); #endif } parentwidth = parent.either.pckitv.upperbound - parent.either.pckitv.lowerbound; if (parentwidth == 1UL) { if (!firstleaf) { if (processlcp != NULL) { if (processlcp(processlcpdata,parent.lcpnodedepth,err) != 0) { haserr = true; } } } else { firstleaf = false; } } else { gt_assert(parentwidth >= 2UL); gt_bwtrangesplitwithoutspecial(&bwci,rangeOccs,fmindex, parent.either.pckitv.lowerbound, parent.either.pckitv.upperbound); nonspecialwidth = dfsnonspecialwidth(&bwci); #ifdef SKDEBUG printf("split "GT_WU" "GT_WU" into "GT_WU" intervals of width " GT_WU"\n", parent.either.pckitv.lowerbound, parent.either.pckitv.upperbound, bwci.nextfreeBoundswithchar, nonspecialwidth); #endif gt_assert(nonspecialwidth <= parentwidth); if (nonspecialwidth < parentwidth) { child.isinterval = false; child.depth = parent.depth + 1; child.either.remainingspecial = parentwidth - nonspecialwidth; if (bwci.nextfreeBoundswithchar > 0) { child.lcpnodedepth = parent.depth; } else { child.lcpnodedepth = parent.lcpnodedepth; } #ifdef SKDEBUG showDfs_Boundsatdepth("special push",&child); #endif GT_STOREINARRAY(&stack,Dfs_Boundsatdepth,128,child); } gt_assert(bwci.spaceBoundswithchar != NULL); for (bwciptr = bwci.spaceBoundswithchar+bwci.nextfreeBoundswithchar-1; bwciptr >= bwci.spaceBoundswithchar; bwciptr--) { child.isinterval = true; child.depth = parent.depth + 1; child.either.pckitv.lowerbound = bwciptr->lbound; child.either.pckitv.upperbound = bwciptr->rbound; if (bwciptr > bwci.spaceBoundswithchar) { child.lcpnodedepth = parent.depth; } else { child.lcpnodedepth = parent.lcpnodedepth; } gt_assert(bwciptr->inchar < (GtUchar) numofchars); child.either.pckitv.inchar = bwciptr->inchar; gt_assert(child.either.pckitv.lowerbound < child.either.pckitv.upperbound); #ifdef SKDEBUG showDfs_Boundsatdepth("push",&child); #endif GT_STOREINARRAY(&stack,Dfs_Boundsatdepth,128,child); } } } } GT_FREEARRAY(&stack,Dfs_Boundsatdepth); GT_FREEARRAY(&bwci,Boundswithchar); GT_FREEARRAY(&currentpath,GtUchar); gt_free(rangeOccs); return haserr ? -1 : 0; }
873294.c
/** @file Copyright (c) 2017 - 2018, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "OsLoader.h" CONST CHAR16 *mConfigFileName[2] = { L"config.cfg", L"boot/grub/grub.cfg" }; /** Get hardware partition handle from boot option info This function will initialize boot device, and get hardware partition handle based on boot option. @param[in] BootOption Current boot option @param[out] HwPartHandle Hardware partition handle for boot image @retval RETURN_SUCCESS If partition was found successfully @retval Others If partition was not found **/ EFI_STATUS FindBootPartition ( IN OS_BOOT_OPTION *BootOption, OUT EFI_HANDLE *HwPartHandle ) { RETURN_STATUS Status; UINTN BootMediumPciBase; AddMeasurePoint (0x4040); // // Get OS boot device address // BootMediumPciBase = GetDeviceAddr (BootOption->DevType, BootOption->DevInstance); DEBUG ((DEBUG_INFO, "BootMediumPciBase(0x%x)\n", BootMediumPciBase)); BootMediumPciBase = TO_MM_PCI_ADDRESS (BootMediumPciBase); // // Init Boot device functions // Status = MediaSetInterfaceType (BootOption->DevType); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failed to set media interface - %r\n", Status)); return RETURN_UNSUPPORTED; } DEBUG ((DEBUG_INFO, "Getting boot image from %a\n", GetBootDeviceNameString(BootOption->DevType))); Status = MediaInitialize (BootMediumPciBase, DevInitAll); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failed to init media - %r\n", Status)); return Status; } AddMeasurePoint (0x4050); MediaTuning (BootMediumPciBase); AddMeasurePoint (0x4055); DEBUG ((DEBUG_INFO, "Try to find boot partition\n")); Status = FindPartitions (BootOption->HwPart, HwPartHandle); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failed to find partition - %r\n", Status)); return Status; } AddMeasurePoint (0x4060); DEBUG ((DEBUG_INFO, "Find partition success\n")); return RETURN_SUCCESS; } /** Get IAS image from raw partition Using boot option info, this function will read IAS image from raw partition based on hardware partition info saved in LoadedImage. After IAS image is loaded into memory, its information will be saved to LoadedImage. @param[in] BootOption Current boot option @param[in, out] LoadedImage Loaded Image information. @retval RETURN_SUCCESS If IAS image was loaded successfully @retval Others If IAS image was not loaded. **/ EFI_STATUS GetIasImageFromRawPartition ( IN OS_BOOT_OPTION *BootOption, IN OUT LOADED_IMAGE *LoadedImage ) { RETURN_STATUS Status; DEVICE_BLOCK_INFO BlockInfo; VOID *Buffer; UINTN ImageSize; LOGICAL_BLOCK_DEVICE LogicBlkDev; UINTN AlginedHeaderSize; UINTN AlginedImageSize; UINT32 BlockSize; UINT8 BlockData[4096]; UINT32 LbaAddr; UINT8 SwPart; SwPart = BootOption->Image[LoadedImage->LoadImageType].LbaImage.SwPart; LbaAddr = BootOption->Image[LoadedImage->LoadImageType].LbaImage.LbaAddr; // // The image_B partition number, is image_A partition number + 1 // They share same LBA offset address. // if ((BootOption->BootFlags & LOAD_IMAGE_FROM_BACKUP) != 0) { if ((LoadedImage->LoadImageType == LOAD_IMAGE_TRUSTY) || (LoadedImage->LoadImageType == LOAD_IMAGE_NORMAL)) { SwPart++; } } DEBUG ((DEBUG_INFO, "Load image from SwPart (0x%x), LbaAddr(0x%x)\n", SwPart, LbaAddr)); Status = GetLogicalPartitionInfo (SwPart, LoadedImage->HwPartHandle, &LogicBlkDev); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "Get logical partition error, Status = %r\n", Status)); return Status; } Status = MediaGetMediaInfo (BootOption->HwPart, &BlockInfo); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "GetMediaInfo Error %r\n", Status)); return Status; } // // Read the IAS Header first to get total size of the IAS image. // Make sure to round the Header size to be block aligned in bytes. // BlockSize = BlockInfo.BlockSize; AlginedHeaderSize = ((sizeof (IAS_HEADER) % BlockSize) == 0) ? \ sizeof (IAS_HEADER) : \ ((sizeof (IAS_HEADER) / BlockSize) + 1) * BlockSize; Status = MediaReadBlocks ( BootOption->HwPart, LogicBlkDev.StartBlock + LbaAddr, AlginedHeaderSize, BlockData ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "Read IAS image error, Status = %r\n", Status)); return Status; } // // Make sure to round the image size to be block aligned in bytes. // ImageSize = IAS_IMAGE_SIZE ((IAS_HEADER *) BlockData); AlginedImageSize = ((ImageSize % BlockSize) == 0) ? \ ImageSize : \ ((ImageSize / BlockSize) + 1) * BlockSize; if (AlginedImageSize > MAX_IAS_IMAGE_SIZE) { DEBUG ((DEBUG_INFO, "IAS image is bigger than limitation (0x%x). ImageSize=0x%x\n", MAX_IAS_IMAGE_SIZE, AlginedImageSize)); return EFI_LOAD_ERROR; } Buffer = (UINT8 *) AllocatePages (EFI_SIZE_TO_PAGES (AlginedImageSize)); if (Buffer == NULL) { DEBUG ((DEBUG_INFO, "Allocate memory (size:0x%x) fail.\n", AlginedImageSize)); return EFI_OUT_OF_RESOURCES; } CopyMem (Buffer, BlockData, AlginedHeaderSize); // // Read the rest of the IAS image into the buffer // Status = MediaReadBlocks ( BootOption->HwPart, LogicBlkDev.StartBlock + LbaAddr + (AlginedHeaderSize / BlockSize), AlginedImageSize, & (((UINT8 *)Buffer)[AlginedHeaderSize]) ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "Read rest of IAS image error, Status = %r\n", Status)); return Status; } if ((Buffer == NULL) || (ImageSize == 0)) { return EFI_LOAD_ERROR; } LoadedImage->IasImage.Addr = Buffer; LoadedImage->IasImage.Size = ImageSize; LoadedImage->Flags |= LOADED_IMAGE_IAS; return EFI_SUCCESS; } /** Get IAS image from file This function will read IAS image from file based on FsHandle. After IAS image is loaded into memory, its information will be saved to LoadedImage. @param[in] FsHandle File system handle used to read file @param[in] BootOption Current boot option @param[out] LoadedImage Loaded Image information. @retval RETURN_SUCCESS If IAS image was loaded successfully @retval Others If IAS image was not loaded. **/ EFI_STATUS GetIasImageFromFs ( IN EFI_HANDLE FsHandle, IN OS_BOOT_OPTION *BootOption, OUT LOADED_IMAGE *LoadedImage ) { RETURN_STATUS Status; CHAR16 FilePath[MAX_FILE_PATH_LEN]; VOID *Image; UINTN ImageSize; CONST CHAR8 *FileName; if (FsHandle == NULL) { return RETURN_INVALID_PARAMETER; } FileName = (CONST CHAR8 *)&BootOption->Image[LoadedImage->LoadImageType].FileName[0]; // Load IAS Image from file system AsciiStrToUnicodeStrS (FileName, FilePath, sizeof (FilePath) / sizeof (CHAR16)); Image = NULL; ImageSize = 0; Status = GetFileByName (FsHandle, FilePath, &Image, &ImageSize); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "Get file '%a' failed, Status = %r\n", FileName, Status)); return Status; } DEBUG ((DEBUG_INFO, "Get file '%s' (size:0x%x) success.\n", FilePath, ImageSize)); if ((Image == NULL) || (ImageSize == 0)) { return EFI_LOAD_ERROR; } LoadedImage->IasImage.Addr = Image; LoadedImage->IasImage.Size = ImageSize; LoadedImage->Flags |= LOADED_IMAGE_IAS; return EFI_SUCCESS; } /** Load a file from media and fill in the loaded file information. @param[in] FsHandle File system handle used to read file @param[in] ConfigFile Configuration file buffer. @param[in] FileInfo Pointer to the file informatino in buffer. @param[out] ImageData Pointer to receive the loaded file address and size. @retval RETURN_SUCCESS If image was loaded successfully @retval Others If image was not loaded. **/ STATIC EFI_STATUS LoadLinuxFile ( IN EFI_HANDLE FsHandle, IN CHAR8 *ConfigFile, IN STR_SLICE *FileInfo, OUT IMAGE_DATA *ImageData ) { EFI_STATUS Status; VOID *FileBuffer; UINTN FileSize; CHAR8 *Ptr; CHAR16 FileName[256]; if (FileInfo->Len == 0) { return EFI_NOT_FOUND; } if (FileInfo->Buf[0] == 0) { Ptr = ConfigFile + FileInfo->Pos; } else { Ptr = FileInfo->Buf + FileInfo->Pos; } Ptr[FileInfo->Len] = 0; AsciiStrToUnicodeStrS (Ptr, FileName, sizeof(FileName) / sizeof(CHAR16)); FileSize = 0; FileBuffer = NULL; Status = GetFileByName (FsHandle, FileName, &FileBuffer, &FileSize); DEBUG ((DEBUG_INFO, "Load file %a [size 0x%x]: %r\n", Ptr, FileSize, Status)); if (!EFI_ERROR (Status)) { ImageData->Addr = FileBuffer; ImageData->Size = FileSize; } return Status; } /** Get traditional linux image from file This function will read traditional linux files (vmlinuz, config.cfg and initrd) from file system into memory. The loaded file info will be saved to LinuxImage. @param[in] FsHandle File system handle used to read file @param[out] LinuxImage Used to save loaded Image information. @retval RETURN_SUCCESS If IAS image was loaded successfully @retval Others If IAS image was not loaded. **/ EFI_STATUS GetTraditionalLinux ( IN EFI_HANDLE FsHandle, OUT LINUX_IMAGE *LinuxImage ) { RETURN_STATUS Status; UINTN ConfigFileSize; VOID *ConfigFile; LINUX_BOOT_CFG LinuxBootCfg; UINT32 Index; UINT32 EntryIdx; CHAR8 *Ptr; MENU_ENTRY *MenuEntry; DEBUG ((DEBUG_INFO, "Try booting Linux from config file ...\n")); Status = RETURN_NOT_FOUND; for (Index = 0; Index < (UINTN)(FeaturePcdGet (PcdGrubBootCfgEnabled) ? 2 : 1); Index++) { DEBUG ((DEBUG_INFO, "Checking %s\n",mConfigFileName[Index])); ConfigFile = NULL; ConfigFileSize = 0; Status = GetFileByName (FsHandle, (CHAR16 *)mConfigFileName[Index], &ConfigFile, &ConfigFileSize); if (!EFI_ERROR (Status)) { break; } } if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "Could not find configuration file!\n")); // No any config was found, try to load vmlinuz/initrd directly. ConfigFileSize = 0; } EntryIdx = 0; ZeroMem (&LinuxBootCfg, sizeof (LINUX_BOOT_CFG)); if (FeaturePcdGet (PcdGrubBootCfgEnabled)) { // Process the config file and // Get boot option from user if timeout is non-zero if (ConfigFileSize > 0) { ParseLinuxBootConfig (ConfigFile, &LinuxBootCfg); PrintLinuxBootConfig (ConfigFile, &LinuxBootCfg); EntryIdx = GetLinuxBootOption (ConfigFile, &LinuxBootCfg); } } if (LinuxBootCfg.EntryNum == 0) { // Build a default boot option LinuxBootCfg.EntryNum = 1; MenuEntry = LinuxBootCfg.MenuEntry; MenuEntry[0].Name.Pos = 0; MenuEntry[0].Name.Len = 5; AsciiStrCpyS (MenuEntry[0].Name.Buf, sizeof(MenuEntry[0].Name.Buf), "Linux"); MenuEntry[0].InitRd.Pos = 0; MenuEntry[0].InitRd.Len = 6; AsciiStrCpyS (MenuEntry[0].InitRd.Buf, sizeof(MenuEntry[0].InitRd.Buf), "initrd"); MenuEntry[0].Kernel.Pos = 0; MenuEntry[0].Kernel.Len = 7; AsciiStrCpyS (MenuEntry[0].Kernel.Buf, sizeof(MenuEntry[0].Kernel.Buf), "vmlinuz"); MenuEntry[0].Command.Pos = 0; MenuEntry[0].Command.Len = ConfigFileSize; EntryIdx = 0; } // Load kernel image Status = LoadLinuxFile (FsHandle, ConfigFile, &LinuxBootCfg.MenuEntry[EntryIdx].Kernel, &LinuxImage->BootFile); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Load kernel failed!\n")); return RETURN_LOAD_ERROR; } // Update command line LinuxImage->CmdFile.Size = LinuxBootCfg.MenuEntry[EntryIdx].Command.Len; if (LinuxImage->CmdFile.Size > 0) { Ptr = (CHAR8 *)ConfigFile + LinuxBootCfg.MenuEntry[EntryIdx].Command.Pos; Ptr[LinuxImage->CmdFile.Size] = 0; LinuxImage->CmdFile.Addr = Ptr; } else { LinuxImage->CmdFile.Addr = 0; } // Load InitRd, optional Status = LoadLinuxFile (FsHandle, ConfigFile, &LinuxBootCfg.MenuEntry[EntryIdx].InitRd, &LinuxImage->InitrdFile); if (EFI_ERROR (Status) && (Status != EFI_NOT_FOUND)) { DEBUG ((DEBUG_ERROR, "Load initrd failed!\n")); return RETURN_LOAD_ERROR; } LinuxImage->ExtraBlobNumber = 0; return EFI_SUCCESS; } /** Load Image from boot media. This function will initialize OS boot device, and load image based on boot option, the loaded image info will be saved in LoadedImage. @param[in] BootOption Current boot option @param[out] LoadedImage Loaded Image information. @retval RETURN_SUCCESS If image was loaded successfully @retval Others If image was not loaded. **/ EFI_STATUS GetImageFromMedia ( IN OS_BOOT_OPTION *BootOption, OUT LOADED_IMAGE *LoadedImage ) { RETURN_STATUS Status; EFI_HANDLE FsHandle; EFI_HANDLE HwPartHandle; EFI_HOB_GUID_TYPE *GuidHob; EXT_BOOT_LOADER_VERSION *VersionHob; FsHandle = NULL; HwPartHandle = LoadedImage->HwPartHandle; if (BootOption->FsType >= EnumFileSystemMax) { Status = GetIasImageFromRawPartition (BootOption, LoadedImage); return Status; } // Load image from file system. DEBUG ((DEBUG_INFO, "Init File system\n")); Status = InitFileSystem (BootOption->SwPart, EnumFileSystemTypeAuto, HwPartHandle, &FsHandle); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "No partitions found, Status = %r\n", Status)); return Status; } Status = GetIasImageFromFs (FsHandle, BootOption, LoadedImage); if (!EFI_ERROR (Status)) { return Status; } // Enable tradition linux boot only in debug build GuidHob = GetNextGuidHob (&gBootLoaderVersionGuid, GetHobListPtr ()); if (GuidHob != NULL) { VersionHob = (EXT_BOOT_LOADER_VERSION *)GET_GUID_HOB_DATA (GuidHob); if ((VersionHob->Version.ImageVersion.BldDebug != 0) || !FeaturePcdGet (PcdVerifiedBootEnabled)) { Status = GetTraditionalLinux (FsHandle, &LoadedImage->Image.Linux); if (!EFI_ERROR (Status)) { LoadedImage->Flags |= LOADED_IMAGE_LINUX; } } } return Status; }
626847.c
/* * vector.c - vector implementation * * Copyright (c) 2000-2019 Shiro Kawai <[email protected]> * * 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 authors nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define LIBGAUCHE_BODY #include "gauche.h" #include "gauche/priv/writerP.h" /* Catch integer overflow. NB: If total size is too big, GC_malloc aborts. But we have to prevent total size from overflowing before passed to GC_malloc. We'll try to allocate size*eltsize (+ up to two words of header). The GC's malloc routine first round it up to GC allocation unit boundary (8 or 16 bytes). If there's not enough heap, then it tries to expand the heap by the size rounded up to the pagesize. We don't want the final value overflows signed long. (In reality, expanding heap with close to LONG_MAX surely fails, so it should suffice to avoid overflow before calling GC_MALLOC. But it won't harm to have a bit of margin here...) */ static void check_size(ScmSmallInt size, int eltsize) { if (size >= (ScmSmallInt)((LONG_MAX - 0x400000)/eltsize)) { Scm_Error("Size too big: %ld", size); } } /*===================================================================== * Generic vectors */ /* * Constructor */ static void vector_print(ScmObj obj, ScmPort *port, ScmWriteContext *ctx) { SCM_PUTZ("#(", -1, port); for (int i=0; i<SCM_VECTOR_SIZE(obj); i++) { if (i != 0) SCM_PUTC(' ', port); Scm_Write(SCM_VECTOR_ELEMENT(obj, i), SCM_OBJ(port), Scm_WriteContextMode(ctx)); } SCM_PUTZ(")", -1, port); } static int vector_compare(ScmObj x, ScmObj y, int equalp) { if (equalp) { /* Vector equality is handled in Scm_Eq* and will never come here, but just in case. */ return Scm_EqualP(x, y)? 0 : 1; } /* Follow srfi-114 */ ScmWord xlen = SCM_VECTOR_SIZE(x); ScmWord ylen = SCM_VECTOR_SIZE(y); if (xlen < ylen) return -1; if (xlen > ylen) return 1; for (int i=0; i<xlen; i++) { int r = Scm_Compare(SCM_VECTOR_ELEMENT(x, i), SCM_VECTOR_ELEMENT(y, i)); if (r != 0) return r; } return 0; } SCM_DEFINE_BUILTIN_CLASS_FLAGS(Scm_VectorClass, vector_print, vector_compare, NULL, NULL, SCM_CLASS_SEQUENCE_CPL, SCM_CLASS_AGGREGATE); static ScmVector *make_vector(ScmSmallInt size) { check_size(size, sizeof(ScmObj)); ScmVector *v = SCM_NEW2(ScmVector *, sizeof(ScmVector) + sizeof(ScmObj)*(size-1)); SCM_SET_CLASS(v, SCM_CLASS_VECTOR); #if GAUCHE_API_VERSION >= 1000 v->size_flags = (size << 1); #else v->size = size; #endif return v; } ScmObj Scm_MakeVector(ScmSmallInt size, ScmObj fill) { if (size < 0) { Scm_Error("vector size must be a positive integer, but got %d", size); } ScmVector *v = make_vector(size); if (SCM_UNBOUNDP(fill)) fill = SCM_UNDEFINED; for (ScmSmallInt i=0; i<size; i++) v->elements[i] = fill; return SCM_OBJ(v); } ScmObj Scm_ListToVector(ScmObj l, ScmSmallInt start, ScmSmallInt end) { ScmVector *v; if (end < 0) { ScmSmallInt size = Scm_Length(l); if (size < 0) Scm_Error("bad list: %S", l); SCM_CHECK_START_END(start, end, size); v = make_vector(size - start); } else { SCM_CHECK_START_END(start, end, end); v = make_vector(end - start); } ScmObj e = Scm_ListTail(l, start, SCM_UNBOUND); for (ScmSmallInt i=0; i<end-start; i++, e=SCM_CDR(e)) { if (!SCM_PAIRP(e)) { Scm_Error("list too short: %S", l); } v->elements[i] = SCM_CAR(e); } return SCM_OBJ(v); } ScmObj Scm_VectorToList(ScmVector *v, ScmSmallInt start, ScmSmallInt end) { ScmWord len = SCM_VECTOR_SIZE(v); SCM_CHECK_START_END(start, end, len); return Scm_ArrayToList(SCM_VECTOR_ELEMENTS(v)+start, end-start); } /* * Accessors */ /* NB: we're permissive about the out-of-range index here; the strict check (for Scheme routines) should be done in the stub file, since Scheme version may receive bignum, which can't be passed to C API. */ ScmObj Scm_VectorRef(ScmVector *vec, ScmSmallInt i, ScmObj fallback) { if (i < 0 || i >= SCM_VECTOR_SIZE(vec)) return fallback; return vec->elements[i]; } ScmObj Scm_VectorSet(ScmVector *vec, ScmSmallInt i, ScmObj obj) { SCM_VECTOR_CHECK_MUTABLE(vec); if (i >= 0 && i < SCM_VECTOR_SIZE(vec)) vec->elements[i] = obj; return obj; } ScmObj Scm_VectorFill(ScmVector *vec, ScmObj fill, ScmSmallInt start, ScmSmallInt end) { SCM_VECTOR_CHECK_MUTABLE(vec); ScmSmallInt len = SCM_VECTOR_SIZE(vec); SCM_CHECK_START_END(start, end, len); for (ScmSmallInt i=start; i < end; i++) { SCM_VECTOR_ELEMENT(vec, i) = fill; } return SCM_OBJ(vec); } ScmObj Scm_VectorCopy(ScmVector *vec, ScmSmallInt start, ScmSmallInt end, ScmObj fill) { ScmSmallInt len = SCM_VECTOR_SIZE(vec); ScmVector *v = NULL; if (end < 0) end = len; if (end < start) { Scm_Error("vector-copy: start (%ld) is greater than end (%ld)", start, end); } else if (end == start) { v = make_vector(0); } else { if (SCM_UNBOUNDP(fill)) fill = SCM_UNDEFINED; v = make_vector(end - start); for (ScmSmallInt i=0; i<end-start; i++) { if (i+start < 0 || i+start >= len) { SCM_VECTOR_ELEMENT(v, i) = fill; } else { SCM_VECTOR_ELEMENT(v, i) = SCM_VECTOR_ELEMENT(vec, i+start); } } } return SCM_OBJ(v); } /*===================================================================== * Uniform vectors */ /* * Class stuff */ static ScmClass *uvector_cpl[] = { SCM_CLASS_STATIC_PTR(Scm_UVectorClass), SCM_CLASS_STATIC_PTR(Scm_SequenceClass), SCM_CLASS_STATIC_PTR(Scm_CollectionClass), SCM_CLASS_STATIC_PTR(Scm_TopClass), NULL }; SCM_DEFINE_BUILTIN_CLASS(Scm_UVectorClass, NULL, NULL, NULL, NULL, uvector_cpl+1); #define DEF_UVCLASS(TAG, tag) \ static void SCM_CPP_CAT3(print_,tag,vector)(ScmObj obj, ScmPort *out, \ ScmWriteContext *ctx); \ static int SCM_CPP_CAT3(compare_,tag,vector)(ScmObj x, ScmObj y, int equalp); \ SCM_DEFINE_BUILTIN_CLASS_FLAGS(SCM_CPP_CAT3(Scm_,TAG,VectorClass), \ SCM_CPP_CAT3(print_,tag,vector), \ SCM_CPP_CAT3(compare_,tag,vector), \ NULL, NULL, uvector_cpl, \ SCM_CLASS_AGGREGATE); DEF_UVCLASS(S8, s8) DEF_UVCLASS(U8, u8) DEF_UVCLASS(S16, s16) DEF_UVCLASS(U16, u16) DEF_UVCLASS(S32, s32) DEF_UVCLASS(U32, u32) DEF_UVCLASS(S64, s64) DEF_UVCLASS(U64, u64) DEF_UVCLASS(F16, f16) DEF_UVCLASS(F32, f32) DEF_UVCLASS(F64, f64) DEF_UVCLASS(C32, c32) DEF_UVCLASS(C64, c64) DEF_UVCLASS(C128, c128) /* * Some generic APIs */ ScmUVectorType Scm_UVectorType(ScmClass *klass) { if (SCM_EQ(klass, SCM_CLASS_S8VECTOR)) return SCM_UVECTOR_S8; if (SCM_EQ(klass, SCM_CLASS_U8VECTOR)) return SCM_UVECTOR_U8; if (SCM_EQ(klass, SCM_CLASS_S16VECTOR)) return SCM_UVECTOR_S16; if (SCM_EQ(klass, SCM_CLASS_U16VECTOR)) return SCM_UVECTOR_U16; if (SCM_EQ(klass, SCM_CLASS_S32VECTOR)) return SCM_UVECTOR_S32; if (SCM_EQ(klass, SCM_CLASS_U32VECTOR)) return SCM_UVECTOR_U32; if (SCM_EQ(klass, SCM_CLASS_S64VECTOR)) return SCM_UVECTOR_S64; if (SCM_EQ(klass, SCM_CLASS_U64VECTOR)) return SCM_UVECTOR_U64; if (SCM_EQ(klass, SCM_CLASS_F16VECTOR)) return SCM_UVECTOR_F16; if (SCM_EQ(klass, SCM_CLASS_F32VECTOR)) return SCM_UVECTOR_F32; if (SCM_EQ(klass, SCM_CLASS_F64VECTOR)) return SCM_UVECTOR_F64; if (SCM_EQ(klass, SCM_CLASS_C32VECTOR)) return SCM_UVECTOR_C32; if (SCM_EQ(klass, SCM_CLASS_C64VECTOR)) return SCM_UVECTOR_C64; if (SCM_EQ(klass, SCM_CLASS_C128VECTOR)) return SCM_UVECTOR_C128; else return SCM_UVECTOR_INVALID; } const char *Scm_UVectorTypeName(int type) /* for error msgs etc. */ { switch (type) { case SCM_UVECTOR_S8: return "s8vector"; case SCM_UVECTOR_U8: return "u8vector"; case SCM_UVECTOR_S16: return "s16vector"; case SCM_UVECTOR_U16: return "u16vector"; case SCM_UVECTOR_S32: return "s32vector"; case SCM_UVECTOR_U32: return "u32vector"; case SCM_UVECTOR_S64: return "s64vector"; case SCM_UVECTOR_U64: return "u64vector"; case SCM_UVECTOR_F16: return "f16vector"; case SCM_UVECTOR_F32: return "f32vector"; case SCM_UVECTOR_F64: return "f64vector"; case SCM_UVECTOR_C32: return "c32vector"; case SCM_UVECTOR_C64: return "c64vector"; case SCM_UVECTOR_C128: return "c128vector"; default: return "invalid type of uvector (possibly implementation error)"; } } /* Returns the size of element of the uvector of given class */ int Scm_UVectorElementSize(ScmClass *klass) { static const int sizes[] = { 1, 1, 2, 2, 4, 4, 8, 8, 2, sizeof(float), sizeof(double), -1, sizeof(ScmHalfComplex), sizeof(ScmFloatComplex), sizeof(ScmDoubleComplex), -1 }; int ind = (int)Scm_UVectorType(klass); if (ind >= 0) return sizes[ind]; return -1; } /* Returns the size of the vector body in bytes */ int Scm_UVectorSizeInBytes(ScmUVector *uv) { return SCM_UVECTOR_SIZE(uv) * Scm_UVectorElementSize(Scm_ClassOf(SCM_OBJ(uv))); } /* Generic constructor */ ScmObj Scm_MakeUVectorFull(ScmClass *klass, ScmSmallInt size, void *init, int immutable, void *owner) { int eltsize = Scm_UVectorElementSize(klass); SCM_ASSERT(eltsize >= 1); ScmUVector *vec = SCM_NEW(ScmUVector); SCM_SET_CLASS(vec, klass); if (init) { vec->elements = init; /* trust the caller */ } else { check_size(size, eltsize); vec->elements = SCM_NEW_ATOMIC2(void*, size*eltsize); } vec->size_flags = (size << 1)|(immutable?1:0); vec->owner = owner; return SCM_OBJ(vec); } ScmObj Scm_MakeUVector(ScmClass *klass, ScmSmallInt size, void *init) { return Scm_MakeUVectorFull(klass, size, init, FALSE, NULL); } ScmObj Scm_ListToUVector(ScmClass *klass, ScmObj list, int clamp) { ScmUVectorType type = Scm_UVectorType(klass); if (type < 0) Scm_Error("uvector class required, but got: %S", klass); ScmSize length = Scm_Length(list); if (length < 0) Scm_Error("improper list not allowed: %S", list); if (length > SCM_SMALL_INT_MAX) Scm_Error("list is too long: %,,,,100S", list); ScmUVector *v = (ScmUVector*)Scm_MakeUVector(klass, (ScmSmallInt)length, NULL); ScmObj cp = list; for (ScmSize i=0; i<length; i++, cp = SCM_CDR(cp)) { switch (type) { case SCM_UVECTOR_S8: SCM_S8VECTOR_ELEMENTS(v)[i] = (int8_t)Scm_GetInteger8Clamp(SCM_CAR(cp), clamp, NULL); break; case SCM_UVECTOR_U8: SCM_U8VECTOR_ELEMENTS(v)[i] = (uint8_t)Scm_GetIntegerU8Clamp(SCM_CAR(cp), clamp, NULL); break; case SCM_UVECTOR_S16: SCM_S16VECTOR_ELEMENTS(v)[i] = (int16_t)Scm_GetInteger16Clamp(SCM_CAR(cp), clamp, NULL); break; case SCM_UVECTOR_U16: SCM_U16VECTOR_ELEMENTS(v)[i] = (uint16_t)Scm_GetIntegerU16Clamp(SCM_CAR(cp), clamp, NULL); break; case SCM_UVECTOR_S32: SCM_S32VECTOR_ELEMENTS(v)[i] = (int32_t)Scm_GetInteger32Clamp(SCM_CAR(cp), clamp, NULL); break; case SCM_UVECTOR_U32: SCM_U32VECTOR_ELEMENTS(v)[i] = (uint32_t)Scm_GetIntegerU32Clamp(SCM_CAR(cp), clamp, NULL); break; case SCM_UVECTOR_S64: SCM_S64VECTOR_ELEMENTS(v)[i] = (int64_t)Scm_GetInteger64Clamp(SCM_CAR(cp), clamp, NULL); break; case SCM_UVECTOR_U64: SCM_U64VECTOR_ELEMENTS(v)[i] = (uint64_t)Scm_GetIntegerU64Clamp(SCM_CAR(cp), clamp, NULL); break; case SCM_UVECTOR_F16: SCM_F16VECTOR_ELEMENTS(v)[i] = (ScmHalfFloat)Scm_DoubleToHalf(Scm_GetDouble(SCM_CAR(cp))); break; case SCM_UVECTOR_F32: SCM_F32VECTOR_ELEMENTS(v)[i] = (float)Scm_GetDouble(SCM_CAR(cp)); break; case SCM_UVECTOR_F64: SCM_F64VECTOR_ELEMENTS(v)[i] = Scm_GetDouble(SCM_CAR(cp)); break; case SCM_UVECTOR_C32: SCM_C32VECTOR_ELEMENTS(v)[i] = Scm_GetHalfComplex(SCM_CAR(cp)); break; case SCM_UVECTOR_C64: SCM_C64VECTOR_ELEMENTS(v)[i] = Scm_GetFloatComplex(SCM_CAR(cp)); break; case SCM_UVECTOR_C128: SCM_C128VECTOR_ELEMENTS(v)[i] = Scm_GetDoubleComplex(SCM_CAR(cp)); break; default: Scm_Error("[internal error] unknown uvector type given to Scm_ListToUVector"); } } return SCM_OBJ(v); } /* Generic accessor, intended to be called from VM loop. (As the 'VM' in the name suggests, the return value of this API should immediately be passed to VM. See comments on FFX in gauche/number.h) */ ScmObj Scm_VMUVectorRef(ScmUVector *v, int t, ScmSmallInt k, ScmObj fallback) { SCM_ASSERT(Scm_UVectorType(SCM_CLASS_OF(v)) == t); if (k < 0 || k >= SCM_UVECTOR_SIZE(v)) { if (SCM_UNBOUNDP(fallback)) { Scm_Error("%s-ref index out of range: %ld", Scm_UVectorTypeName(t), k); } return fallback; } switch (t) { case SCM_UVECTOR_S8: return SCM_MAKE_INT(SCM_S8VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_U8: return SCM_MAKE_INT(SCM_U8VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_S16: return SCM_MAKE_INT(SCM_S16VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_U16: return SCM_MAKE_INT(SCM_U16VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_S32: return Scm_MakeInteger(SCM_S32VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_U32: return Scm_MakeIntegerU(SCM_U32VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_S64: return Scm_MakeInteger64(SCM_S64VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_U64: return Scm_MakeIntegerU64(SCM_U64VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_F16: return Scm_VMReturnFlonum(Scm_HalfToDouble(SCM_F16VECTOR_ELEMENT(v, k))); case SCM_UVECTOR_F32: return Scm_VMReturnFlonum((double)(SCM_F32VECTOR_ELEMENT(v, k))); case SCM_UVECTOR_F64: return Scm_VMReturnFlonum(SCM_F64VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_C32: return Scm_HalfComplexToComplex(SCM_C32VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_C64: return Scm_FloatComplexToComplex(SCM_C64VECTOR_ELEMENT(v, k)); case SCM_UVECTOR_C128: return Scm_DoubleComplexToComplex(SCM_C128VECTOR_ELEMENT(v, k)); default: Scm_Error("[internal error] unknown uvector type given to Scm_VMUVectorRef"); return SCM_UNDEFINED; /* dummy */ } } /* Generic modifier */ ScmObj Scm_UVectorSet(ScmUVector *v, int t, ScmSmallInt k, ScmObj val, int clamp) { SCM_ASSERT(Scm_UVectorType(SCM_CLASS_OF(v)) == t); SCM_UVECTOR_CHECK_MUTABLE(SCM_OBJ(v)); if (k < 0 || k >= SCM_UVECTOR_SIZE(v)) { Scm_Error("%s-set! index out of range: %ld", Scm_UVectorTypeName(t), k); } switch (t) { case SCM_UVECTOR_S8: SCM_S8VECTOR_ELEMENTS(v)[k] = Scm_GetInteger8Clamp(val, clamp, NULL); break; case SCM_UVECTOR_U8: SCM_U8VECTOR_ELEMENTS(v)[k] = Scm_GetIntegerU8Clamp(val, clamp, NULL); break; case SCM_UVECTOR_S16: SCM_S16VECTOR_ELEMENTS(v)[k] = Scm_GetInteger16Clamp(val, clamp, NULL); break; case SCM_UVECTOR_U16: SCM_U16VECTOR_ELEMENTS(v)[k] = Scm_GetIntegerU16Clamp(val, clamp, NULL); break; case SCM_UVECTOR_S32: SCM_S32VECTOR_ELEMENTS(v)[k] = Scm_GetInteger32Clamp(val, clamp, NULL); break; case SCM_UVECTOR_U32: SCM_U32VECTOR_ELEMENTS(v)[k] = Scm_GetIntegerU32Clamp(val, clamp, NULL); break; case SCM_UVECTOR_S64: SCM_S64VECTOR_ELEMENTS(v)[k] = Scm_GetInteger64Clamp(val, clamp, NULL); break; case SCM_UVECTOR_U64: SCM_U64VECTOR_ELEMENTS(v)[k] = Scm_GetIntegerU64Clamp(val, clamp, NULL); break; case SCM_UVECTOR_F16: SCM_F16VECTOR_ELEMENTS(v)[k] = Scm_DoubleToHalf(Scm_GetDouble(val)); break; case SCM_UVECTOR_F32: SCM_F32VECTOR_ELEMENTS(v)[k] = (float)Scm_GetDouble(val); break; case SCM_UVECTOR_F64: SCM_F64VECTOR_ELEMENTS(v)[k] = Scm_GetDouble(val); break; case SCM_UVECTOR_C32: SCM_C32VECTOR_ELEMENTS(v)[k] = Scm_GetHalfComplex(val); break; case SCM_UVECTOR_C64: SCM_C64VECTOR_ELEMENTS(v)[k] = Scm_GetFloatComplex(val); break; case SCM_UVECTOR_C128: SCM_C128VECTOR_ELEMENTS(v)[k] = Scm_GetDoubleComplex(val); break; default: Scm_Error("[internal error] unknown uvector type given to Scm_VMUVectorRef"); } return SCM_UNDEFINED; } /* * Inidividual constructors for convenience */ #define DEF_UVCTOR_FILL(tag, T) \ ScmObj SCM_CPP_CAT3(Scm_Make,tag,Vector)(ScmSmallInt size, T fill) \ { \ ScmUVector *u = \ (ScmUVector*)Scm_MakeUVector(SCM_CPP_CAT3(SCM_CLASS_,tag,VECTOR),\ size, NULL); \ T *elts = SCM_CPP_CAT3(SCM_,tag,VECTOR_ELEMENTS)(u); \ for (ScmSmallInt i=0; i<size; i++) *elts++ = fill; \ return SCM_OBJ(u); \ } #define DEF_UVCTOR_ARRAY(tag, T) \ ScmObj SCM_CPP_CAT3(Scm_Make,tag,VectorFromArray)(ScmSmallInt size, \ const T array[]) \ { \ check_size(size, sizeof(T)); \ T *z = SCM_NEW_ATOMIC_ARRAY(T, size); \ memcpy(z, array, size*sizeof(T)); \ return Scm_MakeUVector(SCM_CPP_CAT3(SCM_CLASS_,tag,VECTOR), \ size, (void*)z); \ } \ ScmObj SCM_CPP_CAT3(Scm_Make,tag,VectorFromArrayShared)(ScmSmallInt size,\ T array[]) \ { \ return Scm_MakeUVector(SCM_CPP_CAT3(SCM_CLASS_,tag,VECTOR), \ size, (void*)array); \ } /* NB: For u8vector and s8vector we can let memset() to fill the contents, expecting it's optimized. */ ScmObj Scm_MakeS8Vector(ScmSmallInt size, int8_t fill) { ScmUVector *u = (ScmUVector*)Scm_MakeUVector(SCM_CLASS_S8VECTOR, size, NULL); (void)memset(SCM_S8VECTOR_ELEMENTS(u), fill, size); return SCM_OBJ(u); } ScmObj Scm_MakeU8Vector(ScmSmallInt size, uint8_t fill) { ScmUVector *u = (ScmUVector*)Scm_MakeUVector(SCM_CLASS_U8VECTOR, size, NULL); (void)memset(SCM_U8VECTOR_ELEMENTS(u), fill, size); return SCM_OBJ(u); } DEF_UVCTOR_FILL(S16, int16_t) DEF_UVCTOR_FILL(U16, uint16_t) DEF_UVCTOR_FILL(S32, int32_t) DEF_UVCTOR_FILL(U32, uint32_t) DEF_UVCTOR_FILL(S64, int64_t) DEF_UVCTOR_FILL(U64, uint64_t) DEF_UVCTOR_FILL(F16, ScmHalfFloat) DEF_UVCTOR_FILL(F32, float) DEF_UVCTOR_FILL(F64, double) DEF_UVCTOR_FILL(C32, ScmHalfComplex) DEF_UVCTOR_FILL(C64, ScmFloatComplex) DEF_UVCTOR_FILL(C128,ScmDoubleComplex) DEF_UVCTOR_ARRAY(S8, int8_t) DEF_UVCTOR_ARRAY(U8, uint8_t) DEF_UVCTOR_ARRAY(S16, int16_t) DEF_UVCTOR_ARRAY(U16, uint16_t) DEF_UVCTOR_ARRAY(S32, int32_t) DEF_UVCTOR_ARRAY(U32, uint32_t) DEF_UVCTOR_ARRAY(S64, int64_t) DEF_UVCTOR_ARRAY(U64, uint64_t) DEF_UVCTOR_ARRAY(F16, ScmHalfFloat) DEF_UVCTOR_ARRAY(F32, float) DEF_UVCTOR_ARRAY(F64, double) DEF_UVCTOR_ARRAY(C32, ScmHalfComplex) DEF_UVCTOR_ARRAY(C64, ScmFloatComplex) DEF_UVCTOR_ARRAY(C128,ScmDoubleComplex) /* * Reader */ ScmObj Scm_ReadUVector(ScmPort *port, const char *tag, ScmReadContext *ctx) { ScmChar c; SCM_GETC(c, port); if (c != '(') Scm_Error("bad uniform vector syntax for %s", tag); ScmObj list = Scm_ReadList(SCM_OBJ(port), ')'); ScmClass *klass = NULL; if (strcmp(tag, "s8") == 0) klass = SCM_CLASS_S8VECTOR; else if (strcmp(tag, "u8") == 0) klass = SCM_CLASS_U8VECTOR; else if (strcmp(tag, "s16") == 0) klass = SCM_CLASS_S16VECTOR; else if (strcmp(tag, "u16") == 0) klass = SCM_CLASS_U16VECTOR; else if (strcmp(tag, "s32") == 0) klass = SCM_CLASS_S32VECTOR; else if (strcmp(tag, "u32") == 0) klass = SCM_CLASS_U32VECTOR; else if (strcmp(tag, "s64") == 0) klass = SCM_CLASS_S64VECTOR; else if (strcmp(tag, "u64") == 0) klass = SCM_CLASS_U64VECTOR; else if (strcmp(tag, "f16") == 0) klass = SCM_CLASS_F16VECTOR; else if (strcmp(tag, "f32") == 0) klass = SCM_CLASS_F32VECTOR; else if (strcmp(tag, "f64") == 0) klass = SCM_CLASS_F64VECTOR; else if (strcmp(tag, "c32") == 0) klass = SCM_CLASS_C32VECTOR; else if (strcmp(tag, "c64") == 0) klass = SCM_CLASS_C64VECTOR; else if (strcmp(tag, "c128") == 0) klass = SCM_CLASS_C128VECTOR; else Scm_Error("invalid unform vector tag: %s", tag); ScmObj uv = Scm_ListToUVector(klass, list, 0); /* If we are reading source file, let literal uvectors be immutable. */ if (Scm_ReadContextLiteralImmutable(ctx)) { SCM_UVECTOR_IMMUTABLE_SET(uv, TRUE); } return uv; } /* * Class-dependent functions */ /* printer */ #define DEF_PRINT(TAG, tag, T, pr) \ static void SCM_CPP_CAT3(print_,tag,vector)(ScmObj obj, \ ScmPort *out, \ ScmWriteContext *ctx) \ { \ const ScmWriteControls *wp = \ Scm_GetWriteControls(ctx, out->writeState); \ Scm_Printf(out, "#"#tag"("); \ for (int i=0; i<SCM_CPP_CAT3(SCM_,TAG,VECTOR_SIZE)(obj); i++) { \ T elt = SCM_CPP_CAT3(SCM_,TAG,VECTOR_ELEMENTS)(obj)[i]; \ if (i != 0) Scm_Printf(out, " "); \ if (wp->printLength >= 0 && i >= wp->printLength) { \ Scm_Printf(out, "..."); \ break; \ } \ pr(out, elt); \ } \ Scm_Printf(out, ")"); \ } #define spr(out, elt) Scm_Printf(out, "%d", elt) #define upr(out, elt) Scm_Printf(out, "%u", elt) #define fpr(out, elt) Scm_PrintDouble(out, (double)elt, 0) #define c32pr(out, elt) \ do { \ Scm_PrintDouble(out, Scm_HalfToDouble(SCM_HALF_COMPLEX_REAL(elt)), 0); \ Scm_Putz("+", 1, out); \ Scm_PrintDouble(out, Scm_HalfToDouble(SCM_HALF_COMPLEX_IMAG(elt)), 0); \ Scm_Putz("i", 1, out); \ } while (0) #define c64pr(out, elt) \ do { \ Scm_PrintDouble(out, (double)crealf(elt), 0); \ Scm_Putz("+", 1, out); \ Scm_PrintDouble(out, (double)cimagf(elt), 0); \ Scm_Putz("i", 1, out); \ } while (0) #define c128pr(out, elt) \ do { \ Scm_PrintDouble(out, creal(elt), 0); \ Scm_Putz("+", 1, out); \ Scm_PrintDouble(out, cimag(elt), 0); \ Scm_Putz("i", 1, out); \ } while (0) static inline void s64pr(ScmPort *out, int64_t elt) { #if SIZEOF_LONG == 4 char buf[50]; snprintf(buf, 50, "%lld", elt); Scm_Printf(out, "%s", buf); #else Scm_Printf(out, "%ld", elt); #endif } static inline void u64pr(ScmPort *out, uint64_t elt) { #if SIZEOF_LONG == 4 char buf[50]; snprintf(buf, 50, "%llu", elt); Scm_Printf(out, "%s", buf); #else Scm_Printf(out, "%lu", elt); #endif } static inline void f16pr(ScmPort *out, ScmHalfFloat elt) { Scm_PrintDouble(out, Scm_HalfToDouble(elt), 0); } DEF_PRINT(S8, s8, int8_t, spr) DEF_PRINT(U8, u8, uint8_t, upr) DEF_PRINT(S16, s16, int16_t, spr) DEF_PRINT(U16, u16, uint16_t, upr) DEF_PRINT(S32, s32, int32_t, spr) DEF_PRINT(U32, u32, uint32_t, upr) DEF_PRINT(S64, s64, int64_t, s64pr) DEF_PRINT(U64, u64, uint64_t, u64pr) DEF_PRINT(F16, f16, ScmHalfFloat, f16pr) DEF_PRINT(F32, f32, float, fpr) DEF_PRINT(F64, f64, double, fpr) DEF_PRINT(C32, c32, ScmHalfComplex, c32pr) DEF_PRINT(C64, c64, ScmFloatComplex, c64pr) DEF_PRINT(C128, c128, ScmDoubleComplex, c128pr) /* comparer */ #define DEF_CMP(TAG, tag, T, eq, lt) \ static int SCM_CPP_CAT3(compare_,tag,vector)(ScmObj x, ScmObj y, int equalp) \ { \ ScmSmallInt xlen = SCM_CPP_CAT3(SCM_,TAG,VECTOR_SIZE)(x); \ ScmSmallInt ylen = SCM_CPP_CAT3(SCM_,TAG,VECTOR_SIZE)(y); \ if (equalp) { \ if (xlen != ylen) return -1; \ for (ScmSmallInt i=0; i<xlen; i++) { \ T xx = SCM_CPP_CAT3(SCM_,TAG,VECTOR_ELEMENTS)(x)[i]; \ T yy = SCM_CPP_CAT3(SCM_,TAG,VECTOR_ELEMENTS)(y)[i]; \ if (!eq(xx,yy)) return -1; \ } \ return 0; \ } else { \ if (xlen != ylen) return (xlen < ylen) ? -1 : 1; \ for (ScmSmallInt i=0; i<xlen; i++) { \ T xx = SCM_CPP_CAT3(SCM_,TAG,VECTOR_ELEMENTS)(x)[i]; \ T yy = SCM_CPP_CAT3(SCM_,TAG,VECTOR_ELEMENTS)(y)[i]; \ if (lt(xx, yy)) return -1; \ if (!eq(xx,yy)) return 1; \ } \ return 0; \ } \ } #define common_eqv(x, y) ((x)==(y)) #define common_lt(x, y) ((x)<(y)) #define f16eqv(a, b) SCM_HALF_FLOAT_CMP(==, a, b) #define f16lt(a, b) SCM_HALF_FLOAT_CMP(<, a, b) static inline int c32eqv(ScmHalfComplex x, ScmHalfComplex y) { return (SCM_HALF_FLOAT_CMP(==, x.r, y.r) && SCM_HALF_FLOAT_CMP(==, x.i, y.i)); } static inline int c32lt(ScmHalfComplex x, ScmHalfComplex y) { return (SCM_HALF_FLOAT_CMP(<, x.r, y.r) || (SCM_HALF_FLOAT_CMP(==, x.r, y.r) && SCM_HALF_FLOAT_CMP(<, x.i, y.i))); } static inline int c64lt(ScmFloatComplex x, ScmFloatComplex y) { return (crealf(x) < crealf(y) || (crealf(x) == crealf(y) && cimagf(x) < cimagf(y))); } static inline int c128lt(ScmDoubleComplex x, ScmDoubleComplex y) { return (creal(x) < creal(y) || (creal(x) == creal(y) && cimag(x) < cimag(y))); } DEF_CMP(S8, s8, int8_t, common_eqv, common_lt) DEF_CMP(U8, u8, uint8_t, common_eqv, common_lt) DEF_CMP(S16, s16, int16_t, common_eqv, common_lt) DEF_CMP(U16, u16, uint16_t, common_eqv, common_lt) DEF_CMP(S32, s32, int32_t, common_eqv, common_lt) DEF_CMP(U32, u32, uint32_t, common_eqv, common_lt) DEF_CMP(S64, s64, int64_t, common_eqv, common_lt) DEF_CMP(U64, u64, uint64_t, common_eqv, common_lt) DEF_CMP(F16, f16, ScmHalfFloat, f16eqv, f16lt) DEF_CMP(F32, f32, float, common_eqv, common_lt) DEF_CMP(F64, f64, double, common_eqv, common_lt) DEF_CMP(C32, c32, ScmHalfComplex, c32eqv, c32lt) DEF_CMP(C64, c64, ScmFloatComplex, common_eqv, c64lt) DEF_CMP(C128, c128, ScmDoubleComplex, common_eqv, c128lt) /*===================================================================== * Utility */ const uint8_t *Scm_GetBytes(ScmObj obj, ScmSize *size) { if (SCM_UVECTORP(obj)) { *size = Scm_UVectorSizeInBytes(SCM_UVECTOR(obj)); return (const uint8_t*)SCM_UVECTOR_ELEMENTS(obj); } else if (SCM_STRINGP(obj)) { ScmSmallInt s; const char *z = Scm_GetStringContent(SCM_STRING(obj), &s, 0, 0); *size = s; return (const uint8_t*)z; } else { *size = 0; return 0; } }
428499.c
/* ----------------------------------------------------------------- * Programmer(s): Allan Taylor, Alan Hindmarsh and * Radu Serban @ LLNL * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2022, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example problem for KINSOL (parallel machine case) using the BBD * preconditioner. * * This example solves a nonlinear system that arises from a system * of partial differential equations. The PDE system is a food web * population model, with predator-prey interaction and diffusion on * the unit square in two dimensions. The dependent variable vector * is the following: * * 1 2 ns * c = (c , c , ..., c ) (denoted by the variable cc) * * and the PDE's are as follows: * * i i * 0 = d(i)*(c + c ) + f (x,y,c) (i=1,...,ns) * xx yy i * * where * * i ns j * f (x,y,c) = c * (b(i) + sum a(i,j)*c ) * i j=1 * * The number of species is ns = 2 * np, with the first np being * prey and the last np being predators. The number np is both the * number of prey and predator species. The coefficients a(i,j), * b(i), d(i) are: * * a(i,i) = -AA (all i) * a(i,j) = -GG (i <= np , j > np) * a(i,j) = EE (i > np, j <= np) * b(i) = BB * (1 + alpha * x * y) (i <= np) * b(i) =-BB * (1 + alpha * x * y) (i > np) * d(i) = DPREY (i <= np) * d(i) = DPRED ( i > np) * * The various scalar parameters are set using define's or in * routine InitUserData. * * The boundary conditions are: normal derivative = 0, and the * initial guess is constant in x and y, but the final solution * is not. * * The PDEs are discretized by central differencing on an MX by * MY mesh. * * The nonlinear system is solved by KINSOL using the method * specified in the local variable globalstrat. * * The preconditioner matrix is a band-block-diagonal matrix * using the KINBBDPRE module. The half-bandwidths are as follows: * * Difference quotient half-bandwidths mldq = mudq = 2*ns - 1 * Retained banded blocks have half-bandwidths mlkeep = mukeep = ns. * * ----------------------------------------------------------------- * References: * * 1. Peter N. Brown and Youcef Saad, * Hybrid Krylov Methods for Nonlinear Systems of Equations * LLNL report UCRL-97645, November 1987. * * 2. Peter N. Brown and Alan C. Hindmarsh, * Reduced Storage Matrix Methods in Stiff ODE systems, * Lawrence Livermore National Laboratory Report UCRL-95088, * Rev. 1, June 1987, and Journal of Applied Mathematics and * Computation, Vol. 31 (May 1989), pp. 40-91. (Presents a * description of the time-dependent version of this test * problem.) * -------------------------------------------------------------------------- * Run command line: mpirun -np N -machinefile machines kinFoodWeb_kry_bbd_p * where N = NPEX * NPEY is the number of processors. * -------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <kinsol/kinsol.h> /* access to KINSOL func., consts. */ #include <nvector/nvector_parallel.h> /* access to MPI parallel N_Vector */ #include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */ #include <kinsol/kinsol_bbdpre.h> /* access to BBD preconditioner */ #include <sundials/sundials_dense.h> /* use generic dense solver in precond. */ #include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */ #include <sundials/sundials_math.h> /* access to SUNMAX, SUNRabs, SUNRsqrt */ #include <mpi.h> /* Problem Constants */ #define NUM_SPECIES 6 /* must equal 2*(number of prey or predators) number of prey = number of predators */ #define PI RCONST(3.1415926535898) /* pi */ #define NPEX 2 /* number of processors in the x-direction */ #define NPEY 2 /* number of processors in the y-direction */ #define MXSUB 10 /* number of x mesh points per subgrid */ #define MYSUB 10 /* number of y mesh points per subgrid */ #define MX (NPEX*MXSUB) /* number of mesh points in the x-direction */ #define MY (NPEY*MYSUB) /* number of mesh points in the y-direction */ #define NSMXSUB (NUM_SPECIES * MXSUB) #define NSMXSUB2 (NUM_SPECIES * (MXSUB+2)) #define NEQ (NUM_SPECIES*MX*MY) /* number of equations in the system */ #define AA RCONST(1.0) /* value of coefficient AA in above eqns */ #define EE RCONST(10000.) /* value of coefficient EE in above eqns */ #define GG RCONST(0.5e-6) /* value of coefficient GG in above eqns */ #define BB RCONST(1.0) /* value of coefficient BB in above eqns */ #define DPREY RCONST(1.0) /* value of coefficient dprey above */ #define DPRED RCONST(0.5) /* value of coefficient dpred above */ #define ALPHA RCONST(1.0) /* value of coefficient alpha above */ #define AX RCONST(1.0) /* total range of x variable */ #define AY RCONST(1.0) /* total range of y variable */ #define FTOL RCONST(1.e-7) /* ftol tolerance */ #define STOL RCONST(1.e-13) /* stol tolerance */ #define THOUSAND RCONST(1000.0) /* one thousand */ #define ZERO RCONST(0.0) /* 0. */ #define ONE RCONST(1.0) /* 1. */ #define PREYIN RCONST(1.0) /* initial guess for prey concentrations. */ #define PREDIN RCONST(30000.0)/* initial guess for predator concs. */ /* User-defined vector access macro: IJ_Vptr */ /* IJ_Vptr is defined in order to translate from the underlying 3D structure of the dependent variable vector to the 1D storage scheme for an N-vector. IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to indices is = 0, jx = i, jy = j. */ #define IJ_Vptr(vv,i,j) (&NV_Ith_P(vv, i*NUM_SPECIES + j*NSMXSUB)) /* Type : UserData contains problem constants and extended array */ typedef struct { realtype **acoef, *bcoef; N_Vector rates; realtype *cox, *coy; realtype ax, ay, dx, dy; sunindextype Nlocal; int mx, my, ns, np; realtype cext[NUM_SPECIES * (MXSUB+2)*(MYSUB+2)]; int my_pe, isubx, isuby, nsmxsub, nsmxsub2; MPI_Comm comm; } *UserData; /* Functions called by the KINSOL Solver */ static int func(N_Vector cc, N_Vector fval, void *user_data); static int ccomm(sunindextype Nlocal, N_Vector cc, void *data); static int func_local(sunindextype Nlocal, N_Vector cc, N_Vector fval, void *user_data); /* Private Helper Functions */ static UserData AllocUserData(void); static void InitUserData(int my_pe, sunindextype Nlocal, MPI_Comm comm, UserData data); static void FreeUserData(UserData data); static void SetInitialProfiles(N_Vector cc, N_Vector sc); static void PrintHeader(int globalstrategy, int maxl, int maxlrst, sunindextype mudq, sunindextype mldq, sunindextype mukeep, sunindextype mlkeep, realtype fnormtol, realtype scsteptol); static void PrintOutput(int my_pe, MPI_Comm comm, N_Vector cc); static void PrintFinalStats(void *kmem); static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data); static realtype DotProd(int size, realtype *x1, realtype *x2); static void BSend(MPI_Comm comm, int my_pe, int isubx, int isuby, int dsizex, int dsizey, realtype *cdata); static void BRecvPost(MPI_Comm comm, MPI_Request request[], int my_pe, int isubx, int isuby, int dsizex, int dsizey, realtype *cext, realtype *buffer); static void BRecvWait(MPI_Request request[], int isubx, int isuby, int dsizex, realtype *cext, realtype *buffer); static int check_retval(void *retvalvalue, const char *funcname, int opt, int id); /* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- */ int main(int argc, char *argv[]) { SUNContext sunctx; int globalstrategy; sunindextype Nlocal; realtype fnormtol, scsteptol, dq_rel_uu; N_Vector cc, sc, constraints; UserData data; int retval, maxl, maxlrst; int my_pe, npes, npelast = NPEX*NPEY-1; void *kmem; SUNLinearSolver LS; sunindextype mudq, mldq, mukeep, mlkeep; MPI_Comm comm; cc = sc = constraints = NULL; kmem = NULL; LS = NULL; data = NULL; /* Get processor number and total number of pe's */ MPI_Init(&argc, &argv); comm = MPI_COMM_WORLD; MPI_Comm_size(comm, &npes); MPI_Comm_rank(comm, &my_pe); if (npes != NPEX*NPEY) { if (my_pe == 0) fprintf(stderr, "\nMPI_ERROR(0): npes = %d is not equal to NPEX*NPEY = %d\n", npes,NPEX*NPEY); MPI_Finalize(); return(1); } /* Create the SUNDIALS simulation context that all SUNDIALS objects require */ retval = SUNContext_Create(&comm, &sunctx); if (check_retval(&retval, "SUNContext_Create", 1, my_pe)) MPI_Abort(comm, 1); /* Allocate memory, and set problem data, initial values, tolerances */ /* Set local vector length */ Nlocal = NUM_SPECIES*MXSUB*MYSUB; /* Allocate and initialize user data block */ data = AllocUserData(); if (check_retval((void *)data, "AllocUserData", 2, my_pe)) MPI_Abort(comm, 1); InitUserData(my_pe, Nlocal, comm, data); /* Set global strategy retval */ globalstrategy = KIN_NONE; /* Allocate and initialize vectors */ cc = N_VNew_Parallel(comm, Nlocal, NEQ, sunctx); if (check_retval((void *)cc, "N_VNew_Parallel", 0, my_pe)) MPI_Abort(comm, 1); sc = N_VNew_Parallel(comm, Nlocal, NEQ, sunctx); if (check_retval((void *)sc, "N_VNew_Parallel", 0, my_pe)) MPI_Abort(comm, 1); data->rates = N_VNew_Parallel(comm, Nlocal, NEQ, sunctx); if (check_retval((void *)data->rates, "N_VNew_Parallel", 0, my_pe)) MPI_Abort(comm, 1); constraints = N_VNew_Parallel(comm, Nlocal, NEQ, sunctx); if (check_retval((void *)constraints, "N_VNew_Parallel", 0, my_pe)) MPI_Abort(comm, 1); N_VConst(ZERO, constraints); SetInitialProfiles(cc, sc); fnormtol = FTOL; scsteptol = STOL; /* Call KINCreate/KINInit to initialize KINSOL: nvSpec points to machine environment data A pointer to KINSOL problem memory is returned and stored in kmem. */ kmem = KINCreate(sunctx); if (check_retval((void *)kmem, "KINCreate", 0, my_pe)) MPI_Abort(comm, 1); /* Vector cc passed as template vector. */ retval = KINInit(kmem, func, cc); if (check_retval(&retval, "KINInit", 1, my_pe)) MPI_Abort(comm, 1); retval = KINSetUserData(kmem, data); if (check_retval(&retval, "KINSetUserData", 1, my_pe)) MPI_Abort(comm, 1); retval = KINSetConstraints(kmem, constraints); if (check_retval(&retval, "KINSetConstraints", 1, my_pe)) MPI_Abort(comm, 1); retval = KINSetFuncNormTol(kmem, fnormtol); if (check_retval(&retval, "KINSetFuncNormTol", 1, my_pe)) MPI_Abort(comm, 1); retval = KINSetScaledStepTol(kmem, scsteptol); if (check_retval(&retval, "KINSetScaledStepTol", 1, my_pe)) MPI_Abort(comm, 1); /* We no longer need the constraints vector since KINSetConstraints creates a private copy for KINSOL to use. */ N_VDestroy(constraints); /* Create SUNLinSol_SPGMR object with right preconditioning and the maximum Krylov dimension maxl */ maxl = 20; LS = SUNLinSol_SPGMR(cc, SUN_PREC_RIGHT, maxl, sunctx); if(check_retval((void *)LS, "SUNLinSol_SPGMR", 0, my_pe)) MPI_Abort(comm, 1); /* Attach the linear solver to KINSOL */ retval = KINSetLinearSolver(kmem, LS, NULL); if (check_retval(&retval, "KINSetLinearSolver", 1, my_pe)) MPI_Abort(comm, 1); /* Set the maximum number of restarts */ maxlrst = 2; retval = SUNLinSol_SPGMRSetMaxRestarts(LS, maxlrst); if (check_retval(&retval, "SUNLinSol_SPGMRSetMaxRestarts", 1, my_pe)) MPI_Abort(comm, 1); /* Call KINBBDPrecInit to initialize and allocate memory for the band-block-diagonal preconditioner, and specify the local and communication functions func_local and gcomm=NULL (all communication needed for the func_local is already done in func). */ dq_rel_uu = ZERO; mudq = mldq = 2*NUM_SPECIES - 1; mukeep = mlkeep = NUM_SPECIES; /* Initialize BBD preconditioner */ retval = KINBBDPrecInit(kmem, Nlocal, mudq, mldq, mukeep, mlkeep, dq_rel_uu, func_local, NULL); if (check_retval(&retval, "KINBBDPrecInit", 1, my_pe)) MPI_Abort(comm, 1); /* Print out the problem size, solution parameters, initial guess. */ if (my_pe == 0) PrintHeader(globalstrategy, maxl, maxlrst, mudq, mldq, mukeep, mlkeep, fnormtol, scsteptol); /* Call KINSol and print output concentration profile */ retval = KINSol(kmem, /* KINSol memory block */ cc, /* initial guess on input; solution vector */ globalstrategy, /* global strategy choice */ sc, /* scaling vector for the variable cc */ sc); /* scaling vector for function values fval */ if (check_retval(&retval, "KINSol", 1, my_pe)) MPI_Abort(comm, 1); if (my_pe == 0) printf("\n\nComputed equilibrium species concentrations:\n"); if (my_pe == 0 || my_pe == npelast) PrintOutput(my_pe, comm, cc); /* Print final statistics and free memory */ if (my_pe == 0) PrintFinalStats(kmem); N_VDestroy(cc); N_VDestroy(sc); KINFree(&kmem); SUNLinSolFree(LS); FreeUserData(data); SUNContext_Free(&sunctx); MPI_Finalize(); return(0); } /* Readability definitions used in other routines below */ #define acoef (data->acoef) #define bcoef (data->bcoef) #define cox (data->cox) #define coy (data->coy) /* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY KINSOL *-------------------------------------------------------------------- */ /* * ccomm routine. This routine performs all communication * between processors of data needed to calculate f. */ static int ccomm(sunindextype Nlocal, N_Vector cc, void *userdata) { realtype *cdata, *cext, buffer[2*NUM_SPECIES*MYSUB]; UserData data; MPI_Comm comm; int my_pe, isubx, isuby, nsmxsub, nsmysub; MPI_Request request[4]; /* Get comm, my_pe, subgrid indices, data sizes, extended array cext */ data = (UserData) userdata; comm = data->comm; my_pe = data->my_pe; isubx = data->isubx; isuby = data->isuby; nsmxsub = data->nsmxsub; nsmysub = NUM_SPECIES*MYSUB; cext = data->cext; cdata = N_VGetArrayPointer(cc); /* Start receiving boundary data from neighboring PEs */ BRecvPost(comm, request, my_pe, isubx, isuby, nsmxsub, nsmysub, cext, buffer); /* Send data from boundary of local grid to neighboring PEs */ BSend(comm, my_pe, isubx, isuby, nsmxsub, nsmysub, cdata); /* Finish receiving boundary data from neighboring PEs */ BRecvWait(request, isubx, isuby, nsmxsub, cext, buffer); return(0); } /* * System function for predator-prey system - calculation part */ static int func_local(sunindextype Nlocal, N_Vector cc, N_Vector fval, void *user_data) { realtype xx, yy, *cxy, *rxy, *fxy, dcydi, dcyui, dcxli, dcxri; realtype *cext, dely, delx, *cdata; int i, jx, jy, is, ly; int isubx, isuby, nsmxsub, nsmxsub2; int shifty, offsetc, offsetce, offsetcl, offsetcr, offsetcd, offsetcu; UserData data; data = (UserData)user_data; cdata = N_VGetArrayPointer(cc); /* Get subgrid indices, data sizes, extended work array cext */ isubx = data->isubx; isuby = data->isuby; nsmxsub = data->nsmxsub; nsmxsub2 = data->nsmxsub2; cext = data->cext; /* Copy local segment of cc vector into the working extended array cext */ offsetc = 0; offsetce = nsmxsub2 + NUM_SPECIES; for (ly = 0; ly < MYSUB; ly++) { for (i = 0; i < nsmxsub; i++) cext[offsetce+i] = cdata[offsetc+i]; offsetc = offsetc + nsmxsub; offsetce = offsetce + nsmxsub2; } /* To facilitate homogeneous Neumann boundary conditions, when this is a boundary PE, copy data from the first interior mesh line of cc to cext */ /* If isuby = 0, copy x-line 2 of cc to cext */ if (isuby == 0) { for (i = 0; i < nsmxsub; i++) cext[NUM_SPECIES+i] = cdata[nsmxsub+i]; } /* If isuby = NPEY-1, copy x-line MYSUB-1 of cc to cext */ if (isuby == NPEY-1) { offsetc = (MYSUB-2)*nsmxsub; offsetce = (MYSUB+1)*nsmxsub2 + NUM_SPECIES; for (i = 0; i < nsmxsub; i++) cext[offsetce+i] = cdata[offsetc+i]; } /* If isubx = 0, copy y-line 2 of cc to cext */ if (isubx == 0) { for (ly = 0; ly < MYSUB; ly++) { offsetc = ly*nsmxsub + NUM_SPECIES; offsetce = (ly+1)*nsmxsub2; for (i = 0; i < NUM_SPECIES; i++) cext[offsetce+i] = cdata[offsetc+i]; } } /* If isubx = NPEX-1, copy y-line MXSUB-1 of cc to cext */ if (isubx == NPEX-1) { for (ly = 0; ly < MYSUB; ly++) { offsetc = (ly+1)*nsmxsub - 2*NUM_SPECIES; offsetce = (ly+2)*nsmxsub2 - NUM_SPECIES; for (i = 0; i < NUM_SPECIES; i++) cext[offsetce+i] = cdata[offsetc+i]; } } /* Loop over all mesh points, evaluating rate arra at each point */ delx = data->dx; dely = data->dy; shifty = (MXSUB+2)*NUM_SPECIES; for (jy = 0; jy < MYSUB; jy++) { yy = dely*(jy + isuby * MYSUB); for (jx = 0; jx < MXSUB; jx++) { xx = delx * (jx + isubx * MXSUB); cxy = IJ_Vptr(cc,jx,jy); rxy = IJ_Vptr(data->rates,jx,jy); fxy = IJ_Vptr(fval,jx,jy); WebRate(xx, yy, cxy, rxy, user_data); offsetc = (jx+1)*NUM_SPECIES + (jy+1)*NSMXSUB2; offsetcd = offsetc - shifty; offsetcu = offsetc + shifty; offsetcl = offsetc - NUM_SPECIES; offsetcr = offsetc + NUM_SPECIES; for (is = 0; is < NUM_SPECIES; is++) { /* differencing in x */ dcydi = cext[offsetc+is] - cext[offsetcd+is]; dcyui = cext[offsetcu+is] - cext[offsetc+is]; /* differencing in y */ dcxli = cext[offsetc+is] - cext[offsetcl+is]; dcxri = cext[offsetcr+is] - cext[offsetc+is]; /* compute the value at xx , yy */ fxy[is] = (coy)[is] * (dcyui - dcydi) + (cox)[is] * (dcxri - dcxli) + rxy[is]; } /* end of is loop */ } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * System function routine. Evaluate f(cc). First call ccomm to do * communication of subgrid boundary data into cext. Then calculate f * by a call to func_local. */ static int func(N_Vector cc, N_Vector fval, void *user_data) { UserData data; data = (UserData) user_data; /* Call ccomm to do inter-processor communicaiton */ ccomm(data->Nlocal, cc, data); /* Call func_local to calculate all right-hand sides */ func_local(data->Nlocal, cc, fval, data); return(0); } /* * Interaction rate function routine */ static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data) { int i; realtype fac; UserData data; data = (UserData)user_data; for (i = 0; i<NUM_SPECIES; i++) ratesxy[i] = DotProd(NUM_SPECIES, cxy, acoef[i]); fac = ONE + ALPHA * xx * yy; for (i = 0; i < NUM_SPECIES; i++) ratesxy[i] = cxy[i] * ( bcoef[i] * fac + ratesxy[i] ); } /* * Dot product routine for realtype arrays */ static realtype DotProd(int size, realtype *x1, realtype *x2) { int i; realtype *xx1, *xx2, temp = ZERO; xx1 = x1; xx2 = x2; for (i = 0; i < size; i++) temp += (*xx1++) * (*xx2++); return(temp); } /* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- */ /* * Allocate memory for data structure of type UserData */ static UserData AllocUserData(void) { UserData data; data = (UserData) malloc(sizeof *data); acoef = SUNDlsMat_newDenseMat(NUM_SPECIES, NUM_SPECIES); bcoef = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); cox = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); coy = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); return(data); } /* * Load problem constants in data */ static void InitUserData(int my_pe, sunindextype Nlocal, MPI_Comm comm, UserData data) { int i, j, np; realtype *a1,*a2, *a3, *a4, dx2, dy2; data->mx = MX; data->my = MY; data->ns = NUM_SPECIES; data->np = NUM_SPECIES/2; data->ax = AX; data->ay = AY; data->dx = (data->ax)/(MX-1); data->dy = (data->ay)/(MY-1); data->my_pe = my_pe; data->Nlocal = Nlocal; data->comm = comm; data->isuby = my_pe/NPEX; data->isubx = my_pe - data->isuby*NPEX; data->nsmxsub = NUM_SPECIES * MXSUB; data->nsmxsub2 = NUM_SPECIES * (MXSUB+2); /* Set up the coefficients a and b plus others found in the equations */ np = data->np; dx2=(data->dx)*(data->dx); dy2=(data->dy)*(data->dy); for (i = 0; i < np; i++) { a1= &(acoef[i][np]); a2= &(acoef[i+np][0]); a3= &(acoef[i][0]); a4= &(acoef[i+np][np]); /* Fill in the portion of acoef in the four quadrants, row by row */ for (j = 0; j < np; j++) { *a1++ = -GG; *a2++ = EE; *a3++ = ZERO; *a4++ = ZERO; } /* and then change the diagonal elements of acoef to -AA */ acoef[i][i]=-AA; acoef[i+np][i+np] = -AA; bcoef[i] = BB; bcoef[i+np] = -BB; cox[i]=DPREY/dx2; cox[i+np]=DPRED/dx2; coy[i]=DPREY/dy2; coy[i+np]=DPRED/dy2; } } /* * Free data memory */ static void FreeUserData(UserData data) { SUNDlsMat_destroyMat(acoef); free(bcoef); free(cox); free(coy); N_VDestroy(data->rates); free(data); } /* * Set initial conditions in cc */ static void SetInitialProfiles(N_Vector cc, N_Vector sc) { int i, jx, jy; realtype *cloc, *sloc; realtype ctemp[NUM_SPECIES], stemp[NUM_SPECIES]; /* Initialize arrays ctemp and stemp used in the loading process */ for (i = 0; i < NUM_SPECIES/2; i++) { ctemp[i] = PREYIN; stemp[i] = ONE; } for (i = NUM_SPECIES/2; i < NUM_SPECIES; i++) { ctemp[i] = PREDIN; stemp[i] = RCONST(0.00001); } /* Load initial profiles into cc and sc vector from ctemp and stemp. */ for (jy = 0; jy < MYSUB; jy++) { for (jx=0; jx < MXSUB; jx++) { cloc = IJ_Vptr(cc,jx,jy); sloc = IJ_Vptr(sc,jx,jy); for (i = 0; i < NUM_SPECIES; i++){ cloc[i] = ctemp[i]; sloc[i] = stemp[i]; } } } } /* * Print first lines of output (problem description) */ static void PrintHeader(int globalstrategy, int maxl, int maxlrst, sunindextype mudq, sunindextype mldq, sunindextype mukeep, sunindextype mlkeep, realtype fnormtol, realtype scsteptol) { printf("\nPredator-prey test problem-- KINSol (parallel-BBD version)\n\n"); printf("Mesh dimensions = %d X %d\n", MX, MY); printf("Number of species = %d\n", NUM_SPECIES); printf("Total system size = %d\n\n", NEQ); printf("Subgrid dimensions = %d X %d\n", MXSUB, MYSUB); printf("Processor array is %d X %d\n\n", NPEX, NPEY); printf("Flag globalstrategy = %d (0 = None, 1 = Linesearch)\n", globalstrategy); printf("Linear solver is SPGMR with maxl = %d, maxlrst = %d\n", maxl, maxlrst); printf("Preconditioning uses band-block-diagonal matrix from KINBBDPRE\n"); printf(" Difference quotient half-bandwidths: mudq = %ld, mldq = %ld\n", (long int) mudq, (long int) mldq); printf(" Retained band block half-bandwidths: mukeep = %ld, mlkeep = %ld\n", (long int) mukeep, (long int) mlkeep); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: fnormtol = %Lg scsteptol = %Lg\n", fnormtol, scsteptol); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #else printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #endif printf("\nInitial profile of concentration\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("At all mesh points: %Lg %Lg %Lg %Lg %Lg %Lg\n", PREYIN,PREYIN,PREYIN, PREDIN,PREDIN,PREDIN); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN,PREYIN,PREYIN, PREDIN,PREDIN,PREDIN); #else printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN,PREYIN,PREYIN, PREDIN,PREDIN,PREDIN); #endif } /* * Print sample of current cc values */ static void PrintOutput(int my_pe, MPI_Comm comm, N_Vector cc) { int is, i0, npelast; realtype *ct, tempc[NUM_SPECIES]; MPI_Status status; npelast = NPEX*NPEY - 1; ct = N_VGetArrayPointer(cc); /* Send the cc values (for all species) at the top right mesh point to PE 0 */ if (my_pe == npelast) { i0 = NUM_SPECIES*(MXSUB*MYSUB-1); if (npelast!=0) MPI_Send(&ct[i0],NUM_SPECIES,MPI_SUNREALTYPE,0,0,comm); else /* single processor case */ for (is = 0; is < NUM_SPECIES; is++) tempc[is]=ct[i0+is]; } /* On PE 0, receive the cc values at top right, then print performance data and sampled solution values */ if (my_pe == 0) { if (npelast != 0) MPI_Recv(&tempc[0],NUM_SPECIES,MPI_SUNREALTYPE,npelast,0,comm,&status); printf("\nAt bottom left:"); for (is = 0; is < NUM_SPECIES; is++){ if ((is%6)*6== is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } printf("\n\nAt top right:"); for (is = 0; is < NUM_SPECIES; is++) { if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",tempc[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",tempc[is]); #else printf(" %g",tempc[is]); #endif } printf("\n\n"); } } /* * Print final statistics contained in iopt */ static void PrintFinalStats(void *kmem) { long int nni, nfe, nli, npe, nps, ncfl, nfeSG; int retval; retval = KINGetNumNonlinSolvIters(kmem, &nni); check_retval(&retval, "KINGetNumNonlinSolvIters", 1, 0); retval = KINGetNumFuncEvals(kmem, &nfe); check_retval(&retval, "KINGetNumFuncEvals", 1, 0); retval = KINGetNumLinIters(kmem, &nli); check_retval(&retval, "KINGetNumLinIters", 1, 0); retval = KINGetNumPrecEvals(kmem, &npe); check_retval(&retval, "KINGetNumPrecEvals", 1, 0); retval = KINGetNumPrecSolves(kmem, &nps); check_retval(&retval, "KINGetNumPrecSolves", 1, 0); retval = KINGetNumLinConvFails(kmem, &ncfl); check_retval(&retval, "KINGetNumLinConvFails", 1, 0); retval = KINGetNumLinFuncEvals(kmem, &nfeSG); check_retval(&retval, "KINGetNumLinFuncEvals", 1, 0); printf("Final Statistics.. \n"); printf("nni = %5ld nli = %5ld\n", nni, nli); printf("nfe = %5ld nfeSG = %5ld\n", nfe, nfeSG); printf("nps = %5ld npe = %5ld ncfl = %5ld\n", nps, npe, ncfl); } /* * Routine to send boundary data to neighboring PEs */ static void BSend(MPI_Comm comm, int my_pe, int isubx, int isuby, int dsizex, int dsizey, realtype *cdata) { int i, ly; int offsetc, offsetbuf; realtype bufleft[NUM_SPECIES*MYSUB], bufright[NUM_SPECIES*MYSUB]; /* If isuby > 0, send data from bottom x-line of u */ if (isuby != 0) MPI_Send(&cdata[0], dsizex, MPI_SUNREALTYPE, my_pe-NPEX, 0, comm); /* If isuby < NPEY-1, send data from top x-line of u */ if (isuby != NPEY-1) { offsetc = (MYSUB-1)*dsizex; MPI_Send(&cdata[offsetc], dsizex, MPI_SUNREALTYPE, my_pe+NPEX, 0, comm); } /* If isubx > 0, send data from left y-line of u (via bufleft) */ if (isubx != 0) { for (ly = 0; ly < MYSUB; ly++) { offsetbuf = ly*NUM_SPECIES; offsetc = ly*dsizex; for (i = 0; i < NUM_SPECIES; i++) bufleft[offsetbuf+i] = cdata[offsetc+i]; } MPI_Send(&bufleft[0], dsizey, MPI_SUNREALTYPE, my_pe-1, 0, comm); } /* If isubx < NPEX-1, send data from right y-line of u (via bufright) */ if (isubx != NPEX-1) { for (ly = 0; ly < MYSUB; ly++) { offsetbuf = ly*NUM_SPECIES; offsetc = offsetbuf*MXSUB + (MXSUB-1)*NUM_SPECIES; for (i = 0; i < NUM_SPECIES; i++) bufright[offsetbuf+i] = cdata[offsetc+i]; } MPI_Send(&bufright[0], dsizey, MPI_SUNREALTYPE, my_pe+1, 0, comm); } } /* * Routine to start receiving boundary data from neighboring PEs. * Notes: * 1) buffer should be able to hold 2*NUM_SPECIES*MYSUB realtype entries, * should be passed to both the BRecvPost and BRecvWait functions, and * should not be manipulated between the two calls. * 2) request should have 4 entries, and should be passed in both calls also. */ static void BRecvPost(MPI_Comm comm, MPI_Request request[], int my_pe, int isubx, int isuby, int dsizex, int dsizey, realtype *cext, realtype *buffer) { int offsetce; /* Have bufleft and bufright use the same buffer */ realtype *bufleft = buffer, *bufright = buffer+NUM_SPECIES*MYSUB; /* If isuby > 0, receive data for bottom x-line of cext */ if (isuby != 0) MPI_Irecv(&cext[NUM_SPECIES], dsizex, MPI_SUNREALTYPE, my_pe-NPEX, 0, comm, &request[0]); /* If isuby < NPEY-1, receive data for top x-line of cext */ if (isuby != NPEY-1) { offsetce = NUM_SPECIES*(1 + (MYSUB+1)*(MXSUB+2)); MPI_Irecv(&cext[offsetce], dsizex, MPI_SUNREALTYPE, my_pe+NPEX, 0, comm, &request[1]); } /* If isubx > 0, receive data for left y-line of cext (via bufleft) */ if (isubx != 0) { MPI_Irecv(&bufleft[0], dsizey, MPI_SUNREALTYPE, my_pe-1, 0, comm, &request[2]); } /* If isubx < NPEX-1, receive data for right y-line of cext (via bufright) */ if (isubx != NPEX-1) { MPI_Irecv(&bufright[0], dsizey, MPI_SUNREALTYPE, my_pe+1, 0, comm, &request[3]); } } /* * Routine to finish receiving boundary data from neighboring PEs. * Notes: * 1) buffer should be able to hold 2*NUM_SPECIES*MYSUB realtype entries, * should be passed to both the BRecvPost and BRecvWait functions, and * should not be manipulated between the two calls. * 2) request should have 4 entries, and should be passed in both calls also. */ static void BRecvWait(MPI_Request request[], int isubx, int isuby, int dsizex, realtype *cext, realtype *buffer) { int i, ly; int dsizex2, offsetce, offsetbuf; realtype *bufleft = buffer, *bufright = buffer+NUM_SPECIES*MYSUB; MPI_Status status; dsizex2 = dsizex + 2*NUM_SPECIES; /* If isuby > 0, receive data for bottom x-line of cext */ if (isuby != 0) MPI_Wait(&request[0],&status); /* If isuby < NPEY-1, receive data for top x-line of cext */ if (isuby != NPEY-1) MPI_Wait(&request[1],&status); /* If isubx > 0, receive data for left y-line of cext (via bufleft) */ if (isubx != 0) { MPI_Wait(&request[2],&status); /* Copy the buffer to cext */ for (ly = 0; ly < MYSUB; ly++) { offsetbuf = ly*NUM_SPECIES; offsetce = (ly+1)*dsizex2; for (i = 0; i < NUM_SPECIES; i++) cext[offsetce+i] = bufleft[offsetbuf+i]; } } /* If isubx < NPEX-1, receive data for right y-line of cext (via bufright) */ if (isubx != NPEX-1) { MPI_Wait(&request[3],&status); /* Copy the buffer to cext */ for (ly = 0; ly < MYSUB; ly++) { offsetbuf = ly*NUM_SPECIES; offsetce = (ly+2)*dsizex2 - NUM_SPECIES; for (i = 0; i < NUM_SPECIES; i++) cext[offsetce+i] = bufright[offsetbuf+i]; } } } /* * Check function return value... * opt == 0 means SUNDIALS function allocates memory so check if * returned NULL pointer * opt == 1 means SUNDIALS function returns a retval so check if * retval >= 0 * opt == 2 means function allocates memory so check if returned * NULL pointer */ static int check_retval(void *retvalvalue, const char *funcname, int opt, int id) { int *errretval; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && retvalvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR(%d): %s() failed - returned NULL pointer\n\n", id, funcname); return(1); } /* Check if retval < 0 */ else if (opt == 1) { errretval = (int *) retvalvalue; if (*errretval < 0) { fprintf(stderr, "\nSUNDIALS_ERROR(%d): %s() failed with retval = %d\n\n", id, funcname, *errretval); return(1); } } /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && retvalvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR(%d): %s() failed - returned NULL pointer\n\n", id, funcname); return(1); } return(0); }
327392.c
/* ** $Id: loslib.c,v 1.64 2016/04/18 13:06:55 roberto Exp $ ** Standard Operating System library ** See Copyright Notice in lua.h */ #define loslib_c #define LUA_LIB #include "lprefix.h" #include <errno.h> #include <locale.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** {================================================================== ** List of valid conversion specifiers for the 'strftime' function; ** options are grouped by length; group of length 2 start with '||'. ** =================================================================== */ #if !defined(LUA_STRFTIMEOPTIONS) /* { */ /* options for ANSI C 89 (only 1-char options) */ #define L_STRFTIMEC89 "aAbBcdHIjmMpSUwWxXyYZ%" /* options for ISO C 99 and POSIX */ #define L_STRFTIMEC99 "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \ "||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */ /* options for Windows */ #define L_STRFTIMEWIN "aAbBcdHIjmMpSUwWxXyYzZ%" \ "||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */ #if defined(LUA_USE_WINDOWS) #define LUA_STRFTIMEOPTIONS L_STRFTIMEWIN #elif defined(LUA_USE_C89) #define LUA_STRFTIMEOPTIONS L_STRFTIMEC89 #else /* C99 specification */ #define LUA_STRFTIMEOPTIONS L_STRFTIMEC99 #endif #endif /* } */ /* }================================================================== */ /* ** {================================================================== ** Configuration for time-related stuff ** =================================================================== */ #if !defined(l_time_t) /* { */ /* ** type to represent time_t in Lua */ #define l_timet lua_Integer #define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t)) static time_t l_checktime (lua_State *L, int arg) { lua_Integer t = luaL_checkinteger(L, arg); luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds"); return (time_t)t; } #endif /* } */ #if !defined(l_gmtime) /* { */ /* ** By default, Lua uses gmtime/localtime, except when POSIX is available, ** where it uses gmtime_r/localtime_r */ #if defined(LUA_USE_POSIX) /* { */ #define l_gmtime(t,r) gmtime_r(t,r) #define l_localtime(t,r) localtime_r(t,r) #else /* }{ */ /* ISO C definitions */ #define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t)) #define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t)) #endif /* } */ #endif /* } */ /* }================================================================== */ /* ** {================================================================== ** Configuration for 'tmpnam': ** By default, Lua uses tmpnam except when POSIX is available, where ** it uses mkstemp. ** =================================================================== */ #if !defined(lua_tmpnam) /* { */ #if defined(LUA_USE_POSIX) /* { */ #include <unistd.h> #define LUA_TMPNAMBUFSIZE 32 #if !defined(LUA_TMPNAMTEMPLATE) #define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX" #endif #define lua_tmpnam(b,e) { \ strcpy(b, LUA_TMPNAMTEMPLATE); \ e = mkstemp(b); \ if (e != -1) close(e); \ e = (e == -1); } #else /* }{ */ /* ISO C definitions */ #define LUA_TMPNAMBUFSIZE L_tmpnam #define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } #endif /* } */ #endif /* } */ /* }================================================================== */ static int os_execute (lua_State *L) { const char *cmd = luaL_optstring(L, 1, NULL); int stat = system(cmd); if (cmd != NULL) return luaL_execresult(L, stat); else { lua_pushboolean(L, stat); /* true if there is a shell */ return 1; } } static int os_remove (lua_State *L) { const char *filename = luaL_checkstring(L, 1); return luaL_fileresult(L, remove(filename) == 0, filename); } static int os_rename (lua_State *L) { const char *fromname = luaL_checkstring(L, 1); const char *toname = luaL_checkstring(L, 2); return luaL_fileresult(L, rename(fromname, toname) == 0, NULL); } static int os_tmpname (lua_State *L) { char buff[LUA_TMPNAMBUFSIZE]; int err; lua_tmpnam(buff, err); if (err) return luaL_error(L, "unable to generate a unique filename"); lua_pushstring(L, buff); return 1; } static int os_getenv (lua_State *L) { lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */ return 1; } static int os_clock (lua_State *L) { lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC); return 1; } /* ** {====================================================== ** Time/Date operations ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S, ** wday=%w+1, yday=%j, isdst=? } ** ======================================================= */ static void setfield (lua_State *L, const char *key, int value) { lua_pushinteger(L, value); lua_setfield(L, -2, key); } static void setboolfield (lua_State *L, const char *key, int value) { if (value < 0) /* undefined? */ return; /* does not set field */ lua_pushboolean(L, value); lua_setfield(L, -2, key); } /* ** Set all fields from structure 'tm' in the table on top of the stack */ static void setallfields (lua_State *L, struct tm *stm) { setfield(L, "sec", stm->tm_sec); setfield(L, "min", stm->tm_min); setfield(L, "hour", stm->tm_hour); setfield(L, "day", stm->tm_mday); setfield(L, "month", stm->tm_mon + 1); setfield(L, "year", stm->tm_year + 1900); setfield(L, "wday", stm->tm_wday + 1); setfield(L, "yday", stm->tm_yday + 1); setboolfield(L, "isdst", stm->tm_isdst); } static int getboolfield (lua_State *L, const char *key) { int res; res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1); lua_pop(L, 1); return res; } /* maximum value for date fields (to avoid arithmetic overflows with 'int') */ #if !defined(L_MAXDATEFIELD) #define L_MAXDATEFIELD (INT_MAX / 2) #endif static int getfield (lua_State *L, const char *key, int d, int delta) { int isnum; int t = lua_getfield(L, -1, key); /* get field and its type */ lua_Integer res = lua_tointegerx(L, -1, &isnum); if (!isnum) { /* field is not an integer? */ if (t != LUA_TNIL) /* some other value? */ return luaL_error(L, "field '%s' is not an integer", key); else if (d < 0) /* absent field; no default? */ return luaL_error(L, "field '%s' missing in date table", key); res = d; } else { if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD)) return luaL_error(L, "field '%s' is out-of-bound", key); res -= delta; } lua_pop(L, 1); return (int)res; } static const char *checkoption (lua_State *L, const char *conv, ptrdiff_t convlen, char *buff) { const char *option = LUA_STRFTIMEOPTIONS; int oplen = 1; /* length of options being checked */ for (; *option != '\0' && oplen <= convlen; option += oplen) { if (*option == '|') /* next block? */ oplen++; /* will check options with next length (+1) */ else if (memcmp(conv, option, oplen) == 0) { /* match? */ memcpy(buff, conv, oplen); /* copy valid option to buffer */ buff[oplen] = '\0'; return conv + oplen; /* return next item */ } } luaL_argerror(L, 1, lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv)); return conv; /* to avoid warnings */ } /* maximum size for an individual 'strftime' item */ #define SIZETIMEFMT 250 static int os_date (lua_State *L) { size_t slen; const char *s = luaL_optlstring(L, 1, "%c", &slen); time_t t = luaL_opt(L, l_checktime, 2, time(NULL)); const char *se = s + slen; /* 's' end */ struct tm tmr, *stm; if (*s == '!') { /* UTC? */ stm = l_gmtime(&t, &tmr); s++; /* skip '!' */ } else stm = l_localtime(&t, &tmr); if (stm == NULL) /* invalid date? */ luaL_error(L, "time result cannot be represented in this installation"); if (strcmp(s, "*t") == 0) { lua_createtable(L, 0, 9); /* 9 = number of fields */ setallfields(L, stm); } else { char cc[4]; /* buffer for individual conversion specifiers */ luaL_Buffer b; cc[0] = '%'; luaL_buffinit(L, &b); while (s < se) { if (*s != '%') /* not a conversion specifier? */ luaL_addchar(&b, *s++); else { size_t reslen; char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT); s++; /* skip '%' */ s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */ reslen = strftime(buff, SIZETIMEFMT, cc, stm); luaL_addsize(&b, reslen); } } luaL_pushresult(&b); } return 1; } static int os_time (lua_State *L) { time_t t; if (lua_isnoneornil(L, 1)) /* called without args? */ t = time(NULL); /* get current time */ else { struct tm ts; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); /* make sure table is at the top */ ts.tm_sec = getfield(L, "sec", 0, 0); ts.tm_min = getfield(L, "min", 0, 0); ts.tm_hour = getfield(L, "hour", 12, 0); ts.tm_mday = getfield(L, "day", -1, 0); ts.tm_mon = getfield(L, "month", -1, 1); ts.tm_year = getfield(L, "year", -1, 1900); ts.tm_isdst = getboolfield(L, "isdst"); t = mktime(&ts); setallfields(L, &ts); /* update fields with normalized values */ } if (t != (time_t)(l_timet)t || t == (time_t)(-1)) luaL_error(L, "time result cannot be represented in this installation"); l_pushtime(L, t); return 1; } static int os_difftime (lua_State *L) { time_t t1 = l_checktime(L, 1); time_t t2 = l_checktime(L, 2); lua_pushnumber(L, (lua_Number)difftime(t1, t2)); return 1; } /* }====================================================== */ static int os_setlocale (lua_State *L) { static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME}; static const char *const catnames[] = {"all", "collate", "ctype", "monetary", "numeric", "time", NULL}; const char *l = luaL_optstring(L, 1, NULL); int op = luaL_checkoption(L, 2, "all", catnames); lua_pushstring(L, setlocale(cat[op], l)); return 1; } static int os_exit (lua_State *L) { int status; if (lua_isboolean(L, 1)) status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE); else status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS); if (lua_toboolean(L, 2)) lua_close(L); if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */ return 0; } static const luaL_Reg syslib[] = { {"clock", os_clock}, {"date", os_date}, {"difftime", os_difftime}, {"execute", os_execute}, {"exit", os_exit}, {"getenv", os_getenv}, {"remove", os_remove}, {"rename", os_rename}, {"setlocale", os_setlocale}, {"time", os_time}, {"tmpname", os_tmpname}, {NULL, NULL} }; /* }====================================================== */ LUAMOD_API int luaopen_os (lua_State *L) { luaL_newlib(L, syslib); return 1; }
689005.c
/* Generated automatically by ../modules.py */ #include "config_platform.h" {"_bisect", init_bisect}, {"_collections", init_collections}, {"_csv", init_csv}, {"_functools", init_functools}, {"_hashlib", init_hashlib}, {"_heapq", init_heapq}, {"_hotshot", init_hotshot}, {"_io", init_io}, {"_json", init_json}, {"_locale", init_locale}, {"_lsprof", init_lsprof}, {"_md5", init_md5}, {"_multibytecodec", init_multibytecodec}, {"_random", init_random}, {"_sha", init_sha}, {"_sha256", init_sha256}, {"_sha512", init_sha512}, {"_sqlite3", init_sqlite3}, {"_ssl", init_ssl}, {"_struct", init_struct}, {"array", initarray}, {"audioop", initaudioop}, {"binascii", initbinascii}, {"bz2", initbz2}, {"cPickle", initcPickle}, {"cStringIO", initcStringIO}, {"cmath", initcmath}, {"datetime", initdatetime}, {"future_builtins", initfuture_builtins}, {"itertools", inititertools}, {"math", initmath}, {"mmap", initmmap}, {"operator", initoperator}, {"parser", initparser}, {"strop", initstrop}, {"time", inittime}, {"unicodedata", initunicodedata}, {"zlib", initzlib}, #ifdef _HAVE_NIS {"nis", initnis}, #endif #ifdef _FREEBSD_ {"_multiprocessing", init_multiprocessing}, {"_multiprocessing", init_multiprocessing}, #endif #ifdef _LINUX_ {"_multiprocessing", init_multiprocessing}, {"spwd", initspwd}, #endif #ifdef _DARWIN_ {"_multiprocessing", init_multiprocessing}, #endif #ifdef _CYGWIN_ {"_multiprocessing", init_multiprocessing}, #endif #ifdef _UNIX_ {"_elementtree", init_elementtree}, {"_socket", init_socket}, {"crypt", initcrypt}, {"fcntl", initfcntl}, {"grp", initgrp}, {"posix", initposix}, {"pwd", initpwd}, {"pyexpat", initpyexpat}, {"resource", initresource}, {"select", initselect}, {"syslog", initsyslog}, {"termios", inittermios}, #endif #ifdef _WIN32_ {"_elementtree", init_elementtree}, {"_multiprocessing", init_multiprocessing}, {"_socket", init_socket}, {"nt", initnt}, {"pyexpat", initpyexpat}, {"select", initselect}, {"msvcrt", initmsvcrt}, {"_subprocess", init_subprocess}, {"_winreg", init_winreg}, #endif #if !defined(_ARM_) && !defined(_CYGWIN_) {"_ctypes", init_ctypes}, #endif
140686.c
#ifdef pr_fmt #undef pr_fmt #endif #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/module.h> #include <linux/printk.h> #include <linux/types.h> #include <linux/kobject.h> #include "mt-plat/mtk_thermal_monitor.h" #define mtk_cooler_backlight_dprintk(fmt, args...) pr_debug("thermal/cooler/backlight " fmt, ##args) #define BACKLIGHT_COOLER_NR 3 static struct thermal_cooling_device *cl_backlight_dev[BACKLIGHT_COOLER_NR] = { 0 }; static unsigned int g_cl_backlight_state[BACKLIGHT_COOLER_NR] = { 0 }; /* static unsigned int g_cl_backlight_last_state[BACKLIGHT_COOLER_NR] = {0}; */ static unsigned int g_cl_id[BACKLIGHT_COOLER_NR]; static unsigned int g_backlight_level; static unsigned int g_backlight_last_level; static void mtk_cl_backlight_set_max_brightness_limit(void) { if (g_backlight_last_level != g_backlight_level) { mtk_cooler_backlight_dprintk("set brightness level = %d\n", g_backlight_level); switch (g_backlight_level) { case 0: setMaxbrightness(255, 0); /* 100% */ break; case 1: setMaxbrightness(178, 1); /* 70% */ break; case 2: setMaxbrightness(102, 1); /* 40% */ break; case 3: setMaxbrightness(25, 1); /* 10% */ break; default: setMaxbrightness(255, 0); break; } } } static int mtk_cl_backlight_get_max_state(struct thermal_cooling_device *cdev, unsigned long *state) { *state = 1; /* mtk_cooler_backlight_dprintk("mtk_cl_backlight_get_max_state() %d\n", *state); */ return 0; } static int mtk_cl_backlight_get_cur_state(struct thermal_cooling_device *cdev, unsigned long *state) { int nCoolerId; /* Get Cooler ID */ nCoolerId = *((int *)cdev->devdata); *state = g_cl_backlight_state[nCoolerId]; /* mtk_cooler_backlight_dprintk("mtk_cl_backlight_get_cur_state() %d CoolerID:%d\n", *state, nCoolerId); */ return 0; } static int mtk_cl_backlight_set_cur_state(struct thermal_cooling_device *cdev, unsigned long state) { int i; int nCoolerId; /* /< Backlight Cooler ID */ /* Get Cooler ID */ nCoolerId = *((int *)cdev->devdata); /* mtk_cooler_backlight_dprintk("mtk_cl_backlight_set_cur_state() %d CoolerID:%d\n", state, nCoolerId); */ g_cl_backlight_state[nCoolerId] = state; g_backlight_level = 0; for (i = 0; i < BACKLIGHT_COOLER_NR; i++) g_backlight_level += g_cl_backlight_state[i]; /* Mark for test */ /* if(g_backlight_last_level != g_backlight_level) */ { /* send uevent to notify current call must be dropped */ /* char event[20] = {0}; */ /* char *envp[] = { event, NULL }; */ /* sprintf(event, "BACKLIGHT=%d", g_backlight_level); ///< BACKLIGHT01=1 ... */ /* kobject_uevent_env(&(cl_backlight_dev[nCoolerId]->device.kobj), KOBJ_CHANGE, envp); */ mtk_cl_backlight_set_max_brightness_limit(); g_backlight_last_level = g_backlight_level; /* mtk_cooler_backlight_dprintk("mtk_cl_backlight_set_cur_state() event:%s g_backlight_level:%d\n", event, g_backlight_level); */ } return 0; } /* bind fan callbacks to fan device */ static struct thermal_cooling_device_ops mtk_cl_backlight_ops = { .get_max_state = mtk_cl_backlight_get_max_state, .get_cur_state = mtk_cl_backlight_get_cur_state, .set_cur_state = mtk_cl_backlight_set_cur_state, }; static int mtk_cooler_backlight_register_ltf(void) { int i; mtk_cooler_backlight_dprintk("register ltf\n"); for (i = 0; i < BACKLIGHT_COOLER_NR; i++) { char temp[20] = { 0 }; sprintf(temp, "mtk-cl-backlight%02d", i + 1); /* /< Cooler Name: mtk-cl-backlight01 */ g_cl_id[i] = i; cl_backlight_dev[i] = mtk_thermal_cooling_device_register(temp, (void *)&g_cl_id[i], &mtk_cl_backlight_ops); } return 0; } static void mtk_cooler_backlight_unregister_ltf(void) { int i; mtk_cooler_backlight_dprintk("unregister ltf\n"); for (i = 0; i < BACKLIGHT_COOLER_NR; i++) { if (cl_backlight_dev[i]) { mtk_thermal_cooling_device_unregister(cl_backlight_dev[i]); cl_backlight_dev[i] = NULL; } } } static int __init mtk_cooler_backlight_init(void) { int err = 0; mtk_cooler_backlight_dprintk("init\n"); err = mtk_cooler_backlight_register_ltf(); if (err) goto err_unreg; return 0; err_unreg: mtk_cooler_backlight_unregister_ltf(); return err; } static void __exit mtk_cooler_backlight_exit(void) { mtk_cooler_backlight_dprintk("exit\n"); mtk_cooler_backlight_unregister_ltf(); } module_init(mtk_cooler_backlight_init); module_exit(mtk_cooler_backlight_exit);
90514.c
/* * Copyright (c) 2015-2017, Intel Corporation * Copyright (c) 2021, Arm Limited * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Intel Corporation nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "accel.h" #include "shufti.h" #include "truffle.h" #include "vermicelli.h" #include "ue2common.h" const u8 *run_accel(const union AccelAux *accel, const u8 *c, const u8 *c_end) { assert(ISALIGNED_N(accel, alignof(union AccelAux))); const u8 *rv; switch (accel->accel_type) { case ACCEL_NONE: DEBUG_PRINTF("accel none %p %p\n", c, c_end); return c; case ACCEL_VERM: DEBUG_PRINTF("accel verm %p %p\n", c, c_end); if (c + 15 >= c_end) { return c; } rv = vermicelliExec(accel->verm.c, 0, c, c_end); break; case ACCEL_VERM_NOCASE: DEBUG_PRINTF("accel verm nc %p %p\n", c, c_end); if (c + 15 >= c_end) { return c; } rv = vermicelliExec(accel->verm.c, 1, c, c_end); break; case ACCEL_DVERM: DEBUG_PRINTF("accel dverm %p %p\n", c, c_end); if (c + 16 + 1 >= c_end) { return c; } /* need to stop one early to get an accurate end state */ rv = vermicelliDoubleExec(accel->dverm.c1, accel->dverm.c2, 0, c, c_end - 1); break; case ACCEL_DVERM_NOCASE: DEBUG_PRINTF("accel dverm nc %p %p\n", c, c_end); if (c + 16 + 1 >= c_end) { return c; } /* need to stop one early to get an accurate end state */ rv = vermicelliDoubleExec(accel->dverm.c1, accel->dverm.c2, 1, c, c_end - 1); break; #ifdef HAVE_SVE2 case ACCEL_VERM16: DEBUG_PRINTF("accel verm16 %p %p\n", c, c_end); if (c_end - c < 16) { return c; } rv = vermicelli16Exec(accel->verm16.mask, c, c_end); break; case ACCEL_DVERM16: DEBUG_PRINTF("accel dverm16 %p %p\n", c, c_end); if (c_end - c < 18) { return c; } /* need to stop one early to get an accurate end state */ rv = vermicelliDouble16Exec(accel->dverm16.mask, accel->dverm16.firsts, c, c_end - 1); break; case ACCEL_DVERM16_MASKED: DEBUG_PRINTF("accel dverm16 masked %p %p\n", c, c_end); if (c_end - c < 18) { return c; } /* need to stop one early to get an accurate end state */ rv = vermicelliDoubleMasked16Exec(accel->mdverm16.mask, accel->mdverm16.c1, accel->mdverm16.m1, c, c_end - 1); break; #endif // HAVE_SVE2 case ACCEL_DVERM_MASKED: DEBUG_PRINTF("accel dverm masked %p %p\n", c, c_end); if (c + 16 + 1 >= c_end) { return c; } /* need to stop one early to get an accurate end state */ rv = vermicelliDoubleMaskedExec(accel->dverm.c1, accel->dverm.c2, accel->dverm.m1, accel->dverm.m2, c, c_end - 1); break; case ACCEL_SHUFTI: DEBUG_PRINTF("accel shufti %p %p\n", c, c_end); if (c + 15 >= c_end) { return c; } rv = shuftiExec(accel->shufti.lo, accel->shufti.hi, c, c_end); break; case ACCEL_TRUFFLE: DEBUG_PRINTF("accel Truffle %p %p\n", c, c_end); if (c + 15 >= c_end) { return c; } rv = truffleExec(accel->truffle.mask1, accel->truffle.mask2, c, c_end); break; case ACCEL_DSHUFTI: DEBUG_PRINTF("accel dshufti %p %p\n", c, c_end); if (c + 15 + 1 >= c_end) { return c; } /* need to stop one early to get an accurate end state */ rv = shuftiDoubleExec(accel->dshufti.lo1, accel->dshufti.hi1, accel->dshufti.lo2, accel->dshufti.hi2, c, c_end - 1); break; case ACCEL_RED_TAPE: DEBUG_PRINTF("accel red tape %p %p\n", c, c_end); rv = c_end; break; default: assert(!"not here"); return c; } DEBUG_PRINTF("adjusting for offset %u\n", accel->generic.offset); /* adjust offset to take into account the offset */ rv = MAX(c + accel->generic.offset, rv); rv -= accel->generic.offset; DEBUG_PRINTF("advanced %zd\n", rv - c); return rv; }
780070.c
/*Em muitas situações, é necessário pegar as informações da data de nascimento e sua idade e coloca-las dentro de uma frase formatada. Por exemplo, suponha que uma pessoa tenha a data de nascimento d/m/y e idade k. Precisamos exibir a seguinte mensagem: Voce nasceu no dia d do mês m no ano y e hoje tem k anos. Implemente um programa que faça isso, recebe do usuário a data de nascimento e a idade no formato "d/m/y k", onde temos primeiro a data de nascimento e separado por espaço a idade, e gere a frase.*/ #include <stdio.h> void main(){ int dia, mes, ano, idade; scanf("%d/%d/%d %d", &dia, &mes, &ano, &idade); printf("voce nasceu no dia %d do mes %d no ano %d e hoje tem %d anos.", dia, mes, ano, idade); }
179304.c
// RUN: 3c -base-dir=%S -addcr -alltypes -output-postfix=checkedALL2 %S/arrsafemulti1.c %s // RUN: 3c -base-dir=%S -addcr -output-postfix=checkedNOALL2 %S/arrsafemulti1.c %s // RUN: %clang -c %S/arrsafemulti1.checkedNOALL2.c %S/arrsafemulti2.checkedNOALL2.c // RUN: FileCheck -match-full-lines -check-prefixes="CHECK_NOALL","CHECK" --input-file %S/arrsafemulti2.checkedNOALL2.c %s // RUN: FileCheck -match-full-lines -check-prefixes="CHECK_ALL","CHECK" --input-file %S/arrsafemulti2.checkedALL2.c %s // RUN: 3c -base-dir=%S -alltypes -output-postfix=checked2 %S/arrsafemulti1.c %s // RUN: 3c -base-dir=%S -alltypes -output-postfix=convert_again %S/arrsafemulti1.checked2.c %S/arrsafemulti2.checked2.c // RUN: test ! -f %S/arrsafemulti1.checked2.convert_again.c // RUN: test ! -f %S/arrsafemulti2.checked2.convert_again.c // RUN: rm %S/arrsafemulti1.checkedALL2.c %S/arrsafemulti2.checkedALL2.c // RUN: rm %S/arrsafemulti1.checkedNOALL2.c %S/arrsafemulti2.checkedNOALL2.c // RUN: rm %S/arrsafemulti1.checked2.c %S/arrsafemulti2.checked2.c /*********************************************************************************/ /*This file tests three functions: two callers bar and foo, and a callee sus*/ /*In particular, this file tests: arrays through a for loop and pointer arithmetic to assign into it*/ /*For robustness, this test is identical to arrprotosafe.c and arrsafe.c except in that the callee and callers are split amongst two files to see how the tool performs conversions*/ /*In this test, foo, bar, and sus will all treat their return values safely*/ /*********************************************************************************/ #include <stddef.h> extern _Itype_for_any(T) void *calloc(size_t nmemb, size_t size) : itype(_Array_ptr<T>) byte_count(nmemb * size); extern _Itype_for_any(T) void free(void *pointer : itype(_Array_ptr<T>) byte_count(0)); extern _Itype_for_any(T) void *malloc(size_t size) : itype(_Array_ptr<T>) byte_count(size); extern _Itype_for_any(T) void *realloc(void *pointer : itype(_Array_ptr<T>) byte_count(1), size_t size) : itype(_Array_ptr<T>) byte_count(size); extern int printf(const char * restrict format : itype(restrict _Nt_array_ptr<const char>), ...); extern _Unchecked char *strcpy(char * restrict dest, const char * restrict src : itype(restrict _Nt_array_ptr<const char>)); struct general { int data; struct general *next; //CHECK: _Ptr<struct general> next; }; struct warr { int data1[5]; //CHECK_NOALL: int data1[5]; //CHECK_ALL: int data1 _Checked[5]; char *name; //CHECK: _Ptr<char> name; }; struct fptrarr { int *values; //CHECK: _Ptr<int> values; char *name; //CHECK: _Ptr<char> name; int (*mapper)(int); //CHECK: _Ptr<int (int )> mapper; }; struct fptr { int *value; //CHECK: _Ptr<int> value; int (*func)(int); //CHECK: _Ptr<int (int )> func; }; struct arrfptr { int args[5]; //CHECK_NOALL: int args[5]; //CHECK_ALL: int args _Checked[5]; int (*funcs[5]) (int); //CHECK_NOALL: int (*funcs[5]) (int); //CHECK_ALL: _Ptr<int (int )> funcs _Checked[5]; }; static int add1(int x) { //CHECK: static int add1(int x) _Checked { return x+1; } static int sub1(int x) { //CHECK: static int sub1(int x) _Checked { return x-1; } static int fact(int n) { //CHECK: static int fact(int n) _Checked { if(n==0) { return 1; } return n*fact(n-1); } static int fib(int n) { //CHECK: static int fib(int n) _Checked { if(n==0) { return 0; } if(n==1) { return 1; } return fib(n-1) + fib(n-2); } static int zerohuh(int n) { //CHECK: static int zerohuh(int n) _Checked { return !n; } static int *mul2(int *x) { //CHECK: static _Ptr<int> mul2(_Ptr<int> x) _Checked { *x *= 2; return x; } int * sus(int * x, int * y) { //CHECK_NOALL: int * sus(int * x, _Ptr<int> y) { //CHECK_ALL: _Array_ptr<int> sus(int * x, _Ptr<int> y) : count(5) { x = (int *) 5; //CHECK: x = (int *) 5; int *z = calloc(5, sizeof(int)); //CHECK_NOALL: int *z = calloc<int>(5, sizeof(int)); //CHECK_ALL: _Array_ptr<int> z : count(5) = calloc<int>(5, sizeof(int)); int i, fac; int *p; //CHECK_NOALL: int *p; //CHECK_ALL: _Array_ptr<int> p = ((void *)0); for(i = 0, p = z, fac = 1; i < 5; ++i, p++, fac *= i) { *p = fac; } //CHECK_NOALL: { *p = fac; } //CHECK_ALL: _Checked { *p = fac; } return z; }
651349.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52b.c Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml Template File: sources-sinks-52b.tmpl.c */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: rand Set data to result of rand(), which may be zero * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #define HELLO_STRING "hello" #ifndef OMITBAD /* bad function declaration */ void CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52c_badSink(size_t data); void CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52b_badSink(size_t data) { CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52c_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52c_goodG2BSink(size_t data); void CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52b_goodG2BSink(size_t data) { CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52c_goodG2BSink(data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52c_goodB2GSink(size_t data); void CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52b_goodB2GSink(size_t data) { CWE789_Uncontrolled_Mem_Alloc__malloc_char_rand_52c_goodB2GSink(data); } #endif /* OMITGOOD */
984563.c
// SPDX-License-Identifier: GPL-2.0 #include "symbol.h" #include <errno.h> #include <inttypes.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <uapi/linux/mman.h> /* To get things like MAP_HUGETLB even on older libc headers */ #include "map.h" #include "thread.h" #include "vdso.h" #include "build-id.h" #include "util.h" #include "debug.h" #include "machine.h" #include <linux/string.h> #include "srcline.h" #include "namespaces.h" #include "unwind.h" static void __maps__insert(struct maps *maps, struct map *map); static inline int is_anon_memory(const char *filename, u32 flags) { return flags & MAP_HUGETLB || !strcmp(filename, "//anon") || !strncmp(filename, "/dev/zero", sizeof("/dev/zero") - 1) || !strncmp(filename, "/anon_hugepage", sizeof("/anon_hugepage") - 1); } static inline int is_no_dso_memory(const char *filename) { return !strncmp(filename, "[stack", 6) || !strncmp(filename, "/SYSV",5) || !strcmp(filename, "[heap]"); } static inline int is_android_lib(const char *filename) { return !strncmp(filename, "/data/app-lib", 13) || !strncmp(filename, "/system/lib", 11); } static inline bool replace_android_lib(const char *filename, char *newfilename) { const char *libname; char *app_abi; size_t app_abi_length, new_length; size_t lib_length = 0; libname = strrchr(filename, '/'); if (libname) lib_length = strlen(libname); app_abi = getenv("APP_ABI"); if (!app_abi) return false; app_abi_length = strlen(app_abi); if (!strncmp(filename, "/data/app-lib", 13)) { char *apk_path; if (!app_abi_length) return false; new_length = 7 + app_abi_length + lib_length; apk_path = getenv("APK_PATH"); if (apk_path) { new_length += strlen(apk_path) + 1; if (new_length > PATH_MAX) return false; snprintf(newfilename, new_length, "%s/libs/%s/%s", apk_path, app_abi, libname); } else { if (new_length > PATH_MAX) return false; snprintf(newfilename, new_length, "libs/%s/%s", app_abi, libname); } return true; } if (!strncmp(filename, "/system/lib/", 11)) { char *ndk, *app; const char *arch; size_t ndk_length; size_t app_length; ndk = getenv("NDK_ROOT"); app = getenv("APP_PLATFORM"); if (!(ndk && app)) return false; ndk_length = strlen(ndk); app_length = strlen(app); if (!(ndk_length && app_length && app_abi_length)) return false; arch = !strncmp(app_abi, "arm", 3) ? "arm" : !strncmp(app_abi, "mips", 4) ? "mips" : !strncmp(app_abi, "x86", 3) ? "x86" : NULL; if (!arch) return false; new_length = 27 + ndk_length + app_length + lib_length + strlen(arch); if (new_length > PATH_MAX) return false; snprintf(newfilename, new_length, "%s/platforms/%s/arch-%s/usr/lib/%s", ndk, app, arch, libname); return true; } return false; } void map__init(struct map *map, u64 start, u64 end, u64 pgoff, struct dso *dso) { map->start = start; map->end = end; map->pgoff = pgoff; map->reloc = 0; map->dso = dso__get(dso); map->map_ip = map__map_ip; map->unmap_ip = map__unmap_ip; RB_CLEAR_NODE(&map->rb_node); map->groups = NULL; map->erange_warned = false; refcount_set(&map->refcnt, 1); } struct map *map__new(struct machine *machine, u64 start, u64 len, u64 pgoff, u32 d_maj, u32 d_min, u64 ino, u64 ino_gen, u32 prot, u32 flags, char *filename, struct thread *thread) { struct map *map = malloc(sizeof(*map)); struct nsinfo *nsi = NULL; struct nsinfo *nnsi; if (map != NULL) { char newfilename[PATH_MAX]; struct dso *dso; int anon, no_dso, vdso, android; android = is_android_lib(filename); anon = is_anon_memory(filename, flags); vdso = is_vdso_map(filename); no_dso = is_no_dso_memory(filename); map->maj = d_maj; map->min = d_min; map->ino = ino; map->ino_generation = ino_gen; map->prot = prot; map->flags = flags; nsi = nsinfo__get(thread->nsinfo); if ((anon || no_dso) && nsi && (prot & PROT_EXEC)) { snprintf(newfilename, sizeof(newfilename), "/tmp/perf-%d.map", nsi->pid); filename = newfilename; } if (android) { if (replace_android_lib(filename, newfilename)) filename = newfilename; } if (vdso) { /* The vdso maps are always on the host and not the * container. Ensure that we don't use setns to look * them up. */ nnsi = nsinfo__copy(nsi); if (nnsi) { nsinfo__put(nsi); nnsi->need_setns = false; nsi = nnsi; } pgoff = 0; dso = machine__findnew_vdso(machine, thread); } else dso = machine__findnew_dso(machine, filename); if (dso == NULL) goto out_delete; map__init(map, start, start + len, pgoff, dso); if (anon || no_dso) { map->map_ip = map->unmap_ip = identity__map_ip; /* * Set memory without DSO as loaded. All map__find_* * functions still return NULL, and we avoid the * unnecessary map__load warning. */ if (!(prot & PROT_EXEC)) dso__set_loaded(dso); } dso->nsinfo = nsi; dso__put(dso); } return map; out_delete: nsinfo__put(nsi); free(map); return NULL; } /* * Constructor variant for modules (where we know from /proc/modules where * they are loaded) and for vmlinux, where only after we load all the * symbols we'll know where it starts and ends. */ struct map *map__new2(u64 start, struct dso *dso) { struct map *map = calloc(1, (sizeof(*map) + (dso->kernel ? sizeof(struct kmap) : 0))); if (map != NULL) { /* * ->end will be filled after we load all the symbols */ map__init(map, start, 0, 0, dso); } return map; } /* * Use this and __map__is_kmodule() for map instances that are in * machine->kmaps, and thus have map->groups->machine all properly set, to * disambiguate between the kernel and modules. * * When the need arises, introduce map__is_{kernel,kmodule)() that * checks (map->groups != NULL && map->groups->machine != NULL && * map->dso->kernel) before calling __map__is_{kernel,kmodule}()) */ bool __map__is_kernel(const struct map *map) { return machine__kernel_map(map->groups->machine) == map; } bool __map__is_extra_kernel_map(const struct map *map) { struct kmap *kmap = __map__kmap((struct map *)map); return kmap && kmap->name[0]; } bool map__has_symbols(const struct map *map) { return dso__has_symbols(map->dso); } static void map__exit(struct map *map) { BUG_ON(!RB_EMPTY_NODE(&map->rb_node)); dso__zput(map->dso); } void map__delete(struct map *map) { map__exit(map); free(map); } void map__put(struct map *map) { if (map && refcount_dec_and_test(&map->refcnt)) map__delete(map); } void map__fixup_start(struct map *map) { struct rb_root *symbols = &map->dso->symbols; struct rb_node *nd = rb_first(symbols); if (nd != NULL) { struct symbol *sym = rb_entry(nd, struct symbol, rb_node); map->start = sym->start; } } void map__fixup_end(struct map *map) { struct rb_root *symbols = &map->dso->symbols; struct rb_node *nd = rb_last(symbols); if (nd != NULL) { struct symbol *sym = rb_entry(nd, struct symbol, rb_node); map->end = sym->end; } } #define DSO__DELETED "(deleted)" int map__load(struct map *map) { const char *name = map->dso->long_name; int nr; if (dso__loaded(map->dso)) return 0; nr = dso__load(map->dso, map); if (nr < 0) { if (map->dso->has_build_id) { char sbuild_id[SBUILD_ID_SIZE]; build_id__sprintf(map->dso->build_id, sizeof(map->dso->build_id), sbuild_id); pr_debug("%s with build id %s not found", name, sbuild_id); } else pr_debug("Failed to open %s", name); pr_debug(", continuing without symbols\n"); return -1; } else if (nr == 0) { #ifdef HAVE_LIBELF_SUPPORT const size_t len = strlen(name); const size_t real_len = len - sizeof(DSO__DELETED); if (len > sizeof(DSO__DELETED) && strcmp(name + real_len + 1, DSO__DELETED) == 0) { pr_debug("%.*s was updated (is prelink enabled?). " "Restart the long running apps that use it!\n", (int)real_len, name); } else { pr_debug("no symbols found in %s, maybe install a debug package?\n", name); } #endif return -1; } return 0; } struct symbol *map__find_symbol(struct map *map, u64 addr) { if (map__load(map) < 0) return NULL; return dso__find_symbol(map->dso, addr); } struct symbol *map__find_symbol_by_name(struct map *map, const char *name) { if (map__load(map) < 0) return NULL; if (!dso__sorted_by_name(map->dso)) dso__sort_by_name(map->dso); return dso__find_symbol_by_name(map->dso, name); } struct map *map__clone(struct map *from) { struct map *map = memdup(from, sizeof(*map)); if (map != NULL) { refcount_set(&map->refcnt, 1); RB_CLEAR_NODE(&map->rb_node); dso__get(map->dso); map->groups = NULL; } return map; } size_t map__fprintf(struct map *map, FILE *fp) { return fprintf(fp, " %" PRIx64 "-%" PRIx64 " %" PRIx64 " %s\n", map->start, map->end, map->pgoff, map->dso->name); } size_t map__fprintf_dsoname(struct map *map, FILE *fp) { const char *dsoname = "[unknown]"; if (map && map->dso) { if (symbol_conf.show_kernel_path && map->dso->long_name) dsoname = map->dso->long_name; else dsoname = map->dso->name; } return fprintf(fp, "%s", dsoname); } char *map__srcline(struct map *map, u64 addr, struct symbol *sym) { if (map == NULL) return SRCLINE_UNKNOWN; return get_srcline(map->dso, map__rip_2objdump(map, addr), sym, true, true, addr); } int map__fprintf_srcline(struct map *map, u64 addr, const char *prefix, FILE *fp) { int ret = 0; if (map && map->dso) { char *srcline = map__srcline(map, addr, NULL); if (srcline != SRCLINE_UNKNOWN) ret = fprintf(fp, "%s%s", prefix, srcline); free_srcline(srcline); } return ret; } /** * map__rip_2objdump - convert symbol start address to objdump address. * @map: memory map * @rip: symbol start address * * objdump wants/reports absolute IPs for ET_EXEC, and RIPs for ET_DYN. * map->dso->adjust_symbols==1 for ET_EXEC-like cases except ET_REL which is * relative to section start. * * Return: Address suitable for passing to "objdump --start-address=" */ u64 map__rip_2objdump(struct map *map, u64 rip) { struct kmap *kmap = __map__kmap(map); /* * vmlinux does not have program headers for PTI entry trampolines and * kcore may not either. However the trampoline object code is on the * main kernel map, so just use that instead. */ if (kmap && is_entry_trampoline(kmap->name) && kmap->kmaps && kmap->kmaps->machine) { struct map *kernel_map = machine__kernel_map(kmap->kmaps->machine); if (kernel_map) map = kernel_map; } if (!map->dso->adjust_symbols) return rip; if (map->dso->rel) return rip - map->pgoff; /* * kernel modules also have DSO_TYPE_USER in dso->kernel, * but all kernel modules are ET_REL, so won't get here. */ if (map->dso->kernel == DSO_TYPE_USER) return rip + map->dso->text_offset; return map->unmap_ip(map, rip) - map->reloc; } /** * map__objdump_2mem - convert objdump address to a memory address. * @map: memory map * @ip: objdump address * * Closely related to map__rip_2objdump(), this function takes an address from * objdump and converts it to a memory address. Note this assumes that @map * contains the address. To be sure the result is valid, check it forwards * e.g. map__rip_2objdump(map->map_ip(map, map__objdump_2mem(map, ip))) == ip * * Return: Memory address. */ u64 map__objdump_2mem(struct map *map, u64 ip) { if (!map->dso->adjust_symbols) return map->unmap_ip(map, ip); if (map->dso->rel) return map->unmap_ip(map, ip + map->pgoff); /* * kernel modules also have DSO_TYPE_USER in dso->kernel, * but all kernel modules are ET_REL, so won't get here. */ if (map->dso->kernel == DSO_TYPE_USER) return map->unmap_ip(map, ip - map->dso->text_offset); return ip + map->reloc; } static void maps__init(struct maps *maps) { maps->entries = RB_ROOT; init_rwsem(&maps->lock); } void map_groups__init(struct map_groups *mg, struct machine *machine) { maps__init(&mg->maps); mg->machine = machine; refcount_set(&mg->refcnt, 1); } static void __maps__purge(struct maps *maps) { struct rb_root *root = &maps->entries; struct rb_node *next = rb_first(root); while (next) { struct map *pos = rb_entry(next, struct map, rb_node); next = rb_next(&pos->rb_node); rb_erase_init(&pos->rb_node, root); map__put(pos); } } static void maps__exit(struct maps *maps) { down_write(&maps->lock); __maps__purge(maps); up_write(&maps->lock); } void map_groups__exit(struct map_groups *mg) { maps__exit(&mg->maps); } bool map_groups__empty(struct map_groups *mg) { return !maps__first(&mg->maps); } struct map_groups *map_groups__new(struct machine *machine) { struct map_groups *mg = malloc(sizeof(*mg)); if (mg != NULL) map_groups__init(mg, machine); return mg; } void map_groups__delete(struct map_groups *mg) { map_groups__exit(mg); free(mg); } void map_groups__put(struct map_groups *mg) { if (mg && refcount_dec_and_test(&mg->refcnt)) map_groups__delete(mg); } struct symbol *map_groups__find_symbol(struct map_groups *mg, u64 addr, struct map **mapp) { struct map *map = map_groups__find(mg, addr); /* Ensure map is loaded before using map->map_ip */ if (map != NULL && map__load(map) >= 0) { if (mapp != NULL) *mapp = map; return map__find_symbol(map, map->map_ip(map, addr)); } return NULL; } static bool map__contains_symbol(struct map *map, struct symbol *sym) { u64 ip = map->unmap_ip(map, sym->start); return ip >= map->start && ip < map->end; } struct symbol *maps__find_symbol_by_name(struct maps *maps, const char *name, struct map **mapp) { struct symbol *sym; struct rb_node *nd; down_read(&maps->lock); for (nd = rb_first(&maps->entries); nd; nd = rb_next(nd)) { struct map *pos = rb_entry(nd, struct map, rb_node); sym = map__find_symbol_by_name(pos, name); if (sym == NULL) continue; if (!map__contains_symbol(pos, sym)) { sym = NULL; continue; } if (mapp != NULL) *mapp = pos; goto out; } sym = NULL; out: up_read(&maps->lock); return sym; } struct symbol *map_groups__find_symbol_by_name(struct map_groups *mg, const char *name, struct map **mapp) { return maps__find_symbol_by_name(&mg->maps, name, mapp); } int map_groups__find_ams(struct addr_map_symbol *ams) { if (ams->addr < ams->map->start || ams->addr >= ams->map->end) { if (ams->map->groups == NULL) return -1; ams->map = map_groups__find(ams->map->groups, ams->addr); if (ams->map == NULL) return -1; } ams->al_addr = ams->map->map_ip(ams->map, ams->addr); ams->sym = map__find_symbol(ams->map, ams->al_addr); return ams->sym ? 0 : -1; } static size_t maps__fprintf(struct maps *maps, FILE *fp) { size_t printed = 0; struct rb_node *nd; down_read(&maps->lock); for (nd = rb_first(&maps->entries); nd; nd = rb_next(nd)) { struct map *pos = rb_entry(nd, struct map, rb_node); printed += fprintf(fp, "Map:"); printed += map__fprintf(pos, fp); if (verbose > 2) { printed += dso__fprintf(pos->dso, fp); printed += fprintf(fp, "--\n"); } } up_read(&maps->lock); return printed; } size_t map_groups__fprintf(struct map_groups *mg, FILE *fp) { return maps__fprintf(&mg->maps, fp); } static void __map_groups__insert(struct map_groups *mg, struct map *map) { __maps__insert(&mg->maps, map); map->groups = mg; } static int maps__fixup_overlappings(struct maps *maps, struct map *map, FILE *fp) { struct rb_root *root; struct rb_node *next, *first; int err = 0; down_write(&maps->lock); root = &maps->entries; /* * Find first map where end > map->start. * Same as find_vma() in kernel. */ next = root->rb_node; first = NULL; while (next) { struct map *pos = rb_entry(next, struct map, rb_node); if (pos->end > map->start) { first = next; if (pos->start <= map->start) break; next = next->rb_left; } else next = next->rb_right; } next = first; while (next) { struct map *pos = rb_entry(next, struct map, rb_node); next = rb_next(&pos->rb_node); /* * Stop if current map starts after map->end. * Maps are ordered by start: next will not overlap for sure. */ if (pos->start >= map->end) break; if (verbose >= 2) { if (use_browser) { pr_debug("overlapping maps in %s (disable tui for more info)\n", map->dso->name); } else { fputs("overlapping maps:\n", fp); map__fprintf(map, fp); map__fprintf(pos, fp); } } rb_erase_init(&pos->rb_node, root); /* * Now check if we need to create new maps for areas not * overlapped by the new map: */ if (map->start > pos->start) { struct map *before = map__clone(pos); if (before == NULL) { err = -ENOMEM; goto put_map; } before->end = map->start; __map_groups__insert(pos->groups, before); if (verbose >= 2 && !use_browser) map__fprintf(before, fp); map__put(before); } if (map->end < pos->end) { struct map *after = map__clone(pos); if (after == NULL) { err = -ENOMEM; goto put_map; } after->start = map->end; __map_groups__insert(pos->groups, after); if (verbose >= 2 && !use_browser) map__fprintf(after, fp); map__put(after); } put_map: map__put(pos); if (err) goto out; } err = 0; out: up_write(&maps->lock); return err; } int map_groups__fixup_overlappings(struct map_groups *mg, struct map *map, FILE *fp) { return maps__fixup_overlappings(&mg->maps, map, fp); } /* * XXX This should not really _copy_ te maps, but refcount them. */ int map_groups__clone(struct thread *thread, struct map_groups *parent) { struct map_groups *mg = thread->mg; int err = -ENOMEM; struct map *map; struct maps *maps = &parent->maps; down_read(&maps->lock); for (map = maps__first(maps); map; map = map__next(map)) { struct map *new = map__clone(map); if (new == NULL) goto out_unlock; err = unwind__prepare_access(thread, new, NULL); if (err) goto out_unlock; map_groups__insert(mg, new); map__put(new); } err = 0; out_unlock: up_read(&maps->lock); return err; } static void __maps__insert(struct maps *maps, struct map *map) { struct rb_node **p = &maps->entries.rb_node; struct rb_node *parent = NULL; const u64 ip = map->start; struct map *m; while (*p != NULL) { parent = *p; m = rb_entry(parent, struct map, rb_node); if (ip < m->start) p = &(*p)->rb_left; else p = &(*p)->rb_right; } rb_link_node(&map->rb_node, parent, p); rb_insert_color(&map->rb_node, &maps->entries); map__get(map); } void maps__insert(struct maps *maps, struct map *map) { down_write(&maps->lock); __maps__insert(maps, map); up_write(&maps->lock); } static void __maps__remove(struct maps *maps, struct map *map) { rb_erase_init(&map->rb_node, &maps->entries); map__put(map); } void maps__remove(struct maps *maps, struct map *map) { down_write(&maps->lock); __maps__remove(maps, map); up_write(&maps->lock); } struct map *maps__find(struct maps *maps, u64 ip) { struct rb_node **p, *parent = NULL; struct map *m; down_read(&maps->lock); p = &maps->entries.rb_node; while (*p != NULL) { parent = *p; m = rb_entry(parent, struct map, rb_node); if (ip < m->start) p = &(*p)->rb_left; else if (ip >= m->end) p = &(*p)->rb_right; else goto out; } m = NULL; out: up_read(&maps->lock); return m; } struct map *maps__first(struct maps *maps) { struct rb_node *first = rb_first(&maps->entries); if (first) return rb_entry(first, struct map, rb_node); return NULL; } struct map *map__next(struct map *map) { struct rb_node *next = rb_next(&map->rb_node); if (next) return rb_entry(next, struct map, rb_node); return NULL; } struct kmap *__map__kmap(struct map *map) { if (!map->dso || !map->dso->kernel) return NULL; return (struct kmap *)(map + 1); } struct kmap *map__kmap(struct map *map) { struct kmap *kmap = __map__kmap(map); if (!kmap) pr_err("Internal error: map__kmap with a non-kernel map\n"); return kmap; } struct map_groups *map__kmaps(struct map *map) { struct kmap *kmap = map__kmap(map); if (!kmap || !kmap->kmaps) { pr_err("Internal error: map__kmaps with a non-kernel map\n"); return NULL; } return kmap->kmaps; }
339156.c
/* * Copyright (c) 2022, Steve C. Woodford. * 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. */ #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "rtos.h" #include "wifi_driver.h" #include "winc_wifi.h" #include "network.h" #include "sam4s4_wifi.h" #include "timer.h" #include "hardware.h" #include "display.h" struct sam4s_wifi_state { void *ws_driver; uint32_t ws_provision_count; rtos_timer_t ws_ptimer; }; static struct sam4s_wifi_state sam4s_wifi_state; static void sam4s_wifi_interrupt(void *arg) { (void) GPIO_NETWORK_IRQ_PIO->PIO_ISR; wifi_driver_interrupt(arg); } static void sam4s_wifi_irq_control(uint8_t enable) { if (enable) GPIO_NETWORK_IRQ_PIO->PIO_IER = GPIO_NETWORK_IRQ_BIT; else GPIO_NETWORK_IRQ_PIO->PIO_IDR = GPIO_NETWORK_IRQ_BIT; } static void sam4s_wifi_reset(void) { /* * The WiFi reset pin and display controller reset pin share the * same GPIO pin, so tell the display task what we're about to do. */ display_stop(); HAL_GPIO_NETWORK_RST_clr(); timer_buzz_delay_ms(100); HAL_GPIO_NETWORK_RST_set(); timer_buzz_delay_ms(100); /* * The display will need to be re-initialised. */ display_restart(); } static void sam4s_wifi_control(void *cookie, uint8_t cmd, void *argp) { (void) cookie; switch (cmd) { case WINC_WIFI_IRQ_CTL: sam4s_wifi_irq_control(*((uint8_t *)argp)); break; case WINC_WIFI_RESET: sam4s_wifi_reset(); break; #ifndef WINC_PROVISION_SW case WIFI_CTL_READ_PROVISION: *(uint8_t *)argp = HAL_GPIO_PROVISION_BUTTON_read() == 0; break; #endif default: break; } } static void sam4s_poll_provision_switch(rtos_timer_t handle) { struct sam4s_wifi_state *ws = rtos_timer_get_id(handle); struct winc_gpio wg; bool pressed; wg.wg_pin = WINC_PROVISION_SW; wg.wg_value = 0; if (wifi_ioctl(ws->ws_driver, WINC_IOCTL_READ_GPIO, &wg) < 0) return; /* Switch is active low. */ pressed = wg.wg_value == 0; if (pressed == false) { if (ws->ws_provision_count >= 4 && ws->ws_provision_count < 20) display_ip_address(); ws->ws_provision_count = 0; return; } display_activity(DISPLAY_ACTIVITY_WAKE); if (++(ws->ws_provision_count) == 20) { if (wifi_driver_provision_start(ws->ws_driver) < 0) ws->ws_provision_count = 0; } } void sam4s_wifi_attach(const struct spi_interface *spi) { struct sam4s_wifi_state *ws = &sam4s_wifi_state; /* * Configure GPIOs for WiFi reset, enable and irq pins. * * Note that timing is important here. The documentation states * that there must be at least 5mS between the rising edges of * CHIP_EN and RESET, with the former rising first. * * We'll be a little more accomodating. */ /* Keep RESET asserted until sam4s_wifi_reset() is invoked. */ HAL_GPIO_NETWORK_RST_clr(); HAL_GPIO_NETWORK_RST_out(); /* Keep CHIP_EN deasserted for a bit longer. */ HAL_GPIO_NETWORK_EN_clr(); HAL_GPIO_NETWORK_EN_out(); timer_buzz_delay_ms(50); /* Now assert it. */ HAL_GPIO_NETWORK_EN_set(); timer_buzz_delay_ms(50); /* * Enable interrupt for the WiFi controller, configured for * falling-edge or low-level as appropriate. * * XXX: I soo need a GPIO driver in ../../../Embedded/arm/stuff */ HAL_GPIO_NETWORK_IRQ_pullup(1); HAL_GPIO_NETWORK_IRQ_in(); GPIO_NETWORK_IRQ_PIO->PIO_IER = GPIO_NETWORK_IRQ_BIT; GPIO_NETWORK_IRQ_PIO->PIO_AIMER = GPIO_NETWORK_IRQ_BIT; #ifdef NM_EDGE_INTERRUPT GPIO_NETWORK_IRQ_PIO->PIO_ESR = GPIO_NETWORK_IRQ_BIT; #else GPIO_NETWORK_IRQ_PIO->PIO_LSR = GPIO_NETWORK_IRQ_BIT; #endif GPIO_NETWORK_IRQ_PIO->PIO_FELLSR = GPIO_NETWORK_IRQ_BIT; /* * Attach the WiFi controller */ ws->ws_driver = wifi_driver_attach(spi, sam4s_wifi_control, NULL); if (ws->ws_driver == NULL) return; /* Hook the wifi interrupt */ rtos_irq_register_named("WiFi", GPIO_NETWORK_IRQ_NUMBER, HW_IPL_NETWORK, sam4s_wifi_interrupt, ws->ws_driver); /* Enable WiFi interrupt */ sam4s_wifi_irq_control(1); /* * Start a timer to monitor the provision switch */ ws->ws_ptimer = rtos_timer_create("Provision", 250, 1, sam4s_poll_provision_switch, ws); assert(ws->ws_ptimer != NULL); rtos_timer_start(ws->ws_ptimer); }
396914.c
/* * linux/fs/ext4/bitmap.c * * Copyright (C) 1992, 1993, 1994, 1995 * Remy Card ([email protected]) * Laboratoire MASI - Institut Blaise Pascal * Universite Pierre et Marie Curie (Paris VI) */ #include <linux/buffer_head.h> #include <linux/jbd2.h> #include "ext4.h" static const int nibblemap[] = {4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0}; unsigned int ext4_count_free(char *bitmap, unsigned int numchars) { unsigned int i, sum = 0; for (i = 0; i < numchars; i++) sum += nibblemap[bitmap[i] & 0xf] + nibblemap[(bitmap[i] >> 4) & 0xf]; return sum; }
217665.c
/*- * BSD LICENSE * * Copyright(c) 2010-2015 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/queue.h> #include <stdio.h> #include <errno.h> #include <stdint.h> #include <stdarg.h> #include <rte_common.h> #include <rte_interrupts.h> #include <rte_byteorder.h> #include <rte_log.h> #include <rte_debug.h> #include <rte_pci.h> #include <rte_ether.h> #include <rte_ethdev.h> #include <rte_memory.h> #include <rte_memzone.h> #include <rte_eal.h> #include <rte_atomic.h> #include <rte_malloc.h> #include <rte_dev.h> #include "e1000_logs.h" #include "base/e1000_api.h" #include "e1000_ethdev.h" #define EM_EIAC 0x000DC #define PMD_ROUNDUP(x,y) (((x) + (y) - 1)/(y) * (y)) static int eth_em_configure(struct rte_eth_dev *dev); static int eth_em_start(struct rte_eth_dev *dev); static void eth_em_stop(struct rte_eth_dev *dev); static void eth_em_close(struct rte_eth_dev *dev); static void eth_em_promiscuous_enable(struct rte_eth_dev *dev); static void eth_em_promiscuous_disable(struct rte_eth_dev *dev); static void eth_em_allmulticast_enable(struct rte_eth_dev *dev); static void eth_em_allmulticast_disable(struct rte_eth_dev *dev); static int eth_em_link_update(struct rte_eth_dev *dev, int wait_to_complete); static void eth_em_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *rte_stats); static void eth_em_stats_reset(struct rte_eth_dev *dev); static void eth_em_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info); static int eth_em_flow_ctrl_get(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf); static int eth_em_flow_ctrl_set(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf); static int eth_em_interrupt_setup(struct rte_eth_dev *dev); static int eth_em_interrupt_get_status(struct rte_eth_dev *dev); static int eth_em_interrupt_action(struct rte_eth_dev *dev); static void eth_em_interrupt_handler(struct rte_intr_handle *handle, void *param); static int em_hw_init(struct e1000_hw *hw); static int em_hardware_init(struct e1000_hw *hw); static void em_hw_control_acquire(struct e1000_hw *hw); static void em_hw_control_release(struct e1000_hw *hw); static void em_init_manageability(struct e1000_hw *hw); static void em_release_manageability(struct e1000_hw *hw); static int eth_em_mtu_set(struct rte_eth_dev *dev, uint16_t mtu); static int eth_em_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on); static void eth_em_vlan_offload_set(struct rte_eth_dev *dev, int mask); static void em_vlan_hw_filter_enable(struct rte_eth_dev *dev); static void em_vlan_hw_filter_disable(struct rte_eth_dev *dev); static void em_vlan_hw_strip_enable(struct rte_eth_dev *dev); static void em_vlan_hw_strip_disable(struct rte_eth_dev *dev); /* static void eth_em_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on); */ static int eth_em_led_on(struct rte_eth_dev *dev); static int eth_em_led_off(struct rte_eth_dev *dev); static void em_intr_disable(struct e1000_hw *hw); static int em_get_rx_buffer_size(struct e1000_hw *hw); static void eth_em_rar_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr, uint32_t index, uint32_t pool); static void eth_em_rar_clear(struct rte_eth_dev *dev, uint32_t index); static int eth_em_set_mc_addr_list(struct rte_eth_dev *dev, struct ether_addr *mc_addr_set, uint32_t nb_mc_addr); #define EM_FC_PAUSE_TIME 0x0680 #define EM_LINK_UPDATE_CHECK_TIMEOUT 90 /* 9s */ #define EM_LINK_UPDATE_CHECK_INTERVAL 100 /* ms */ static enum e1000_fc_mode em_fc_setting = e1000_fc_full; /* * The set of PCI devices this driver supports */ static const struct rte_pci_id pci_id_em_map[] = { #define RTE_PCI_DEV_ID_DECL_EM(vend, dev) {RTE_PCI_DEVICE(vend, dev)}, #include "rte_pci_dev_ids.h" {0}, }; static const struct eth_dev_ops eth_em_ops = { .dev_configure = eth_em_configure, .dev_start = eth_em_start, .dev_stop = eth_em_stop, .dev_close = eth_em_close, .promiscuous_enable = eth_em_promiscuous_enable, .promiscuous_disable = eth_em_promiscuous_disable, .allmulticast_enable = eth_em_allmulticast_enable, .allmulticast_disable = eth_em_allmulticast_disable, .link_update = eth_em_link_update, .stats_get = eth_em_stats_get, .stats_reset = eth_em_stats_reset, .dev_infos_get = eth_em_infos_get, .mtu_set = eth_em_mtu_set, .vlan_filter_set = eth_em_vlan_filter_set, .vlan_offload_set = eth_em_vlan_offload_set, .rx_queue_setup = eth_em_rx_queue_setup, .rx_queue_release = eth_em_rx_queue_release, .rx_queue_count = eth_em_rx_queue_count, .rx_descriptor_done = eth_em_rx_descriptor_done, .tx_queue_setup = eth_em_tx_queue_setup, .tx_queue_release = eth_em_tx_queue_release, .dev_led_on = eth_em_led_on, .dev_led_off = eth_em_led_off, .flow_ctrl_get = eth_em_flow_ctrl_get, .flow_ctrl_set = eth_em_flow_ctrl_set, .mac_addr_add = eth_em_rar_set, .mac_addr_remove = eth_em_rar_clear, .set_mc_addr_list = eth_em_set_mc_addr_list, }; /** * Atomically reads the link status information from global * structure rte_eth_dev. * * @param dev * - Pointer to the structure rte_eth_dev to read from. * - Pointer to the buffer to be saved with the link status. * * @return * - On success, zero. * - On failure, negative value. */ static inline int rte_em_dev_atomic_read_link_status(struct rte_eth_dev *dev, struct rte_eth_link *link) { struct rte_eth_link *dst = link; struct rte_eth_link *src = &(dev->data->dev_link); if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst, *(uint64_t *)src) == 0) return -1; return 0; } /** * Atomically writes the link status information into global * structure rte_eth_dev. * * @param dev * - Pointer to the structure rte_eth_dev to read from. * - Pointer to the buffer to be saved with the link status. * * @return * - On success, zero. * - On failure, negative value. */ static inline int rte_em_dev_atomic_write_link_status(struct rte_eth_dev *dev, struct rte_eth_link *link) { struct rte_eth_link *dst = &(dev->data->dev_link); struct rte_eth_link *src = link; if (rte_atomic64_cmpset((uint64_t *)dst, *(uint64_t *)dst, *(uint64_t *)src) == 0) return -1; return 0; } static int eth_em_dev_init(struct rte_eth_dev *eth_dev) { struct rte_pci_device *pci_dev; struct e1000_adapter *adapter = E1000_DEV_PRIVATE(eth_dev->data->dev_private); struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private); struct e1000_vfta * shadow_vfta = E1000_DEV_PRIVATE_TO_VFTA(eth_dev->data->dev_private); pci_dev = eth_dev->pci_dev; eth_dev->dev_ops = &eth_em_ops; eth_dev->rx_pkt_burst = (eth_rx_burst_t)&eth_em_recv_pkts; eth_dev->tx_pkt_burst = (eth_tx_burst_t)&eth_em_xmit_pkts; /* for secondary processes, we don't initialise any further as primary * has already done this work. Only check we don't need a different * RX function */ if (rte_eal_process_type() != RTE_PROC_PRIMARY){ if (eth_dev->data->scattered_rx) eth_dev->rx_pkt_burst = (eth_rx_burst_t)&eth_em_recv_scattered_pkts; return 0; } hw->hw_addr = (void *)pci_dev->mem_resource[0].addr; hw->device_id = pci_dev->id.device_id; adapter->stopped = 0; /* For ICH8 support we'll need to map the flash memory BAR */ if (e1000_setup_init_funcs(hw, TRUE) != E1000_SUCCESS || em_hw_init(hw) != 0) { PMD_INIT_LOG(ERR, "port_id %d vendorID=0x%x deviceID=0x%x: " "failed to init HW", eth_dev->data->port_id, pci_dev->id.vendor_id, pci_dev->id.device_id); return -(ENODEV); } /* Allocate memory for storing MAC addresses */ eth_dev->data->mac_addrs = rte_zmalloc("e1000", ETHER_ADDR_LEN * hw->mac.rar_entry_count, 0); if (eth_dev->data->mac_addrs == NULL) { PMD_INIT_LOG(ERR, "Failed to allocate %d bytes needed to " "store MAC addresses", ETHER_ADDR_LEN * hw->mac.rar_entry_count); return -(ENOMEM); } /* Copy the permanent MAC address */ ether_addr_copy((struct ether_addr *) hw->mac.addr, eth_dev->data->mac_addrs); /* initialize the vfta */ memset(shadow_vfta, 0, sizeof(*shadow_vfta)); PMD_INIT_LOG(DEBUG, "port_id %d vendorID=0x%x deviceID=0x%x", eth_dev->data->port_id, pci_dev->id.vendor_id, pci_dev->id.device_id); rte_intr_callback_register(&(pci_dev->intr_handle), eth_em_interrupt_handler, (void *)eth_dev); return (0); } static int eth_em_dev_uninit(struct rte_eth_dev *eth_dev) { struct rte_pci_device *pci_dev; struct e1000_adapter *adapter = E1000_DEV_PRIVATE(eth_dev->data->dev_private); PMD_INIT_FUNC_TRACE(); if (rte_eal_process_type() != RTE_PROC_PRIMARY) return -EPERM; pci_dev = eth_dev->pci_dev; if (adapter->stopped == 0) eth_em_close(eth_dev); eth_dev->dev_ops = NULL; eth_dev->rx_pkt_burst = NULL; eth_dev->tx_pkt_burst = NULL; rte_free(eth_dev->data->mac_addrs); eth_dev->data->mac_addrs = NULL; /* disable uio intr before callback unregister */ rte_intr_disable(&(pci_dev->intr_handle)); rte_intr_callback_unregister(&(pci_dev->intr_handle), eth_em_interrupt_handler, (void *)eth_dev); return 0; } static struct eth_driver rte_em_pmd = { .pci_drv = { .name = "rte_em_pmd", .id_table = pci_id_em_map, .drv_flags = RTE_PCI_DRV_NEED_MAPPING | RTE_PCI_DRV_INTR_LSC | RTE_PCI_DRV_DETACHABLE, }, .eth_dev_init = eth_em_dev_init, .eth_dev_uninit = eth_em_dev_uninit, .dev_private_size = sizeof(struct e1000_adapter), }; static int rte_em_pmd_init(const char *name __rte_unused, const char *params __rte_unused) { rte_eth_driver_register(&rte_em_pmd); return 0; } static int em_hw_init(struct e1000_hw *hw) { int diag; diag = hw->mac.ops.init_params(hw); if (diag != 0) { PMD_INIT_LOG(ERR, "MAC Initialization Error"); return diag; } diag = hw->nvm.ops.init_params(hw); if (diag != 0) { PMD_INIT_LOG(ERR, "NVM Initialization Error"); return diag; } diag = hw->phy.ops.init_params(hw); if (diag != 0) { PMD_INIT_LOG(ERR, "PHY Initialization Error"); return diag; } (void) e1000_get_bus_info(hw); hw->mac.autoneg = 1; hw->phy.autoneg_wait_to_complete = 0; hw->phy.autoneg_advertised = E1000_ALL_SPEED_DUPLEX; e1000_init_script_state_82541(hw, TRUE); e1000_set_tbi_compatibility_82543(hw, TRUE); /* Copper options */ if (hw->phy.media_type == e1000_media_type_copper) { hw->phy.mdix = 0; /* AUTO_ALL_MODES */ hw->phy.disable_polarity_correction = 0; hw->phy.ms_type = e1000_ms_hw_default; } /* * Start from a known state, this is important in reading the nvm * and mac from that. */ e1000_reset_hw(hw); /* Make sure we have a good EEPROM before we read from it */ if (e1000_validate_nvm_checksum(hw) < 0) { /* * Some PCI-E parts fail the first check due to * the link being in sleep state, call it again, * if it fails a second time its a real issue. */ diag = e1000_validate_nvm_checksum(hw); if (diag < 0) { PMD_INIT_LOG(ERR, "EEPROM checksum invalid"); goto error; } } /* Read the permanent MAC address out of the EEPROM */ diag = e1000_read_mac_addr(hw); if (diag != 0) { PMD_INIT_LOG(ERR, "EEPROM error while reading MAC address"); goto error; } /* Now initialize the hardware */ diag = em_hardware_init(hw); if (diag != 0) { PMD_INIT_LOG(ERR, "Hardware initialization failed"); goto error; } hw->mac.get_link_status = 1; /* Indicate SOL/IDER usage */ diag = e1000_check_reset_block(hw); if (diag < 0) { PMD_INIT_LOG(ERR, "PHY reset is blocked due to " "SOL/IDER session"); } return (0); error: em_hw_control_release(hw); return (diag); } static int eth_em_configure(struct rte_eth_dev *dev) { struct e1000_interrupt *intr = E1000_DEV_PRIVATE_TO_INTR(dev->data->dev_private); PMD_INIT_FUNC_TRACE(); intr->flags |= E1000_FLAG_NEED_LINK_UPDATE; PMD_INIT_FUNC_TRACE(); return (0); } static void em_set_pba(struct e1000_hw *hw) { uint32_t pba; /* * Packet Buffer Allocation (PBA) * Writing PBA sets the receive portion of the buffer * the remainder is used for the transmit buffer. * Devices before the 82547 had a Packet Buffer of 64K. * After the 82547 the buffer was reduced to 40K. */ switch (hw->mac.type) { case e1000_82547: case e1000_82547_rev_2: /* 82547: Total Packet Buffer is 40K */ pba = E1000_PBA_22K; /* 22K for Rx, 18K for Tx */ break; case e1000_82571: case e1000_82572: case e1000_80003es2lan: pba = E1000_PBA_32K; /* 32K for Rx, 16K for Tx */ break; case e1000_82573: /* 82573: Total Packet Buffer is 32K */ pba = E1000_PBA_12K; /* 12K for Rx, 20K for Tx */ break; case e1000_82574: case e1000_82583: pba = E1000_PBA_20K; /* 20K for Rx, 20K for Tx */ break; case e1000_ich8lan: pba = E1000_PBA_8K; break; case e1000_ich9lan: case e1000_ich10lan: pba = E1000_PBA_10K; break; case e1000_pchlan: case e1000_pch2lan: pba = E1000_PBA_26K; break; default: pba = E1000_PBA_40K; /* 40K for Rx, 24K for Tx */ } E1000_WRITE_REG(hw, E1000_PBA, pba); } static int eth_em_start(struct rte_eth_dev *dev) { struct e1000_adapter *adapter = E1000_DEV_PRIVATE(dev->data->dev_private); struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); int ret, mask; PMD_INIT_FUNC_TRACE(); eth_em_stop(dev); e1000_power_up_phy(hw); /* Set default PBA value */ em_set_pba(hw); /* Put the address into the Receive Address Array */ e1000_rar_set(hw, hw->mac.addr, 0); /* * With the 82571 adapter, RAR[0] may be overwritten * when the other port is reset, we make a duplicate * in RAR[14] for that eventuality, this assures * the interface continues to function. */ if (hw->mac.type == e1000_82571) { e1000_set_laa_state_82571(hw, TRUE); e1000_rar_set(hw, hw->mac.addr, E1000_RAR_ENTRIES - 1); } /* Initialize the hardware */ if (em_hardware_init(hw)) { PMD_INIT_LOG(ERR, "Unable to initialize the hardware"); return (-EIO); } E1000_WRITE_REG(hw, E1000_VET, ETHER_TYPE_VLAN); /* Configure for OS presence */ em_init_manageability(hw); eth_em_tx_init(dev); ret = eth_em_rx_init(dev); if (ret) { PMD_INIT_LOG(ERR, "Unable to initialize RX hardware"); em_dev_clear_queues(dev); return ret; } e1000_clear_hw_cntrs_base_generic(hw); mask = ETH_VLAN_STRIP_MASK | ETH_VLAN_FILTER_MASK | \ ETH_VLAN_EXTEND_MASK; eth_em_vlan_offload_set(dev, mask); /* Set Interrupt Throttling Rate to maximum allowed value. */ E1000_WRITE_REG(hw, E1000_ITR, UINT16_MAX); /* Setup link speed and duplex */ switch (dev->data->dev_conf.link_speed) { case ETH_LINK_SPEED_AUTONEG: if (dev->data->dev_conf.link_duplex == ETH_LINK_AUTONEG_DUPLEX) hw->phy.autoneg_advertised = E1000_ALL_SPEED_DUPLEX; else if (dev->data->dev_conf.link_duplex == ETH_LINK_HALF_DUPLEX) hw->phy.autoneg_advertised = E1000_ALL_HALF_DUPLEX; else if (dev->data->dev_conf.link_duplex == ETH_LINK_FULL_DUPLEX) hw->phy.autoneg_advertised = E1000_ALL_FULL_DUPLEX; else goto error_invalid_config; break; case ETH_LINK_SPEED_10: if (dev->data->dev_conf.link_duplex == ETH_LINK_AUTONEG_DUPLEX) hw->phy.autoneg_advertised = E1000_ALL_10_SPEED; else if (dev->data->dev_conf.link_duplex == ETH_LINK_HALF_DUPLEX) hw->phy.autoneg_advertised = ADVERTISE_10_HALF; else if (dev->data->dev_conf.link_duplex == ETH_LINK_FULL_DUPLEX) hw->phy.autoneg_advertised = ADVERTISE_10_FULL; else goto error_invalid_config; break; case ETH_LINK_SPEED_100: if (dev->data->dev_conf.link_duplex == ETH_LINK_AUTONEG_DUPLEX) hw->phy.autoneg_advertised = E1000_ALL_100_SPEED; else if (dev->data->dev_conf.link_duplex == ETH_LINK_HALF_DUPLEX) hw->phy.autoneg_advertised = ADVERTISE_100_HALF; else if (dev->data->dev_conf.link_duplex == ETH_LINK_FULL_DUPLEX) hw->phy.autoneg_advertised = ADVERTISE_100_FULL; else goto error_invalid_config; break; case ETH_LINK_SPEED_1000: if ((dev->data->dev_conf.link_duplex == ETH_LINK_AUTONEG_DUPLEX) || (dev->data->dev_conf.link_duplex == ETH_LINK_FULL_DUPLEX)) hw->phy.autoneg_advertised = ADVERTISE_1000_FULL; else goto error_invalid_config; break; case ETH_LINK_SPEED_10000: default: goto error_invalid_config; } e1000_setup_link(hw); /* check if lsc interrupt feature is enabled */ if (dev->data->dev_conf.intr_conf.lsc != 0) { ret = eth_em_interrupt_setup(dev); if (ret) { PMD_INIT_LOG(ERR, "Unable to setup interrupts"); em_dev_clear_queues(dev); return ret; } } adapter->stopped = 0; PMD_INIT_LOG(DEBUG, "<<"); return (0); error_invalid_config: PMD_INIT_LOG(ERR, "Invalid link_speed/link_duplex (%u/%u) for port %u", dev->data->dev_conf.link_speed, dev->data->dev_conf.link_duplex, dev->data->port_id); em_dev_clear_queues(dev); return (-EINVAL); } /********************************************************************* * * This routine disables all traffic on the adapter by issuing a * global reset on the MAC. * **********************************************************************/ static void eth_em_stop(struct rte_eth_dev *dev) { struct rte_eth_link link; struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); em_intr_disable(hw); e1000_reset_hw(hw); if (hw->mac.type >= e1000_82544) E1000_WRITE_REG(hw, E1000_WUC, 0); /* Power down the phy. Needed to make the link go down */ e1000_power_down_phy(hw); em_dev_clear_queues(dev); /* clear the recorded link status */ memset(&link, 0, sizeof(link)); rte_em_dev_atomic_write_link_status(dev, &link); } static void eth_em_close(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct e1000_adapter *adapter = E1000_DEV_PRIVATE(dev->data->dev_private); eth_em_stop(dev); adapter->stopped = 1; em_dev_free_queues(dev); e1000_phy_hw_reset(hw); em_release_manageability(hw); em_hw_control_release(hw); } static int em_get_rx_buffer_size(struct e1000_hw *hw) { uint32_t rx_buf_size; rx_buf_size = ((E1000_READ_REG(hw, E1000_PBA) & UINT16_MAX) << 10); return rx_buf_size; } /********************************************************************* * * Initialize the hardware * **********************************************************************/ static int em_hardware_init(struct e1000_hw *hw) { uint32_t rx_buf_size; int diag; /* Issue a global reset */ e1000_reset_hw(hw); /* Let the firmware know the OS is in control */ em_hw_control_acquire(hw); /* * These parameters control the automatic generation (Tx) and * response (Rx) to Ethernet PAUSE frames. * - High water mark should allow for at least two standard size (1518) * frames to be received after sending an XOFF. * - Low water mark works best when it is very near the high water mark. * This allows the receiver to restart by sending XON when it has * drained a bit. Here we use an arbitrary value of 1500 which will * restart after one full frame is pulled from the buffer. There * could be several smaller frames in the buffer and if so they will * not trigger the XON until their total number reduces the buffer * by 1500. * - The pause time is fairly large at 1000 x 512ns = 512 usec. */ rx_buf_size = em_get_rx_buffer_size(hw); hw->fc.high_water = rx_buf_size - PMD_ROUNDUP(ETHER_MAX_LEN * 2, 1024); hw->fc.low_water = hw->fc.high_water - 1500; if (hw->mac.type == e1000_80003es2lan) hw->fc.pause_time = UINT16_MAX; else hw->fc.pause_time = EM_FC_PAUSE_TIME; hw->fc.send_xon = 1; /* Set Flow control, use the tunable location if sane */ if (em_fc_setting <= e1000_fc_full) hw->fc.requested_mode = em_fc_setting; else hw->fc.requested_mode = e1000_fc_none; /* Workaround: no TX flow ctrl for PCH */ if (hw->mac.type == e1000_pchlan) hw->fc.requested_mode = e1000_fc_rx_pause; /* Override - settings for PCH2LAN, ya its magic :) */ if (hw->mac.type == e1000_pch2lan) { hw->fc.high_water = 0x5C20; hw->fc.low_water = 0x5048; hw->fc.pause_time = 0x0650; hw->fc.refresh_time = 0x0400; } diag = e1000_init_hw(hw); if (diag < 0) return (diag); e1000_check_for_link(hw); return (0); } /* This function is based on em_update_stats_counters() in e1000/if_em.c */ static void eth_em_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *rte_stats) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct e1000_hw_stats *stats = E1000_DEV_PRIVATE_TO_STATS(dev->data->dev_private); int pause_frames; if(hw->phy.media_type == e1000_media_type_copper || (E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU)) { stats->symerrs += E1000_READ_REG(hw,E1000_SYMERRS); stats->sec += E1000_READ_REG(hw, E1000_SEC); } stats->crcerrs += E1000_READ_REG(hw, E1000_CRCERRS); stats->mpc += E1000_READ_REG(hw, E1000_MPC); stats->scc += E1000_READ_REG(hw, E1000_SCC); stats->ecol += E1000_READ_REG(hw, E1000_ECOL); stats->mcc += E1000_READ_REG(hw, E1000_MCC); stats->latecol += E1000_READ_REG(hw, E1000_LATECOL); stats->colc += E1000_READ_REG(hw, E1000_COLC); stats->dc += E1000_READ_REG(hw, E1000_DC); stats->rlec += E1000_READ_REG(hw, E1000_RLEC); stats->xonrxc += E1000_READ_REG(hw, E1000_XONRXC); stats->xontxc += E1000_READ_REG(hw, E1000_XONTXC); /* * For watchdog management we need to know if we have been * paused during the last interval, so capture that here. */ pause_frames = E1000_READ_REG(hw, E1000_XOFFRXC); stats->xoffrxc += pause_frames; stats->xofftxc += E1000_READ_REG(hw, E1000_XOFFTXC); stats->fcruc += E1000_READ_REG(hw, E1000_FCRUC); stats->prc64 += E1000_READ_REG(hw, E1000_PRC64); stats->prc127 += E1000_READ_REG(hw, E1000_PRC127); stats->prc255 += E1000_READ_REG(hw, E1000_PRC255); stats->prc511 += E1000_READ_REG(hw, E1000_PRC511); stats->prc1023 += E1000_READ_REG(hw, E1000_PRC1023); stats->prc1522 += E1000_READ_REG(hw, E1000_PRC1522); stats->gprc += E1000_READ_REG(hw, E1000_GPRC); stats->bprc += E1000_READ_REG(hw, E1000_BPRC); stats->mprc += E1000_READ_REG(hw, E1000_MPRC); stats->gptc += E1000_READ_REG(hw, E1000_GPTC); /* * For the 64-bit byte counters the low dword must be read first. * Both registers clear on the read of the high dword. */ stats->gorc += E1000_READ_REG(hw, E1000_GORCL); stats->gorc += ((uint64_t)E1000_READ_REG(hw, E1000_GORCH) << 32); stats->gotc += E1000_READ_REG(hw, E1000_GOTCL); stats->gotc += ((uint64_t)E1000_READ_REG(hw, E1000_GOTCH) << 32); stats->rnbc += E1000_READ_REG(hw, E1000_RNBC); stats->ruc += E1000_READ_REG(hw, E1000_RUC); stats->rfc += E1000_READ_REG(hw, E1000_RFC); stats->roc += E1000_READ_REG(hw, E1000_ROC); stats->rjc += E1000_READ_REG(hw, E1000_RJC); stats->tor += E1000_READ_REG(hw, E1000_TORH); stats->tot += E1000_READ_REG(hw, E1000_TOTH); stats->tpr += E1000_READ_REG(hw, E1000_TPR); stats->tpt += E1000_READ_REG(hw, E1000_TPT); stats->ptc64 += E1000_READ_REG(hw, E1000_PTC64); stats->ptc127 += E1000_READ_REG(hw, E1000_PTC127); stats->ptc255 += E1000_READ_REG(hw, E1000_PTC255); stats->ptc511 += E1000_READ_REG(hw, E1000_PTC511); stats->ptc1023 += E1000_READ_REG(hw, E1000_PTC1023); stats->ptc1522 += E1000_READ_REG(hw, E1000_PTC1522); stats->mptc += E1000_READ_REG(hw, E1000_MPTC); stats->bptc += E1000_READ_REG(hw, E1000_BPTC); /* Interrupt Counts */ if (hw->mac.type >= e1000_82571) { stats->iac += E1000_READ_REG(hw, E1000_IAC); stats->icrxptc += E1000_READ_REG(hw, E1000_ICRXPTC); stats->icrxatc += E1000_READ_REG(hw, E1000_ICRXATC); stats->ictxptc += E1000_READ_REG(hw, E1000_ICTXPTC); stats->ictxatc += E1000_READ_REG(hw, E1000_ICTXATC); stats->ictxqec += E1000_READ_REG(hw, E1000_ICTXQEC); stats->ictxqmtc += E1000_READ_REG(hw, E1000_ICTXQMTC); stats->icrxdmtc += E1000_READ_REG(hw, E1000_ICRXDMTC); stats->icrxoc += E1000_READ_REG(hw, E1000_ICRXOC); } if (hw->mac.type >= e1000_82543) { stats->algnerrc += E1000_READ_REG(hw, E1000_ALGNERRC); stats->rxerrc += E1000_READ_REG(hw, E1000_RXERRC); stats->tncrs += E1000_READ_REG(hw, E1000_TNCRS); stats->cexterr += E1000_READ_REG(hw, E1000_CEXTERR); stats->tsctc += E1000_READ_REG(hw, E1000_TSCTC); stats->tsctfc += E1000_READ_REG(hw, E1000_TSCTFC); } if (rte_stats == NULL) return; /* Rx Errors */ rte_stats->ibadcrc = stats->crcerrs; rte_stats->ibadlen = stats->rlec + stats->ruc + stats->roc; rte_stats->imissed = stats->mpc; rte_stats->ierrors = rte_stats->ibadcrc + rte_stats->ibadlen + rte_stats->imissed + stats->rxerrc + stats->algnerrc + stats->cexterr; /* Tx Errors */ rte_stats->oerrors = stats->ecol + stats->latecol; rte_stats->ipackets = stats->gprc; rte_stats->opackets = stats->gptc; rte_stats->ibytes = stats->gorc; rte_stats->obytes = stats->gotc; /* XON/XOFF pause frames stats registers */ rte_stats->tx_pause_xon = stats->xontxc; rte_stats->rx_pause_xon = stats->xonrxc; rte_stats->tx_pause_xoff = stats->xofftxc; rte_stats->rx_pause_xoff = stats->xoffrxc; } static void eth_em_stats_reset(struct rte_eth_dev *dev) { struct e1000_hw_stats *hw_stats = E1000_DEV_PRIVATE_TO_STATS(dev->data->dev_private); /* HW registers are cleared on read */ eth_em_stats_get(dev, NULL); /* Reset software totals */ memset(hw_stats, 0, sizeof(*hw_stats)); } static uint32_t em_get_max_pktlen(const struct e1000_hw *hw) { switch (hw->mac.type) { case e1000_82571: case e1000_82572: case e1000_ich9lan: case e1000_ich10lan: case e1000_pch2lan: case e1000_82574: case e1000_80003es2lan: /* 9K Jumbo Frame size */ case e1000_82583: return (0x2412); case e1000_pchlan: return (0x1000); /* Adapters that do not support jumbo frames */ case e1000_ich8lan: return (ETHER_MAX_LEN); default: return (MAX_JUMBO_FRAME_SIZE); } } static void eth_em_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); dev_info->min_rx_bufsize = 256; /* See BSIZE field of RCTL register. */ dev_info->max_rx_pktlen = em_get_max_pktlen(hw); dev_info->max_mac_addrs = hw->mac.rar_entry_count; /* * Starting with 631xESB hw supports 2 TX/RX queues per port. * Unfortunatelly, all these nics have just one TX context. * So we have few choises for TX: * - Use just one TX queue. * - Allow cksum offload only for one TX queue. * - Don't allow TX cksum offload at all. * For now, option #1 was chosen. * To use second RX queue we have to use extended RX descriptor * (Multiple Receive Queues are mutually exclusive with UDP * fragmentation and are not supported when a legacy receive * descriptor format is used). * Which means separate RX routinies - as legacy nics (82540, 82545) * don't support extended RXD. * To avoid it we support just one RX queue for now (no RSS). */ dev_info->max_rx_queues = 1; dev_info->max_tx_queues = 1; } /* return 0 means link status changed, -1 means not changed */ static int eth_em_link_update(struct rte_eth_dev *dev, int wait_to_complete) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct rte_eth_link link, old; int link_check, count; link_check = 0; hw->mac.get_link_status = 1; /* possible wait-to-complete in up to 9 seconds */ for (count = 0; count < EM_LINK_UPDATE_CHECK_TIMEOUT; count ++) { /* Read the real link status */ switch (hw->phy.media_type) { case e1000_media_type_copper: /* Do the work to read phy */ e1000_check_for_link(hw); link_check = !hw->mac.get_link_status; break; case e1000_media_type_fiber: e1000_check_for_link(hw); link_check = (E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU); break; case e1000_media_type_internal_serdes: e1000_check_for_link(hw); link_check = hw->mac.serdes_has_link; break; default: break; } if (link_check || wait_to_complete == 0) break; rte_delay_ms(EM_LINK_UPDATE_CHECK_INTERVAL); } memset(&link, 0, sizeof(link)); rte_em_dev_atomic_read_link_status(dev, &link); old = link; /* Now we check if a transition has happened */ if (link_check && (link.link_status == 0)) { hw->mac.ops.get_link_up_info(hw, &link.link_speed, &link.link_duplex); link.link_status = 1; } else if (!link_check && (link.link_status == 1)) { link.link_speed = 0; link.link_duplex = 0; link.link_status = 0; } rte_em_dev_atomic_write_link_status(dev, &link); /* not changed */ if (old.link_status == link.link_status) return -1; /* changed */ return 0; } /* * em_hw_control_acquire sets {CTRL_EXT|FWSM}:DRV_LOAD bit. * For ASF and Pass Through versions of f/w this means * that the driver is loaded. For AMT version type f/w * this means that the network i/f is open. */ static void em_hw_control_acquire(struct e1000_hw *hw) { uint32_t ctrl_ext, swsm; /* Let firmware know the driver has taken over */ if (hw->mac.type == e1000_82573) { swsm = E1000_READ_REG(hw, E1000_SWSM); E1000_WRITE_REG(hw, E1000_SWSM, swsm | E1000_SWSM_DRV_LOAD); } else { ctrl_ext = E1000_READ_REG(hw, E1000_CTRL_EXT); E1000_WRITE_REG(hw, E1000_CTRL_EXT, ctrl_ext | E1000_CTRL_EXT_DRV_LOAD); } } /* * em_hw_control_release resets {CTRL_EXTT|FWSM}:DRV_LOAD bit. * For ASF and Pass Through versions of f/w this means that the * driver is no longer loaded. For AMT versions of the * f/w this means that the network i/f is closed. */ static void em_hw_control_release(struct e1000_hw *hw) { uint32_t ctrl_ext, swsm; /* Let firmware taken over control of h/w */ if (hw->mac.type == e1000_82573) { swsm = E1000_READ_REG(hw, E1000_SWSM); E1000_WRITE_REG(hw, E1000_SWSM, swsm & ~E1000_SWSM_DRV_LOAD); } else { ctrl_ext = E1000_READ_REG(hw, E1000_CTRL_EXT); E1000_WRITE_REG(hw, E1000_CTRL_EXT, ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD); } } /* * Bit of a misnomer, what this really means is * to enable OS management of the system... aka * to disable special hardware management features. */ static void em_init_manageability(struct e1000_hw *hw) { if (e1000_enable_mng_pass_thru(hw)) { uint32_t manc2h = E1000_READ_REG(hw, E1000_MANC2H); uint32_t manc = E1000_READ_REG(hw, E1000_MANC); /* disable hardware interception of ARP */ manc &= ~(E1000_MANC_ARP_EN); /* enable receiving management packets to the host */ manc |= E1000_MANC_EN_MNG2HOST; manc2h |= 1 << 5; /* Mng Port 623 */ manc2h |= 1 << 6; /* Mng Port 664 */ E1000_WRITE_REG(hw, E1000_MANC2H, manc2h); E1000_WRITE_REG(hw, E1000_MANC, manc); } } /* * Give control back to hardware management * controller if there is one. */ static void em_release_manageability(struct e1000_hw *hw) { uint32_t manc; if (e1000_enable_mng_pass_thru(hw)) { manc = E1000_READ_REG(hw, E1000_MANC); /* re-enable hardware interception of ARP */ manc |= E1000_MANC_ARP_EN; manc &= ~E1000_MANC_EN_MNG2HOST; E1000_WRITE_REG(hw, E1000_MANC, manc); } } static void eth_em_promiscuous_enable(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint32_t rctl; rctl = E1000_READ_REG(hw, E1000_RCTL); rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE); E1000_WRITE_REG(hw, E1000_RCTL, rctl); } static void eth_em_promiscuous_disable(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint32_t rctl; rctl = E1000_READ_REG(hw, E1000_RCTL); rctl &= ~(E1000_RCTL_UPE | E1000_RCTL_SBP); if (dev->data->all_multicast == 1) rctl |= E1000_RCTL_MPE; else rctl &= (~E1000_RCTL_MPE); E1000_WRITE_REG(hw, E1000_RCTL, rctl); } static void eth_em_allmulticast_enable(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint32_t rctl; rctl = E1000_READ_REG(hw, E1000_RCTL); rctl |= E1000_RCTL_MPE; E1000_WRITE_REG(hw, E1000_RCTL, rctl); } static void eth_em_allmulticast_disable(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint32_t rctl; if (dev->data->promiscuous == 1) return; /* must remain in all_multicast mode */ rctl = E1000_READ_REG(hw, E1000_RCTL); rctl &= (~E1000_RCTL_MPE); E1000_WRITE_REG(hw, E1000_RCTL, rctl); } static int eth_em_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct e1000_vfta * shadow_vfta = E1000_DEV_PRIVATE_TO_VFTA(dev->data->dev_private); uint32_t vfta; uint32_t vid_idx; uint32_t vid_bit; vid_idx = (uint32_t) ((vlan_id >> E1000_VFTA_ENTRY_SHIFT) & E1000_VFTA_ENTRY_MASK); vid_bit = (uint32_t) (1 << (vlan_id & E1000_VFTA_ENTRY_BIT_SHIFT_MASK)); vfta = E1000_READ_REG_ARRAY(hw, E1000_VFTA, vid_idx); if (on) vfta |= vid_bit; else vfta &= ~vid_bit; E1000_WRITE_REG_ARRAY(hw, E1000_VFTA, vid_idx, vfta); /* update local VFTA copy */ shadow_vfta->vfta[vid_idx] = vfta; return 0; } static void em_vlan_hw_filter_disable(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint32_t reg; /* Filter Table Disable */ reg = E1000_READ_REG(hw, E1000_RCTL); reg &= ~E1000_RCTL_CFIEN; reg &= ~E1000_RCTL_VFE; E1000_WRITE_REG(hw, E1000_RCTL, reg); } static void em_vlan_hw_filter_enable(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct e1000_vfta * shadow_vfta = E1000_DEV_PRIVATE_TO_VFTA(dev->data->dev_private); uint32_t reg; int i; /* Filter Table Enable, CFI not used for packet acceptance */ reg = E1000_READ_REG(hw, E1000_RCTL); reg &= ~E1000_RCTL_CFIEN; reg |= E1000_RCTL_VFE; E1000_WRITE_REG(hw, E1000_RCTL, reg); /* restore vfta from local copy */ for (i = 0; i < IGB_VFTA_SIZE; i++) E1000_WRITE_REG_ARRAY(hw, E1000_VFTA, i, shadow_vfta->vfta[i]); } static void em_vlan_hw_strip_disable(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint32_t reg; /* VLAN Mode Disable */ reg = E1000_READ_REG(hw, E1000_CTRL); reg &= ~E1000_CTRL_VME; E1000_WRITE_REG(hw, E1000_CTRL, reg); } static void em_vlan_hw_strip_enable(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); uint32_t reg; /* VLAN Mode Enable */ reg = E1000_READ_REG(hw, E1000_CTRL); reg |= E1000_CTRL_VME; E1000_WRITE_REG(hw, E1000_CTRL, reg); } static void eth_em_vlan_offload_set(struct rte_eth_dev *dev, int mask) { if(mask & ETH_VLAN_STRIP_MASK){ if (dev->data->dev_conf.rxmode.hw_vlan_strip) em_vlan_hw_strip_enable(dev); else em_vlan_hw_strip_disable(dev); } if(mask & ETH_VLAN_FILTER_MASK){ if (dev->data->dev_conf.rxmode.hw_vlan_filter) em_vlan_hw_filter_enable(dev); else em_vlan_hw_filter_disable(dev); } } static void em_intr_disable(struct e1000_hw *hw) { E1000_WRITE_REG(hw, E1000_IMC, ~0); } /** * It enables the interrupt mask and then enable the interrupt. * * @param dev * Pointer to struct rte_eth_dev. * * @return * - On success, zero. * - On failure, a negative value. */ static int eth_em_interrupt_setup(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); E1000_WRITE_REG(hw, E1000_IMS, E1000_ICR_LSC); rte_intr_enable(&(dev->pci_dev->intr_handle)); return (0); } /* * It reads ICR and gets interrupt causes, check it and set a bit flag * to update link status. * * @param dev * Pointer to struct rte_eth_dev. * * @return * - On success, zero. * - On failure, a negative value. */ static int eth_em_interrupt_get_status(struct rte_eth_dev *dev) { uint32_t icr; struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct e1000_interrupt *intr = E1000_DEV_PRIVATE_TO_INTR(dev->data->dev_private); /* read-on-clear nic registers here */ icr = E1000_READ_REG(hw, E1000_ICR); if (icr & E1000_ICR_LSC) { intr->flags |= E1000_FLAG_NEED_LINK_UPDATE; } return 0; } /* * It executes link_update after knowing an interrupt is prsent. * * @param dev * Pointer to struct rte_eth_dev. * * @return * - On success, zero. * - On failure, a negative value. */ static int eth_em_interrupt_action(struct rte_eth_dev *dev) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); struct e1000_interrupt *intr = E1000_DEV_PRIVATE_TO_INTR(dev->data->dev_private); uint32_t tctl, rctl; struct rte_eth_link link; int ret; if (!(intr->flags & E1000_FLAG_NEED_LINK_UPDATE)) return -1; intr->flags &= ~E1000_FLAG_NEED_LINK_UPDATE; rte_intr_enable(&(dev->pci_dev->intr_handle)); /* set get_link_status to check register later */ hw->mac.get_link_status = 1; ret = eth_em_link_update(dev, 0); /* check if link has changed */ if (ret < 0) return 0; memset(&link, 0, sizeof(link)); rte_em_dev_atomic_read_link_status(dev, &link); if (link.link_status) { PMD_INIT_LOG(INFO, " Port %d: Link Up - speed %u Mbps - %s", dev->data->port_id, (unsigned)link.link_speed, link.link_duplex == ETH_LINK_FULL_DUPLEX ? "full-duplex" : "half-duplex"); } else { PMD_INIT_LOG(INFO, " Port %d: Link Down", dev->data->port_id); } PMD_INIT_LOG(DEBUG, "PCI Address: %04d:%02d:%02d:%d", dev->pci_dev->addr.domain, dev->pci_dev->addr.bus, dev->pci_dev->addr.devid, dev->pci_dev->addr.function); tctl = E1000_READ_REG(hw, E1000_TCTL); rctl = E1000_READ_REG(hw, E1000_RCTL); if (link.link_status) { /* enable Tx/Rx */ tctl |= E1000_TCTL_EN; rctl |= E1000_RCTL_EN; } else { /* disable Tx/Rx */ tctl &= ~E1000_TCTL_EN; rctl &= ~E1000_RCTL_EN; } E1000_WRITE_REG(hw, E1000_TCTL, tctl); E1000_WRITE_REG(hw, E1000_RCTL, rctl); E1000_WRITE_FLUSH(hw); return 0; } /** * Interrupt handler which shall be registered at first. * * @param handle * Pointer to interrupt handle. * @param param * The address of parameter (struct rte_eth_dev *) regsitered before. * * @return * void */ static void eth_em_interrupt_handler(__rte_unused struct rte_intr_handle *handle, void *param) { struct rte_eth_dev *dev = (struct rte_eth_dev *)param; eth_em_interrupt_get_status(dev); eth_em_interrupt_action(dev); _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC); } static int eth_em_led_on(struct rte_eth_dev *dev) { struct e1000_hw *hw; hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); return (e1000_led_on(hw) == E1000_SUCCESS ? 0 : -ENOTSUP); } static int eth_em_led_off(struct rte_eth_dev *dev) { struct e1000_hw *hw; hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); return (e1000_led_off(hw) == E1000_SUCCESS ? 0 : -ENOTSUP); } static int eth_em_flow_ctrl_get(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf) { struct e1000_hw *hw; uint32_t ctrl; int tx_pause; int rx_pause; hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); fc_conf->pause_time = hw->fc.pause_time; fc_conf->high_water = hw->fc.high_water; fc_conf->low_water = hw->fc.low_water; fc_conf->send_xon = hw->fc.send_xon; fc_conf->autoneg = hw->mac.autoneg; /* * Return rx_pause and tx_pause status according to actual setting of * the TFCE and RFCE bits in the CTRL register. */ ctrl = E1000_READ_REG(hw, E1000_CTRL); if (ctrl & E1000_CTRL_TFCE) tx_pause = 1; else tx_pause = 0; if (ctrl & E1000_CTRL_RFCE) rx_pause = 1; else rx_pause = 0; if (rx_pause && tx_pause) fc_conf->mode = RTE_FC_FULL; else if (rx_pause) fc_conf->mode = RTE_FC_RX_PAUSE; else if (tx_pause) fc_conf->mode = RTE_FC_TX_PAUSE; else fc_conf->mode = RTE_FC_NONE; return 0; } static int eth_em_flow_ctrl_set(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf) { struct e1000_hw *hw; int err; enum e1000_fc_mode rte_fcmode_2_e1000_fcmode[] = { e1000_fc_none, e1000_fc_rx_pause, e1000_fc_tx_pause, e1000_fc_full }; uint32_t rx_buf_size; uint32_t max_high_water; uint32_t rctl; hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); if (fc_conf->autoneg != hw->mac.autoneg) return -ENOTSUP; rx_buf_size = em_get_rx_buffer_size(hw); PMD_INIT_LOG(DEBUG, "Rx packet buffer size = 0x%x", rx_buf_size); /* At least reserve one Ethernet frame for watermark */ max_high_water = rx_buf_size - ETHER_MAX_LEN; if ((fc_conf->high_water > max_high_water) || (fc_conf->high_water < fc_conf->low_water)) { PMD_INIT_LOG(ERR, "e1000 incorrect high/low water value"); PMD_INIT_LOG(ERR, "high water must <= 0x%x", max_high_water); return (-EINVAL); } hw->fc.requested_mode = rte_fcmode_2_e1000_fcmode[fc_conf->mode]; hw->fc.pause_time = fc_conf->pause_time; hw->fc.high_water = fc_conf->high_water; hw->fc.low_water = fc_conf->low_water; hw->fc.send_xon = fc_conf->send_xon; err = e1000_setup_link_generic(hw); if (err == E1000_SUCCESS) { /* check if we want to forward MAC frames - driver doesn't have native * capability to do that, so we'll write the registers ourselves */ rctl = E1000_READ_REG(hw, E1000_RCTL); /* set or clear MFLCN.PMCF bit depending on configuration */ if (fc_conf->mac_ctrl_frame_fwd != 0) rctl |= E1000_RCTL_PMCF; else rctl &= ~E1000_RCTL_PMCF; E1000_WRITE_REG(hw, E1000_RCTL, rctl); E1000_WRITE_FLUSH(hw); return 0; } PMD_INIT_LOG(ERR, "e1000_setup_link_generic = 0x%x", err); return (-EIO); } static void eth_em_rar_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr, uint32_t index, __rte_unused uint32_t pool) { struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); e1000_rar_set(hw, mac_addr->addr_bytes, index); } static void eth_em_rar_clear(struct rte_eth_dev *dev, uint32_t index) { uint8_t addr[ETHER_ADDR_LEN]; struct e1000_hw *hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); memset(addr, 0, sizeof(addr)); e1000_rar_set(hw, addr, index); } static int eth_em_mtu_set(struct rte_eth_dev *dev, uint16_t mtu) { struct rte_eth_dev_info dev_info; struct e1000_hw *hw; uint32_t frame_size; uint32_t rctl; eth_em_infos_get(dev, &dev_info); frame_size = mtu + ETHER_HDR_LEN + ETHER_CRC_LEN + VLAN_TAG_SIZE; /* check that mtu is within the allowed range */ if ((mtu < ETHER_MIN_MTU) || (frame_size > dev_info.max_rx_pktlen)) return -EINVAL; /* refuse mtu that requires the support of scattered packets when this * feature has not been enabled before. */ if (!dev->data->scattered_rx && frame_size > dev->data->min_rx_buf_size - RTE_PKTMBUF_HEADROOM) return -EINVAL; hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); rctl = E1000_READ_REG(hw, E1000_RCTL); /* switch to jumbo mode if needed */ if (frame_size > ETHER_MAX_LEN) { dev->data->dev_conf.rxmode.jumbo_frame = 1; rctl |= E1000_RCTL_LPE; } else { dev->data->dev_conf.rxmode.jumbo_frame = 0; rctl &= ~E1000_RCTL_LPE; } E1000_WRITE_REG(hw, E1000_RCTL, rctl); /* update max frame size */ dev->data->dev_conf.rxmode.max_rx_pkt_len = frame_size; return 0; } static int eth_em_set_mc_addr_list(struct rte_eth_dev *dev, struct ether_addr *mc_addr_set, uint32_t nb_mc_addr) { struct e1000_hw *hw; hw = E1000_DEV_PRIVATE_TO_HW(dev->data->dev_private); e1000_update_mc_addr_list(hw, (u8 *)mc_addr_set, nb_mc_addr); return 0; } struct rte_driver em_pmd_drv = { .type = PMD_PDEV, .init = rte_em_pmd_init, }; PMD_REGISTER_DRIVER(em_pmd_drv);
230123.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NGAP-IEs" * found in "asn/NGAP-IEs.asn" * `asn1c -fcompound-names -findirect-choice -fno-include-deps -gen-PER -no-gen-OER -no-gen-example -D ngap -pdu=all` */ #include "NGAP_PDUSessionResourceListCxtRelCpl.h" #include "NGAP_PDUSessionResourceItemCxtRelCpl.h" asn_per_constraints_t asn_PER_type_NGAP_PDUSessionResourceListCxtRelCpl_constr_1 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 8, 8, 1, 256 } /* (SIZE(1..256)) */, 0, 0 /* No PER value map */ }; asn_TYPE_member_t asn_MBR_NGAP_PDUSessionResourceListCxtRelCpl_1[] = { { ATF_POINTER, 0, 0, (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)), 0, &asn_DEF_NGAP_PDUSessionResourceItemCxtRelCpl, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "" }, }; static const ber_tlv_tag_t asn_DEF_NGAP_PDUSessionResourceListCxtRelCpl_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; asn_SET_OF_specifics_t asn_SPC_NGAP_PDUSessionResourceListCxtRelCpl_specs_1 = { sizeof(struct NGAP_PDUSessionResourceListCxtRelCpl), offsetof(struct NGAP_PDUSessionResourceListCxtRelCpl, _asn_ctx), 0, /* XER encoding is XMLDelimitedItemList */ }; asn_TYPE_descriptor_t asn_DEF_NGAP_PDUSessionResourceListCxtRelCpl = { "PDUSessionResourceListCxtRelCpl", "PDUSessionResourceListCxtRelCpl", &asn_OP_SEQUENCE_OF, asn_DEF_NGAP_PDUSessionResourceListCxtRelCpl_tags_1, sizeof(asn_DEF_NGAP_PDUSessionResourceListCxtRelCpl_tags_1) /sizeof(asn_DEF_NGAP_PDUSessionResourceListCxtRelCpl_tags_1[0]), /* 1 */ asn_DEF_NGAP_PDUSessionResourceListCxtRelCpl_tags_1, /* Same as above */ sizeof(asn_DEF_NGAP_PDUSessionResourceListCxtRelCpl_tags_1) /sizeof(asn_DEF_NGAP_PDUSessionResourceListCxtRelCpl_tags_1[0]), /* 1 */ { 0, &asn_PER_type_NGAP_PDUSessionResourceListCxtRelCpl_constr_1, SEQUENCE_OF_constraint }, asn_MBR_NGAP_PDUSessionResourceListCxtRelCpl_1, 1, /* Single element */ &asn_SPC_NGAP_PDUSessionResourceListCxtRelCpl_specs_1 /* Additional specs */ };
48658.c
void BTSR1_DecTraceCb_SetupForTrace(BTSR1_Context *ctx, BTSR1_Trace *tr) { ctx->tr_cur=tr; ctx->tr_rnxt=tr->lnknext; ctx->tr_rjmp=tr->jmpnext; ctx->regs[BTSR1_REG_PC]=tr->addr_nxt; } BTSR1_Trace *BTSR1_DecTraceCb_Run1(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run2(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run3(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run4(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run5(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run6(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run7(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run8(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run9(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run10(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run11(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run12(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run13(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run14(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run15(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run16(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run17(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run18(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run19(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run20(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run21(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run22(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run23(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run24(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run25(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run26(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run27(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run28(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run29(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run30(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run31(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Run32(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_Opcode **ops; BTSR1_DecTraceCb_SetupForTrace(ctx, tr); ops=tr->ops; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; (*ops)->Run(ctx, *ops); ops++; return(ctx->tr_rnxt); } BTSR1_Trace *BTSR1_DecTraceCb_Bad(BTSR1_Context *ctx, BTSR1_Trace *tr) { BTSR1_ThrowFaultStatus(ctx, BTSR1_FLT_INV_MEX); return(NULL); } int BTSR1_DecodeTraceForAddr(BTSR1_Context *ctx, BTSR1_Trace *tr, btsr1_addr addr) { BTSR1_Opcode *op; int ldrl, vdrl; int pc, nc, ncyc, npc, jpc; if((addr&1) || (addr&(~65535))) { tr->n_ops=0; tr->n_cyc=0; tr->Run=BTSR1_DecTraceCb_Bad; return(-1); } ldrl=0; vdrl=0; nc=0; ncyc=0; pc=addr; npc=0; jpc=0; while(nc<BTSR1_TR_MAXOP) { op=BTSR1_ContextAllocOpcode(ctx); BTSR1_DecodeOpcodeForAddr(ctx, op, pc); tr->ops[nc++]=op; // ncyc++; ncyc+=op->cyc; pc+=2; if(op->fl&BTSR1_OPFL_TWOWORD) { ncyc++; pc+=2; } if(op->fl&BTSR1_OPFL_CTRLF) { if(op->nmid!=BTSR1_NMID_BRA) { npc=pc; } if( (op->nmid==BTSR1_NMID_BRA) || (op->nmid==BTSR1_NMID_BSR) || (op->nmid==BTSR1_NMID_BT) || (op->nmid==BTSR1_NMID_BF) ) { if(op->fmid==BTSR1_FMID_PCDISP) { jpc=(op->pc+2)+(op->imm*2); } if(vdrl && (op->fmid==BTSR1_FMID_PCDR4)) { jpc=(op->pc+2)+(ldrl*32)+(op->imm*2); } if(vdrl && (op->fmid==BTSR1_FMID_PCDR)) { jpc=(op->pc+2)+(ldrl*2); } } break; }else { if((op->nmid==BTSR1_NMID_LDIZ) || (op->nmid==BTSR1_NMID_LDIN)) { ldrl=op->imm; vdrl=1; }else if(op->nmid==BTSR1_NMID_LDISH) { ldrl=(ldrl<<8)|(op->imm&255); }else { vdrl=0; } } } if(nc>=BTSR1_TR_MAXOP) { npc=pc; } tr->n_ops=nc; tr->n_cyc=ncyc; tr->addr_nxt=npc; tr->addr_jmp=jpc; if(npc) { tr->lnknext=BTSR1_GetTraceForAddr(ctx, pc); } if(jpc) { tr->jmpnext=BTSR1_GetTraceForAddr(ctx, jpc); } switch(nc) { case 1: tr->Run=BTSR1_DecTraceCb_Run1; break; case 2: tr->Run=BTSR1_DecTraceCb_Run2; break; case 3: tr->Run=BTSR1_DecTraceCb_Run3; break; case 4: tr->Run=BTSR1_DecTraceCb_Run4; break; case 5: tr->Run=BTSR1_DecTraceCb_Run5; break; case 6: tr->Run=BTSR1_DecTraceCb_Run6; break; case 7: tr->Run=BTSR1_DecTraceCb_Run7; break; case 8: tr->Run=BTSR1_DecTraceCb_Run8; break; case 9: tr->Run=BTSR1_DecTraceCb_Run9; break; case 10: tr->Run=BTSR1_DecTraceCb_Run10; break; case 11: tr->Run=BTSR1_DecTraceCb_Run11; break; case 12: tr->Run=BTSR1_DecTraceCb_Run12; break; case 13: tr->Run=BTSR1_DecTraceCb_Run13; break; case 14: tr->Run=BTSR1_DecTraceCb_Run14; break; case 15: tr->Run=BTSR1_DecTraceCb_Run15; break; case 16: tr->Run=BTSR1_DecTraceCb_Run16; break; case 17: tr->Run=BTSR1_DecTraceCb_Run17; break; case 18: tr->Run=BTSR1_DecTraceCb_Run18; break; case 19: tr->Run=BTSR1_DecTraceCb_Run19; break; case 20: tr->Run=BTSR1_DecTraceCb_Run20; break; case 21: tr->Run=BTSR1_DecTraceCb_Run21; break; case 22: tr->Run=BTSR1_DecTraceCb_Run22; break; case 23: tr->Run=BTSR1_DecTraceCb_Run23; break; case 24: tr->Run=BTSR1_DecTraceCb_Run24; break; case 25: tr->Run=BTSR1_DecTraceCb_Run25; break; case 26: tr->Run=BTSR1_DecTraceCb_Run26; break; case 27: tr->Run=BTSR1_DecTraceCb_Run27; break; case 28: tr->Run=BTSR1_DecTraceCb_Run28; break; case 29: tr->Run=BTSR1_DecTraceCb_Run29; break; case 30: tr->Run=BTSR1_DecTraceCb_Run30; break; case 31: tr->Run=BTSR1_DecTraceCb_Run31; break; case 32: tr->Run=BTSR1_DecTraceCb_Run32; break; } return(0); }
199642.c
#include <ansi.h> #include "etc.h" inherit NPC; inherit F_MASTER; inherit F_QUESTER; mixed ask_skill(); mixed ask_skill2(); void create() { set_name("黎夫人", ({ "li furen", "li", "furen"})); set("gender", "女性"); set("title", "南海椰花岛岛主"); set("age", 37); set("long", @LONG 这便是南海椰花岛岛主黎夫人,只见她不过中 年,但头发已是班白,手持一根形状颇为奇特 的钓竿,不知究为何物。 LONG ); set("attitude", "peaceful"); set("str", 30); set("int", 30); set("con", 30); set("dex", 30); set("qi", 3600); set("max_qi", 3600); set("jing", 2000); set("max_jing", 2000); set("neili", 3200); set("max_neili", 3200); set("jiali", 100); set("combat_exp", 1400000); set_skill("force", 180); set_skill("linji-zhuang", 180); set_skill("dodge", 180); set_skill("caiyan-gong", 180); set_skill("hand", 180); set_skill("jieshou-jiushi", 180); set_skill("parry", 180); set_skill("club", 180); set_skill("literate", 160); set_skill("martial-cognize", 160); set_skill("mahayana", 180); map_skill("force", "linji-zhuang"); map_skill("dodge", "caiyan-gong"); map_skill("club", "caiyan-gong"); map_skill("parry", "caiyan-gong"); map_skill("hand", "jieshou-jiushi"); prepare_skill("hand", "jieshou-jiushi"); set("inquiry", ([ "云霞幻生" : (: ask_skill :), "截筋断脉" : (: ask_skill2 :), "虚竹" : "他是我们灵鹫宫新的主公,我们全部听他号令。", "虚竹子" : "他是我们灵鹫宫新的主公,我们全部听他号令。", ])); create_family("椰花岛", 11, "岛主"); set("chat_chance_combat", 120); set("chat_msg_combat", ({ (: perform_action, "club.huan" :), (: exert_function, "powerup" :), (: exert_function, "recover" :), }) ); setup(); carry_object("/d/lingjiu/npc/obj/diaogan")->wield(); carry_object("/d/city/npc/cloth/color-dress")->wear(); } int recognize_apprentice(object ob, string skill) { if (ob->query("family/family_name") != "灵鹫宫") { command("hmm"); command("say 给老娘滚开。"); return -1; } if (ob->query("family/master_id") != "xuzhu zi") { command("heng"); command("say 找你师父去,没大没小,缺乏管教。"); return -1; } if (skill != "caiyan-gong" && skill != "club") { command("say 我只能教你一些棍法功夫,不学就算了。"); return -1; } if (! ob->query_temp("can_learn/lifuren")) { command("nod2"); command("say 既然你是主公的弟子,我就教你好了。"); ob->set_temp("can_learn/lifuren", 1); } return 1; } mixed ask_skill() { object me; me = this_player(); if (me->query("can_perform/caiyan-gong/huan")) return "你不是已经学会了吗?何故来消遣老娘!"; if (me->query("family/family_name") != "灵鹫宫" && me->query("family/family_name") != "椰花岛") return "还不给老娘滚开!"; if (me->query_skill("caiyan-gong", 1) < 1) return "你采燕功都未曾练过,还谈什么绝招。"; if (me->query("family/family_name") == "灵鹫宫" && me->query("gongxian") < 500) return "主公有令,不得传功给无功劳的弟子。"; if (me->query_skill("dodge") < 180) return "你的轻功火候未到,学不了这招。"; if (me->query_skill("caiyan-gong", 1) < 120) return "你的采燕功火候还差得远,再回去练练!"; message_vision(HIY "$n" HIY "点了点头,喝道:“看好了!”说完" "单手一抖,已抽\n出背负在背上的钓竿,随即急速舞" "动,顿时只见钓竿由一变\n二,由二变四,由四变八" ",由八变十六……幻出无数竿影连\n连刺出,全全笼" "罩$N" HIY "四周各个方位。\n" NOR, me, this_object()); command("sweat"); command("say 这招看起来复杂,其实却并不难练习。"); tell_object(me, HIC "你学会了「云霞幻生」。\n" NOR); if (me->can_improve_skill("dodge")) me->improve_skill("dodge", 1500000); if (me->can_improve_skill("club")) me->improve_skill("club", 1500000); if (me->can_improve_skill("caiyan-gong")) me->improve_skill("caiyan-gong", 1500000); me->improve_skill("martial-cognize", 1500000); me->set("can_perform/caiyan-gong/huan", 1); if (me->query("family/family_name") == "灵鹫宫") me->add("gongxian", -500); return 1; } mixed ask_skill2() { object me; me = this_player(); if (me->query("can_perform/jieshou-jiushi/jie")) return "这招我不是已经教过你了吗?自己下去多练吧!"; if (me->query("family/family_name") != query("family/family_name")) return "你是哪里来的?快给我滚开!"; if (me->query_skill("jieshou-jiushi", 1) < 1) return "你连截手九式都没学,还谈什么绝招可言?"; if (me->query("gongxian") < 300) return "哼,你在本派中碌碌无为,这一招我暂时还不能传你。"; if (me->query("max_neili") < 850) return "你的内力修行太浅,尚且学不了这一招。"; if (me->query_skill("force") < 120) return "你的内功修行太浅,尚且学不了这一招。"; if (me->query_skill("jieshou-jiushi", 1) < 100) return "你的截手九式火候未到,尚且学不了这一招。"; message_sort(HIY "\n$n" HIY "甚喜,对$N" HIY "点头道:“不错,不" "错。你这孩子,真不亏了我平时的教诲。”说完将$N" HIY "招至跟前,细说良久。\n\n" NOR, me, this_object()); command("say 这招也是峨眉派的绝学,你可不能外传。"); tell_object(me, HIC "你学会了「截筋断脉」。\n" NOR); if (me->can_improve_skill("hand")) me->improve_skill("hand", 1500000); if (me->can_improve_skill("jieshou-jiushi")) me->improve_skill("jieshou-jiushi", 1500000); me->improve_skill("martial-cognize", 1500000); me->set("can_perform/jieshou-jiushi/jie", 1); me->add("gongxian", -300); return 1; } void attempt_apprentice(object ob) { if (! permit_recruit(ob)) return; command("en"); command("say 好吧,既然你想闹着玩,老娘就收下你好了!"); command("recruit " + ob->query("id")); } void unconcious() { die(); }
696149.c
/* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" static int32_t t5 = -7930006; static int16_t x32 = -185; uint16_t x33 = 8765U; volatile int32_t t8 = -42487604; static int8_t x50 = INT8_MIN; int64_t x55 = 1336LL; int64_t x56 = INT64_MAX; uint32_t x57 = 224446U; volatile int64_t x67 = -1LL; uint32_t x74 = 4827U; int8_t x75 = -1; uint16_t x77 = 1335U; int32_t x78 = -1; int8_t x96 = INT8_MAX; int32_t x103 = -1; static uint8_t x106 = 3U; int32_t x113 = -1; volatile int32_t x114 = 32; volatile int32_t t28 = 10; volatile int32_t x120 = -1; volatile int8_t x121 = INT8_MIN; volatile int64_t t30 = -6977961545536LL; int8_t x127 = -1; uint8_t x128 = UINT8_MAX; static volatile uint64_t x134 = 11877887521658LLU; volatile uint64_t t33 = 1540612LLU; int64_t x139 = -1LL; int16_t x141 = INT16_MIN; volatile uint64_t x145 = 354537337LLU; int8_t x147 = INT8_MIN; static int32_t x151 = INT32_MAX; int64_t x152 = 1683LL; uint32_t t37 = 9529564U; int64_t x157 = -1795689821952069129LL; uint64_t x160 = 6713583181242648863LLU; static int8_t x170 = INT8_MIN; volatile int8_t x171 = INT8_MAX; uint64_t x182 = UINT64_MAX; static int64_t x187 = INT64_MAX; volatile int64_t x196 = -1LL; int8_t x197 = INT8_MIN; int16_t x208 = 3864; int64_t x212 = INT64_MIN; static uint32_t x215 = UINT32_MAX; int16_t x219 = INT16_MAX; int16_t x220 = -110; int8_t x224 = INT8_MIN; static int16_t x225 = 44; volatile int64_t x232 = 54LL; static volatile int32_t t57 = -13; static uint64_t x238 = 71962210LLU; int8_t x243 = -1; static uint64_t x255 = UINT64_MAX; int16_t x256 = 15; int16_t x258 = -2; volatile uint64_t x261 = 724897727249LLU; static uint32_t x269 = 29U; volatile uint32_t t67 = 931205U; uint32_t x275 = 1993496U; int8_t x279 = INT8_MIN; int32_t x281 = -1; static int8_t x285 = -17; int64_t x288 = INT64_MIN; int16_t x292 = -13; volatile int16_t x300 = 8; uint32_t x301 = UINT32_MAX; volatile uint32_t t75 = UINT32_MAX; volatile uint8_t x307 = 3U; int8_t x310 = -1; int8_t x312 = INT8_MAX; static volatile uint8_t x315 = 35U; int64_t x317 = 4054682LL; volatile int16_t x319 = INT16_MIN; int8_t x332 = -1; volatile uint32_t t83 = 8068868U; int8_t x339 = INT8_MIN; int16_t x347 = INT16_MAX; int16_t x348 = INT16_MIN; uint8_t x353 = 54U; int8_t x354 = -2; int8_t x357 = 2; volatile int16_t x367 = INT16_MIN; int16_t x376 = -1; uint64_t x378 = UINT64_MAX; static volatile int16_t x382 = -2034; int64_t x384 = INT64_MIN; volatile int32_t t94 = 7734453; volatile int64_t t96 = 14600LL; int8_t x395 = 17; int64_t x399 = -1LL; volatile int16_t x401 = 0; int64_t x402 = INT64_MIN; uint64_t x407 = 27412940943LLU; int32_t x409 = INT32_MIN; int64_t x413 = INT64_MIN; volatile uint64_t x416 = UINT64_MAX; volatile int32_t t103 = -22796; int64_t x432 = INT64_MIN; uint32_t x439 = 6572U; uint64_t x444 = 2303309592LLU; int64_t x454 = -1LL; uint32_t x457 = 66743U; int32_t x462 = INT32_MIN; int16_t x464 = INT16_MAX; int16_t x466 = INT16_MAX; int64_t t114 = -5642902384LL; static uint64_t x476 = 6251401LLU; int64_t x479 = INT64_MIN; uint32_t x485 = UINT32_MAX; volatile uint32_t t118 = 110U; volatile int32_t t120 = 114508; static int32_t x501 = 3561; int16_t x502 = -1; volatile int32_t t122 = -1602; static int8_t x505 = -1; uint16_t x506 = UINT16_MAX; volatile int64_t x507 = -12758569LL; static int32_t x512 = INT32_MAX; static volatile int64_t t125 = -1035694523LL; int64_t x526 = INT64_MAX; uint16_t x528 = UINT16_MAX; static uint32_t x534 = UINT32_MAX; static volatile int64_t x538 = INT64_MIN; uint64_t x539 = 4LLU; volatile int8_t x542 = INT8_MIN; int64_t x547 = -98140780963333159LL; static volatile uint16_t x551 = 3U; static uint16_t x555 = 1U; static int16_t x557 = -2782; uint8_t x564 = 44U; volatile uint64_t x567 = UINT64_MAX; volatile uint64_t t138 = 7LLU; int32_t x573 = 1; int32_t t140 = 509; int8_t x579 = INT8_MIN; volatile int64_t x581 = 7727779773619295LL; static int16_t x582 = 13453; uint8_t x584 = UINT8_MAX; int8_t x591 = INT8_MIN; int16_t x597 = 0; int16_t x605 = INT16_MIN; int32_t x612 = -121; int8_t x613 = 7; volatile uint32_t t150 = 8492965U; int16_t x619 = -248; uint64_t x622 = 3116LLU; uint32_t x623 = 2081014U; int8_t x624 = -3; uint64_t x625 = 4613703670669635480LLU; static volatile uint64_t t153 = 140157621655355949LLU; static int64_t x629 = -1912709095520LL; int64_t t154 = 131575195181745LL; int16_t x642 = INT16_MAX; static int8_t x649 = -1; int64_t t158 = 53249LL; uint32_t x663 = 363012U; static volatile int16_t x672 = INT16_MIN; uint8_t x673 = 7U; int64_t x680 = -1LL; int32_t x683 = INT32_MAX; int64_t t165 = -907251490259LL; int16_t x699 = 56; uint32_t t169 = 2971U; int8_t x707 = INT8_MIN; uint64_t x709 = 135LLU; int64_t x710 = -1LL; uint16_t x714 = 0U; volatile int32_t x719 = INT32_MIN; int16_t x726 = INT16_MIN; uint8_t x734 = UINT8_MAX; int16_t x739 = 0; volatile int16_t x741 = INT16_MIN; int32_t x742 = INT32_MAX; static int64_t x743 = INT64_MIN; volatile int64_t x744 = 841182568220610LL; volatile uint16_t x768 = UINT16_MAX; static uint8_t x770 = 0U; volatile int32_t t187 = -54; volatile int32_t x773 = -1; static volatile int8_t x774 = INT8_MIN; int16_t x776 = -3574; int8_t x784 = -1; int16_t x785 = -1; int32_t x792 = -2296; int32_t x793 = INT32_MAX; int64_t x797 = -1LL; int16_t x798 = -1; int64_t x807 = INT64_MIN; static int64_t x812 = -1LL; int64_t t197 = -105582860319132178LL; static int8_t x815 = 2; int32_t t199 = 241865; void f0(void) { int16_t x1 = 0; volatile int8_t x2 = INT8_MIN; int64_t x3 = INT64_MIN; static uint8_t x4 = 80U; int32_t t0 = 1; t0 = ((x1|x2)+(x3!=x4)); if (t0 != -127) { NG(); } else { ; } } void f1(void) { volatile uint32_t x5 = 14332U; int16_t x6 = INT16_MAX; volatile int16_t x7 = INT16_MIN; volatile uint64_t x8 = 9873LLU; static uint32_t t1 = 60071117U; t1 = ((x5|x6)+(x7!=x8)); if (t1 != 32768U) { NG(); } else { ; } } void f2(void) { int16_t x9 = INT16_MAX; volatile int16_t x10 = INT16_MIN; int16_t x11 = -1; uint8_t x12 = 0U; volatile int32_t t2 = 43091994; t2 = ((x9|x10)+(x11!=x12)); if (t2 != 0) { NG(); } else { ; } } void f3(void) { int16_t x13 = 0; int32_t x14 = -48451033; int64_t x15 = 2740986169LL; int64_t x16 = -55379554128651LL; volatile int32_t t3 = -80441; t3 = ((x13|x14)+(x15!=x16)); if (t3 != -48451032) { NG(); } else { ; } } void f4(void) { volatile int64_t x17 = INT64_MIN; uint64_t x18 = 1298817643497723LLU; static int8_t x19 = INT8_MIN; volatile int8_t x20 = INT8_MIN; uint64_t t4 = 291167924825LLU; t4 = ((x17|x18)+(x19!=x20)); if (t4 != 9224670854498273531LLU) { NG(); } else { ; } } void f5(void) { static uint16_t x21 = 1846U; static uint16_t x22 = 3679U; static int16_t x23 = INT16_MAX; volatile int16_t x24 = INT16_MIN; t5 = ((x21|x22)+(x23!=x24)); if (t5 != 3968) { NG(); } else { ; } } void f6(void) { uint64_t x25 = 80517262667181196LLU; int8_t x26 = -10; static uint8_t x27 = 51U; int32_t x28 = INT32_MAX; volatile uint64_t t6 = UINT64_MAX; t6 = ((x25|x26)+(x27!=x28)); if (t6 != UINT64_MAX) { NG(); } else { ; } } void f7(void) { int64_t x29 = 8451558760639032LL; static uint8_t x30 = 42U; static int8_t x31 = INT8_MIN; int64_t t7 = -2207581555741934LL; t7 = ((x29|x30)+(x31!=x32)); if (t7 != 8451558760639035LL) { NG(); } else { ; } } void f8(void) { int8_t x34 = INT8_MIN; uint32_t x35 = 9802U; int16_t x36 = -1; t8 = ((x33|x34)+(x35!=x36)); if (t8 != -66) { NG(); } else { ; } } void f9(void) { int16_t x37 = 4; uint16_t x38 = UINT16_MAX; uint64_t x39 = UINT64_MAX; uint32_t x40 = UINT32_MAX; volatile int32_t t9 = -2934118; t9 = ((x37|x38)+(x39!=x40)); if (t9 != 65536) { NG(); } else { ; } } void f10(void) { int16_t x41 = INT16_MIN; int16_t x42 = -264; int64_t x43 = -1LL; volatile int32_t x44 = -1; volatile int32_t t10 = 15; t10 = ((x41|x42)+(x43!=x44)); if (t10 != -264) { NG(); } else { ; } } void f11(void) { volatile int16_t x45 = -1; uint32_t x46 = UINT32_MAX; uint16_t x47 = 21U; static int16_t x48 = INT16_MIN; volatile uint32_t t11 = 222379U; t11 = ((x45|x46)+(x47!=x48)); if (t11 != 0U) { NG(); } else { ; } } void f12(void) { volatile uint64_t x49 = 1006259LLU; uint16_t x51 = UINT16_MAX; int32_t x52 = INT32_MAX; uint64_t t12 = 258102436710LLU; t12 = ((x49|x50)+(x51!=x52)); if (t12 != 18446744073709551540LLU) { NG(); } else { ; } } void f13(void) { volatile uint16_t x53 = UINT16_MAX; volatile int8_t x54 = -1; volatile int32_t t13 = -543439592; t13 = ((x53|x54)+(x55!=x56)); if (t13 != 0) { NG(); } else { ; } } void f14(void) { static int16_t x58 = -1; volatile int8_t x59 = INT8_MIN; uint16_t x60 = UINT16_MAX; volatile uint32_t t14 = 1U; t14 = ((x57|x58)+(x59!=x60)); if (t14 != 0U) { NG(); } else { ; } } void f15(void) { int64_t x61 = INT64_MIN; int8_t x62 = INT8_MAX; volatile int32_t x63 = INT32_MAX; static volatile int8_t x64 = -1; static int64_t t15 = 675410634105069760LL; t15 = ((x61|x62)+(x63!=x64)); if (t15 != -9223372036854775680LL) { NG(); } else { ; } } void f16(void) { int8_t x65 = INT8_MIN; static int16_t x66 = INT16_MIN; int32_t x68 = 25; volatile int32_t t16 = -1067805; t16 = ((x65|x66)+(x67!=x68)); if (t16 != -127) { NG(); } else { ; } } void f17(void) { volatile int16_t x69 = -565; int32_t x70 = -470888438; int16_t x71 = -1; int16_t x72 = INT16_MAX; int32_t t17 = 15; t17 = ((x69|x70)+(x71!=x72)); if (t17 != -564) { NG(); } else { ; } } void f18(void) { int32_t x73 = 0; volatile uint32_t x76 = UINT32_MAX; volatile uint32_t t18 = 264215638U; t18 = ((x73|x74)+(x75!=x76)); if (t18 != 4827U) { NG(); } else { ; } } void f19(void) { int16_t x79 = INT16_MAX; uint8_t x80 = UINT8_MAX; int32_t t19 = -570637; t19 = ((x77|x78)+(x79!=x80)); if (t19 != 0) { NG(); } else { ; } } void f20(void) { uint64_t x81 = 9079025440908LLU; uint8_t x82 = UINT8_MAX; int32_t x83 = 144; int32_t x84 = 288; volatile uint64_t t20 = 340952LLU; t20 = ((x81|x82)+(x83!=x84)); if (t20 != 9079025441024LLU) { NG(); } else { ; } } void f21(void) { volatile int64_t x85 = -1LL; volatile uint16_t x86 = UINT16_MAX; volatile uint64_t x87 = 3140852332067456LLU; static volatile int16_t x88 = INT16_MAX; volatile int64_t t21 = 2LL; t21 = ((x85|x86)+(x87!=x88)); if (t21 != 0LL) { NG(); } else { ; } } void f22(void) { static uint16_t x89 = 337U; uint16_t x90 = 32U; uint64_t x91 = UINT64_MAX; static uint8_t x92 = 18U; int32_t t22 = 3; t22 = ((x89|x90)+(x91!=x92)); if (t22 != 370) { NG(); } else { ; } } void f23(void) { uint32_t x93 = 23665567U; int16_t x94 = -1; int32_t x95 = -1; volatile uint32_t t23 = 27497U; t23 = ((x93|x94)+(x95!=x96)); if (t23 != 0U) { NG(); } else { ; } } void f24(void) { static volatile uint32_t x97 = 60U; int16_t x98 = INT16_MIN; int16_t x99 = INT16_MIN; int8_t x100 = -1; volatile uint32_t t24 = 1U; t24 = ((x97|x98)+(x99!=x100)); if (t24 != 4294934589U) { NG(); } else { ; } } void f25(void) { int16_t x101 = INT16_MIN; static int64_t x102 = 1850902195LL; static volatile int32_t x104 = INT32_MIN; static volatile int64_t t25 = 24811966LL; t25 = ((x101|x102)+(x103!=x104)); if (t25 != -31052LL) { NG(); } else { ; } } void f26(void) { uint16_t x105 = 2033U; int8_t x107 = INT8_MIN; int32_t x108 = INT32_MIN; static volatile int32_t t26 = 38966603; t26 = ((x105|x106)+(x107!=x108)); if (t26 != 2036) { NG(); } else { ; } } void f27(void) { int64_t x109 = 16159LL; int8_t x110 = INT8_MIN; static volatile int8_t x111 = -1; int16_t x112 = INT16_MIN; volatile int64_t t27 = 307723995LL; t27 = ((x109|x110)+(x111!=x112)); if (t27 != -96LL) { NG(); } else { ; } } void f28(void) { uint32_t x115 = UINT32_MAX; volatile int32_t x116 = 182596; t28 = ((x113|x114)+(x115!=x116)); if (t28 != 0) { NG(); } else { ; } } void f29(void) { int16_t x117 = INT16_MIN; int16_t x118 = INT16_MIN; volatile int8_t x119 = -24; volatile int32_t t29 = 255; t29 = ((x117|x118)+(x119!=x120)); if (t29 != -32767) { NG(); } else { ; } } void f30(void) { int64_t x122 = -32643614748066074LL; int16_t x123 = INT16_MIN; int8_t x124 = INT8_MAX; t30 = ((x121|x122)+(x123!=x124)); if (t30 != -25LL) { NG(); } else { ; } } void f31(void) { uint8_t x125 = UINT8_MAX; int8_t x126 = 0; volatile int32_t t31 = 34; t31 = ((x125|x126)+(x127!=x128)); if (t31 != 256) { NG(); } else { ; } } void f32(void) { int8_t x129 = INT8_MAX; int32_t x130 = INT32_MIN; uint64_t x131 = UINT64_MAX; static volatile int8_t x132 = -1; volatile int32_t t32 = 4; t32 = ((x129|x130)+(x131!=x132)); if (t32 != -2147483521) { NG(); } else { ; } } void f33(void) { uint64_t x133 = UINT64_MAX; int16_t x135 = -1; static int16_t x136 = -8308; t33 = ((x133|x134)+(x135!=x136)); if (t33 != 0LLU) { NG(); } else { ; } } void f34(void) { int32_t x137 = INT32_MIN; uint32_t x138 = UINT32_MAX; int64_t x140 = 497LL; volatile uint32_t t34 = 83507U; t34 = ((x137|x138)+(x139!=x140)); if (t34 != 0U) { NG(); } else { ; } } void f35(void) { volatile int16_t x142 = INT16_MIN; volatile int16_t x143 = INT16_MAX; static int16_t x144 = INT16_MAX; int32_t t35 = 105042804; t35 = ((x141|x142)+(x143!=x144)); if (t35 != -32768) { NG(); } else { ; } } void f36(void) { int32_t x146 = INT32_MIN; uint8_t x148 = 27U; static volatile uint64_t t36 = 995200136811LLU; t36 = ((x145|x146)+(x147!=x148)); if (t36 != 18446744071916605306LLU) { NG(); } else { ; } } void f37(void) { uint32_t x149 = 34617U; volatile int32_t x150 = -1; t37 = ((x149|x150)+(x151!=x152)); if (t37 != 0U) { NG(); } else { ; } } void f38(void) { volatile int16_t x153 = 60; int64_t x154 = INT64_MIN; uint8_t x155 = UINT8_MAX; static uint32_t x156 = UINT32_MAX; volatile int64_t t38 = 8319764234870459LL; t38 = ((x153|x154)+(x155!=x156)); if (t38 != -9223372036854775747LL) { NG(); } else { ; } } void f39(void) { volatile uint8_t x158 = 12U; static uint16_t x159 = 583U; int64_t t39 = 83993LL; t39 = ((x157|x158)+(x159!=x160)); if (t39 != -1795689821952069120LL) { NG(); } else { ; } } void f40(void) { int16_t x161 = 161; volatile uint8_t x162 = 5U; uint64_t x163 = UINT64_MAX; uint8_t x164 = 1U; static int32_t t40 = -43; t40 = ((x161|x162)+(x163!=x164)); if (t40 != 166) { NG(); } else { ; } } void f41(void) { uint32_t x165 = 22287486U; int8_t x166 = INT8_MAX; int8_t x167 = 47; uint32_t x168 = 30U; uint32_t t41 = 155144U; t41 = ((x165|x166)+(x167!=x168)); if (t41 != 22287488U) { NG(); } else { ; } } void f42(void) { int64_t x169 = -602LL; uint8_t x172 = 0U; volatile int64_t t42 = -2789567LL; t42 = ((x169|x170)+(x171!=x172)); if (t42 != -89LL) { NG(); } else { ; } } void f43(void) { volatile int16_t x173 = INT16_MIN; int32_t x174 = -68; int8_t x175 = INT8_MIN; volatile uint8_t x176 = UINT8_MAX; volatile int32_t t43 = -15741029; t43 = ((x173|x174)+(x175!=x176)); if (t43 != -67) { NG(); } else { ; } } void f44(void) { int8_t x177 = 3; static int8_t x178 = -1; int32_t x179 = -221825293; volatile int16_t x180 = -1; static volatile int32_t t44 = 1321954; t44 = ((x177|x178)+(x179!=x180)); if (t44 != 0) { NG(); } else { ; } } void f45(void) { uint16_t x181 = 0U; volatile uint16_t x183 = 90U; static int32_t x184 = -4339152; volatile uint64_t t45 = 3287LLU; t45 = ((x181|x182)+(x183!=x184)); if (t45 != 0LLU) { NG(); } else { ; } } void f46(void) { volatile int8_t x185 = INT8_MIN; volatile uint8_t x186 = 105U; int16_t x188 = -1; static int32_t t46 = 8225; t46 = ((x185|x186)+(x187!=x188)); if (t46 != -22) { NG(); } else { ; } } void f47(void) { int32_t x189 = -44879572; int64_t x190 = -32946814393725568LL; int16_t x191 = 28; volatile int64_t x192 = INT64_MAX; int64_t t47 = -57131LL; t47 = ((x189|x190)+(x191!=x192)); if (t47 != -2622035LL) { NG(); } else { ; } } void f48(void) { volatile int64_t x193 = 371472991867068625LL; volatile int16_t x194 = -1; uint16_t x195 = 59U; int64_t t48 = 341045608LL; t48 = ((x193|x194)+(x195!=x196)); if (t48 != 0LL) { NG(); } else { ; } } void f49(void) { int16_t x198 = INT16_MIN; volatile int16_t x199 = 1; uint64_t x200 = 268434043111268LLU; static volatile int32_t t49 = -2; t49 = ((x197|x198)+(x199!=x200)); if (t49 != -127) { NG(); } else { ; } } void f50(void) { uint32_t x201 = UINT32_MAX; static uint8_t x202 = 0U; static int8_t x203 = INT8_MAX; volatile int64_t x204 = 805201238227251LL; volatile uint32_t t50 = 43035U; t50 = ((x201|x202)+(x203!=x204)); if (t50 != 0U) { NG(); } else { ; } } void f51(void) { uint16_t x205 = 11270U; int32_t x206 = -274368; uint32_t x207 = 1U; static volatile int32_t t51 = -95514781; t51 = ((x205|x206)+(x207!=x208)); if (t51 != -263097) { NG(); } else { ; } } void f52(void) { int32_t x209 = INT32_MIN; int32_t x210 = INT32_MAX; static int8_t x211 = INT8_MIN; static volatile int32_t t52 = -124649; t52 = ((x209|x210)+(x211!=x212)); if (t52 != 0) { NG(); } else { ; } } void f53(void) { int8_t x213 = INT8_MAX; int64_t x214 = -1LL; volatile int64_t x216 = -23162535LL; volatile int64_t t53 = -1474390298888LL; t53 = ((x213|x214)+(x215!=x216)); if (t53 != 0LL) { NG(); } else { ; } } void f54(void) { volatile int8_t x217 = INT8_MIN; int64_t x218 = INT64_MIN; static int64_t t54 = 208053LL; t54 = ((x217|x218)+(x219!=x220)); if (t54 != -127LL) { NG(); } else { ; } } void f55(void) { static uint64_t x221 = 3LLU; int8_t x222 = -1; volatile int64_t x223 = INT64_MIN; static uint64_t t55 = 647940LLU; t55 = ((x221|x222)+(x223!=x224)); if (t55 != 0LLU) { NG(); } else { ; } } void f56(void) { static uint64_t x226 = UINT64_MAX; int32_t x227 = -2141021; uint16_t x228 = UINT16_MAX; static uint64_t t56 = 338365395479241LLU; t56 = ((x225|x226)+(x227!=x228)); if (t56 != 0LLU) { NG(); } else { ; } } void f57(void) { uint16_t x229 = 260U; volatile uint16_t x230 = 1U; volatile int16_t x231 = INT16_MIN; t57 = ((x229|x230)+(x231!=x232)); if (t57 != 262) { NG(); } else { ; } } void f58(void) { volatile uint16_t x233 = 0U; static int64_t x234 = 31LL; int16_t x235 = INT16_MIN; volatile uint64_t x236 = 22792515869476LLU; volatile int64_t t58 = 3476486097408607633LL; t58 = ((x233|x234)+(x235!=x236)); if (t58 != 32LL) { NG(); } else { ; } } void f59(void) { int16_t x237 = -1; volatile uint8_t x239 = 114U; int8_t x240 = 32; uint64_t t59 = 758163325LLU; t59 = ((x237|x238)+(x239!=x240)); if (t59 != 0LLU) { NG(); } else { ; } } void f60(void) { static int8_t x241 = INT8_MIN; static int16_t x242 = INT16_MAX; uint16_t x244 = UINT16_MAX; int32_t t60 = -496; t60 = ((x241|x242)+(x243!=x244)); if (t60 != 0) { NG(); } else { ; } } void f61(void) { static int32_t x245 = INT32_MIN; static int32_t x246 = -1; int32_t x247 = INT32_MIN; int64_t x248 = -1LL; volatile int32_t t61 = 1668797; t61 = ((x245|x246)+(x247!=x248)); if (t61 != 0) { NG(); } else { ; } } void f62(void) { int8_t x249 = INT8_MIN; static volatile int32_t x250 = INT32_MIN; volatile int32_t x251 = INT32_MIN; uint32_t x252 = 139932U; int32_t t62 = -13536516; t62 = ((x249|x250)+(x251!=x252)); if (t62 != -127) { NG(); } else { ; } } void f63(void) { int64_t x253 = INT64_MAX; volatile int32_t x254 = INT32_MIN; int64_t t63 = 238367999210547LL; t63 = ((x253|x254)+(x255!=x256)); if (t63 != 0LL) { NG(); } else { ; } } void f64(void) { uint8_t x257 = 53U; static int8_t x259 = -1; int64_t x260 = INT64_MAX; int32_t t64 = -6994; t64 = ((x257|x258)+(x259!=x260)); if (t64 != 0) { NG(); } else { ; } } void f65(void) { uint8_t x262 = 4U; static int64_t x263 = -1LL; uint64_t x264 = 224323100817176502LLU; volatile uint64_t t65 = 3194359851518734776LLU; t65 = ((x261|x262)+(x263!=x264)); if (t65 != 724897727254LLU) { NG(); } else { ; } } void f66(void) { uint16_t x265 = 13U; int8_t x266 = INT8_MAX; int16_t x267 = INT16_MAX; int16_t x268 = 8178; int32_t t66 = -6; t66 = ((x265|x266)+(x267!=x268)); if (t66 != 128) { NG(); } else { ; } } void f67(void) { int8_t x270 = -1; static uint64_t x271 = 6088148242236871LLU; volatile uint16_t x272 = 1341U; t67 = ((x269|x270)+(x271!=x272)); if (t67 != 0U) { NG(); } else { ; } } void f68(void) { uint16_t x273 = UINT16_MAX; uint16_t x274 = UINT16_MAX; volatile uint16_t x276 = 5371U; int32_t t68 = 148223531; t68 = ((x273|x274)+(x275!=x276)); if (t68 != 65536) { NG(); } else { ; } } void f69(void) { static int32_t x277 = INT32_MIN; int32_t x278 = INT32_MIN; volatile int16_t x280 = 1; volatile int32_t t69 = -76860238; t69 = ((x277|x278)+(x279!=x280)); if (t69 != -2147483647) { NG(); } else { ; } } void f70(void) { int64_t x282 = INT64_MAX; volatile int32_t x283 = INT32_MIN; uint32_t x284 = 81703857U; int64_t t70 = -15LL; t70 = ((x281|x282)+(x283!=x284)); if (t70 != 0LL) { NG(); } else { ; } } void f71(void) { uint32_t x286 = 11U; volatile int16_t x287 = INT16_MAX; volatile uint32_t t71 = 0U; t71 = ((x285|x286)+(x287!=x288)); if (t71 != 4294967280U) { NG(); } else { ; } } void f72(void) { int64_t x289 = INT64_MAX; int8_t x290 = INT8_MIN; static uint32_t x291 = 6101328U; volatile int64_t t72 = 3303LL; t72 = ((x289|x290)+(x291!=x292)); if (t72 != 0LL) { NG(); } else { ; } } void f73(void) { int64_t x293 = INT64_MIN; uint32_t x294 = 483936833U; volatile uint32_t x295 = UINT32_MAX; static uint8_t x296 = UINT8_MAX; int64_t t73 = 1LL; t73 = ((x293|x294)+(x295!=x296)); if (t73 != -9223372036370838974LL) { NG(); } else { ; } } void f74(void) { uint8_t x297 = UINT8_MAX; uint32_t x298 = 108U; static volatile int32_t x299 = -1; uint32_t t74 = 340791U; t74 = ((x297|x298)+(x299!=x300)); if (t74 != 256U) { NG(); } else { ; } } void f75(void) { static uint32_t x302 = 93701U; uint32_t x303 = UINT32_MAX; static int32_t x304 = -1; t75 = ((x301|x302)+(x303!=x304)); if (t75 != UINT32_MAX) { NG(); } else { ; } } void f76(void) { static int64_t x305 = 32590689026903799LL; static int8_t x306 = -1; volatile int16_t x308 = INT16_MIN; int64_t t76 = 108LL; t76 = ((x305|x306)+(x307!=x308)); if (t76 != 0LL) { NG(); } else { ; } } void f77(void) { int32_t x309 = INT32_MIN; static int8_t x311 = -1; volatile int32_t t77 = -104; t77 = ((x309|x310)+(x311!=x312)); if (t77 != 0) { NG(); } else { ; } } void f78(void) { volatile uint16_t x313 = UINT16_MAX; static int16_t x314 = -1; uint16_t x316 = 0U; int32_t t78 = -6252; t78 = ((x313|x314)+(x315!=x316)); if (t78 != 0) { NG(); } else { ; } } void f79(void) { static uint32_t x318 = UINT32_MAX; int32_t x320 = -1; int64_t t79 = 1LL; t79 = ((x317|x318)+(x319!=x320)); if (t79 != 4294967296LL) { NG(); } else { ; } } void f80(void) { volatile int16_t x321 = INT16_MIN; volatile uint64_t x322 = UINT64_MAX; volatile int16_t x323 = INT16_MAX; volatile uint64_t x324 = 146731183637LLU; static uint64_t t80 = 61755210172LLU; t80 = ((x321|x322)+(x323!=x324)); if (t80 != 0LLU) { NG(); } else { ; } } void f81(void) { int8_t x325 = -1; static volatile uint32_t x326 = 464U; volatile int64_t x327 = INT64_MAX; uint8_t x328 = 0U; volatile uint32_t t81 = 56770U; t81 = ((x325|x326)+(x327!=x328)); if (t81 != 0U) { NG(); } else { ; } } void f82(void) { int32_t x329 = INT32_MIN; int64_t x330 = -1LL; uint32_t x331 = 9540U; volatile int64_t t82 = 81LL; t82 = ((x329|x330)+(x331!=x332)); if (t82 != 0LL) { NG(); } else { ; } } void f83(void) { static uint16_t x333 = 28U; volatile uint32_t x334 = 7713U; int16_t x335 = -58; static uint64_t x336 = UINT64_MAX; t83 = ((x333|x334)+(x335!=x336)); if (t83 != 7742U) { NG(); } else { ; } } void f84(void) { static int16_t x337 = INT16_MIN; int64_t x338 = INT64_MAX; int64_t x340 = INT64_MIN; volatile int64_t t84 = 253225520091529LL; t84 = ((x337|x338)+(x339!=x340)); if (t84 != 0LL) { NG(); } else { ; } } void f85(void) { int8_t x341 = -1; int32_t x342 = -18857515; uint32_t x343 = UINT32_MAX; volatile uint16_t x344 = 5U; int32_t t85 = -203010; t85 = ((x341|x342)+(x343!=x344)); if (t85 != 0) { NG(); } else { ; } } void f86(void) { volatile int16_t x345 = -1; volatile int64_t x346 = INT64_MIN; static volatile int64_t t86 = 8053943786892LL; t86 = ((x345|x346)+(x347!=x348)); if (t86 != 0LL) { NG(); } else { ; } } void f87(void) { uint64_t x355 = 79979004840784LLU; int64_t x356 = INT64_MIN; int32_t t87 = -58; t87 = ((x353|x354)+(x355!=x356)); if (t87 != -1) { NG(); } else { ; } } void f88(void) { int64_t x358 = 238351989430870LL; uint32_t x359 = 3723315U; uint32_t x360 = 2790U; int64_t t88 = -6991633831022705LL; t88 = ((x357|x358)+(x359!=x360)); if (t88 != 238351989430871LL) { NG(); } else { ; } } void f89(void) { int16_t x361 = 396; volatile uint16_t x362 = 1102U; int64_t x363 = INT64_MIN; int32_t x364 = -223046; int32_t t89 = 409939396; t89 = ((x361|x362)+(x363!=x364)); if (t89 != 1487) { NG(); } else { ; } } void f90(void) { int8_t x365 = -1; uint8_t x366 = UINT8_MAX; volatile int64_t x368 = INT64_MAX; int32_t t90 = 79; t90 = ((x365|x366)+(x367!=x368)); if (t90 != 0) { NG(); } else { ; } } void f91(void) { uint8_t x369 = UINT8_MAX; uint32_t x370 = 16257U; int64_t x371 = INT64_MIN; static int64_t x372 = INT64_MIN; uint32_t t91 = 230U; t91 = ((x369|x370)+(x371!=x372)); if (t91 != 16383U) { NG(); } else { ; } } void f92(void) { int32_t x373 = -142584; int8_t x374 = INT8_MIN; uint32_t x375 = 1813U; int32_t t92 = -17; t92 = ((x373|x374)+(x375!=x376)); if (t92 != -119) { NG(); } else { ; } } void f93(void) { int8_t x377 = 0; static uint32_t x379 = 15439U; volatile int16_t x380 = -1; static volatile uint64_t t93 = 32915724571998738LLU; t93 = ((x377|x378)+(x379!=x380)); if (t93 != 0LLU) { NG(); } else { ; } } void f94(void) { int8_t x381 = INT8_MIN; int8_t x383 = INT8_MIN; t94 = ((x381|x382)+(x383!=x384)); if (t94 != -113) { NG(); } else { ; } } void f95(void) { volatile uint8_t x385 = 93U; static volatile int8_t x386 = INT8_MIN; int64_t x387 = 3405676606LL; int8_t x388 = 11; volatile int32_t t95 = 2244; t95 = ((x385|x386)+(x387!=x388)); if (t95 != -34) { NG(); } else { ; } } void f96(void) { volatile uint32_t x389 = 0U; int64_t x390 = INT64_MIN; static uint64_t x391 = 218666LLU; int16_t x392 = INT16_MIN; t96 = ((x389|x390)+(x391!=x392)); if (t96 != -9223372036854775807LL) { NG(); } else { ; } } void f97(void) { static int32_t x393 = INT32_MIN; int16_t x394 = 1; int64_t x396 = -1LL; volatile int32_t t97 = -275257; t97 = ((x393|x394)+(x395!=x396)); if (t97 != -2147483646) { NG(); } else { ; } } void f98(void) { int8_t x397 = INT8_MIN; volatile int8_t x398 = 23; uint64_t x400 = 4323680163867LLU; static int32_t t98 = 55; t98 = ((x397|x398)+(x399!=x400)); if (t98 != -104) { NG(); } else { ; } } void f99(void) { int32_t x403 = INT32_MAX; int32_t x404 = -1; static volatile int64_t t99 = -74936LL; t99 = ((x401|x402)+(x403!=x404)); if (t99 != -9223372036854775807LL) { NG(); } else { ; } } void f100(void) { uint8_t x405 = UINT8_MAX; uint64_t x406 = UINT64_MAX; int64_t x408 = INT64_MIN; static volatile uint64_t t100 = 2978857246170271LLU; t100 = ((x405|x406)+(x407!=x408)); if (t100 != 0LLU) { NG(); } else { ; } } void f101(void) { static uint32_t x410 = 1138753188U; int32_t x411 = INT32_MIN; uint8_t x412 = UINT8_MAX; volatile uint32_t t101 = 1393U; t101 = ((x409|x410)+(x411!=x412)); if (t101 != 3286236837U) { NG(); } else { ; } } void f102(void) { uint16_t x414 = 4U; int64_t x415 = -1LL; int64_t t102 = 211LL; t102 = ((x413|x414)+(x415!=x416)); if (t102 != -9223372036854775804LL) { NG(); } else { ; } } void f103(void) { int8_t x421 = INT8_MIN; int16_t x422 = -1; int16_t x423 = INT16_MIN; int16_t x424 = INT16_MIN; t103 = ((x421|x422)+(x423!=x424)); if (t103 != -1) { NG(); } else { ; } } void f104(void) { int8_t x425 = INT8_MAX; int8_t x426 = INT8_MIN; static int64_t x427 = INT64_MAX; uint64_t x428 = 130137427617994LLU; int32_t t104 = 26926; t104 = ((x425|x426)+(x427!=x428)); if (t104 != 0) { NG(); } else { ; } } void f105(void) { static uint16_t x429 = UINT16_MAX; static volatile int64_t x430 = 6LL; static int32_t x431 = INT32_MAX; static int64_t t105 = -1LL; t105 = ((x429|x430)+(x431!=x432)); if (t105 != 65536LL) { NG(); } else { ; } } void f106(void) { uint16_t x433 = UINT16_MAX; int8_t x434 = -1; uint32_t x435 = 241664U; static int8_t x436 = INT8_MAX; int32_t t106 = 4805723; t106 = ((x433|x434)+(x435!=x436)); if (t106 != 0) { NG(); } else { ; } } void f107(void) { uint32_t x437 = UINT32_MAX; uint8_t x438 = 17U; int32_t x440 = -1; volatile uint32_t t107 = 106U; t107 = ((x437|x438)+(x439!=x440)); if (t107 != 0U) { NG(); } else { ; } } void f108(void) { static uint32_t x441 = 35303081U; uint16_t x442 = 22103U; volatile uint8_t x443 = 47U; uint32_t t108 = 153816225U; t108 = ((x441|x442)+(x443!=x444)); if (t108 != 35323648U) { NG(); } else { ; } } void f109(void) { uint8_t x445 = UINT8_MAX; int8_t x446 = INT8_MIN; static uint8_t x447 = 35U; int32_t x448 = -115127; int32_t t109 = 44382; t109 = ((x445|x446)+(x447!=x448)); if (t109 != 0) { NG(); } else { ; } } void f110(void) { int16_t x449 = INT16_MIN; int32_t x450 = 1557709; uint64_t x451 = 4117324996883206LLU; volatile int32_t x452 = -1; int32_t t110 = 204; t110 = ((x449|x450)+(x451!=x452)); if (t110 != -15154) { NG(); } else { ; } } void f111(void) { volatile uint16_t x453 = UINT16_MAX; int64_t x455 = -1LL; volatile int32_t x456 = INT32_MAX; static volatile int64_t t111 = -1LL; t111 = ((x453|x454)+(x455!=x456)); if (t111 != 0LL) { NG(); } else { ; } } void f112(void) { volatile int8_t x458 = 1; static int16_t x459 = INT16_MIN; int32_t x460 = -3369; uint32_t t112 = 55414U; t112 = ((x457|x458)+(x459!=x460)); if (t112 != 66744U) { NG(); } else { ; } } void f113(void) { static int16_t x461 = -160; uint32_t x463 = 18934909U; int32_t t113 = 1110; t113 = ((x461|x462)+(x463!=x464)); if (t113 != -159) { NG(); } else { ; } } void f114(void) { int64_t x465 = 777965015481376710LL; volatile int64_t x467 = INT64_MAX; int8_t x468 = -1; t114 = ((x465|x466)+(x467!=x468)); if (t114 != 777965015481384960LL) { NG(); } else { ; } } void f115(void) { int32_t x469 = -1; static uint32_t x470 = 904U; int16_t x471 = -99; static int64_t x472 = -173223265547678LL; static volatile uint32_t t115 = 618021U; t115 = ((x469|x470)+(x471!=x472)); if (t115 != 0U) { NG(); } else { ; } } void f116(void) { static volatile uint32_t x473 = 6U; uint32_t x474 = UINT32_MAX; int32_t x475 = -866; static volatile uint32_t t116 = 6U; t116 = ((x473|x474)+(x475!=x476)); if (t116 != 0U) { NG(); } else { ; } } void f117(void) { volatile int16_t x477 = -1; int16_t x478 = 410; static int64_t x480 = INT64_MAX; int32_t t117 = 609007832; t117 = ((x477|x478)+(x479!=x480)); if (t117 != 0) { NG(); } else { ; } } void f118(void) { int16_t x486 = INT16_MIN; uint8_t x487 = 10U; uint64_t x488 = UINT64_MAX; t118 = ((x485|x486)+(x487!=x488)); if (t118 != 0U) { NG(); } else { ; } } void f119(void) { uint16_t x489 = 166U; int8_t x490 = 39; int8_t x491 = 3; uint8_t x492 = 101U; static int32_t t119 = -89475113; t119 = ((x489|x490)+(x491!=x492)); if (t119 != 168) { NG(); } else { ; } } void f120(void) { int32_t x493 = INT32_MIN; int8_t x494 = INT8_MAX; int8_t x495 = -4; int64_t x496 = 96997005LL; t120 = ((x493|x494)+(x495!=x496)); if (t120 != -2147483520) { NG(); } else { ; } } void f121(void) { uint32_t x497 = 742813U; uint16_t x498 = UINT16_MAX; int16_t x499 = INT16_MIN; uint8_t x500 = 62U; uint32_t t121 = 6411U; t121 = ((x497|x498)+(x499!=x500)); if (t121 != 786432U) { NG(); } else { ; } } void f122(void) { int32_t x503 = -4666480; int64_t x504 = INT64_MIN; t122 = ((x501|x502)+(x503!=x504)); if (t122 != 0) { NG(); } else { ; } } void f123(void) { static uint8_t x508 = 74U; volatile int32_t t123 = 3413; t123 = ((x505|x506)+(x507!=x508)); if (t123 != 0) { NG(); } else { ; } } void f124(void) { static int8_t x509 = -1; volatile int32_t x510 = 2; volatile int8_t x511 = INT8_MAX; volatile int32_t t124 = 294473; t124 = ((x509|x510)+(x511!=x512)); if (t124 != 0) { NG(); } else { ; } } void f125(void) { int32_t x513 = -1148; int64_t x514 = INT64_MIN; int16_t x515 = 504; uint64_t x516 = 24005840120782647LLU; t125 = ((x513|x514)+(x515!=x516)); if (t125 != -1147LL) { NG(); } else { ; } } void f126(void) { uint64_t x517 = 318271751688866LLU; static uint64_t x518 = 12428446940844383LLU; uint16_t x519 = UINT16_MAX; int8_t x520 = -1; static volatile uint64_t t126 = 46711508555LLU; t126 = ((x517|x518)+(x519!=x520)); if (t126 != 12710351996441600LLU) { NG(); } else { ; } } void f127(void) { uint64_t x521 = UINT64_MAX; static int32_t x522 = 253642; int16_t x523 = -1; uint8_t x524 = 6U; volatile uint64_t t127 = 4979225087684LLU; t127 = ((x521|x522)+(x523!=x524)); if (t127 != 0LLU) { NG(); } else { ; } } void f128(void) { volatile int32_t x525 = -71285; int8_t x527 = INT8_MIN; int64_t t128 = 1012321LL; t128 = ((x525|x526)+(x527!=x528)); if (t128 != 0LL) { NG(); } else { ; } } void f129(void) { static volatile int64_t x529 = -105351030431LL; int8_t x530 = -53; int64_t x531 = INT64_MIN; int8_t x532 = 1; int64_t t129 = 397606LL; t129 = ((x529|x530)+(x531!=x532)); if (t129 != -20LL) { NG(); } else { ; } } void f130(void) { int32_t x533 = -1; volatile int32_t x535 = INT32_MIN; volatile int8_t x536 = 14; static uint32_t t130 = 237U; t130 = ((x533|x534)+(x535!=x536)); if (t130 != 0U) { NG(); } else { ; } } void f131(void) { static int64_t x537 = -1LL; static int16_t x540 = -1; static int64_t t131 = 563258867641525789LL; t131 = ((x537|x538)+(x539!=x540)); if (t131 != 0LL) { NG(); } else { ; } } void f132(void) { int64_t x541 = -1LL; int32_t x543 = -81; static volatile uint64_t x544 = UINT64_MAX; int64_t t132 = -2469476714423110LL; t132 = ((x541|x542)+(x543!=x544)); if (t132 != 0LL) { NG(); } else { ; } } void f133(void) { volatile uint32_t x545 = 0U; int32_t x546 = 5; int64_t x548 = -1LL; static volatile uint32_t t133 = 126686U; t133 = ((x545|x546)+(x547!=x548)); if (t133 != 6U) { NG(); } else { ; } } void f134(void) { uint64_t x549 = UINT64_MAX; int16_t x550 = INT16_MAX; int16_t x552 = -1; volatile uint64_t t134 = 28160LLU; t134 = ((x549|x550)+(x551!=x552)); if (t134 != 0LLU) { NG(); } else { ; } } void f135(void) { static int8_t x553 = -1; volatile uint32_t x554 = UINT32_MAX; volatile int64_t x556 = INT64_MIN; static uint32_t t135 = 11260U; t135 = ((x553|x554)+(x555!=x556)); if (t135 != 0U) { NG(); } else { ; } } void f136(void) { volatile int64_t x558 = -5618719393LL; uint64_t x559 = 8679912508818424808LLU; int64_t x560 = -1LL; static volatile int64_t t136 = 1271384399240497028LL; t136 = ((x557|x558)+(x559!=x560)); if (t136 != -2688LL) { NG(); } else { ; } } void f137(void) { uint8_t x561 = 0U; static uint16_t x562 = 11378U; volatile uint32_t x563 = UINT32_MAX; int32_t t137 = 43081387; t137 = ((x561|x562)+(x563!=x564)); if (t137 != 11379) { NG(); } else { ; } } void f138(void) { uint64_t x565 = 7LLU; int16_t x566 = INT16_MAX; int32_t x568 = -5402; t138 = ((x565|x566)+(x567!=x568)); if (t138 != 32768LLU) { NG(); } else { ; } } void f139(void) { static int32_t x569 = 13490; int32_t x570 = INT32_MIN; int32_t x571 = 2305895; int64_t x572 = -10648948251425LL; volatile int32_t t139 = 0; t139 = ((x569|x570)+(x571!=x572)); if (t139 != -2147470157) { NG(); } else { ; } } void f140(void) { static int32_t x574 = -1; int64_t x575 = INT64_MIN; uint32_t x576 = 6950830U; t140 = ((x573|x574)+(x575!=x576)); if (t140 != 0) { NG(); } else { ; } } void f141(void) { int16_t x577 = -1; uint32_t x578 = 0U; volatile uint8_t x580 = 17U; volatile uint32_t t141 = 1U; t141 = ((x577|x578)+(x579!=x580)); if (t141 != 0U) { NG(); } else { ; } } void f142(void) { uint8_t x583 = UINT8_MAX; static volatile int64_t t142 = 1LL; t142 = ((x581|x582)+(x583!=x584)); if (t142 != 7727779773627615LL) { NG(); } else { ; } } void f143(void) { int32_t x585 = INT32_MAX; int64_t x586 = INT64_MIN; int64_t x587 = INT64_MIN; uint8_t x588 = 10U; int64_t t143 = -1119147692LL; t143 = ((x585|x586)+(x587!=x588)); if (t143 != -9223372034707292160LL) { NG(); } else { ; } } void f144(void) { static uint8_t x589 = 46U; int16_t x590 = INT16_MAX; int32_t x592 = 859; int32_t t144 = 3; t144 = ((x589|x590)+(x591!=x592)); if (t144 != 32768) { NG(); } else { ; } } void f145(void) { int32_t x593 = -1; int32_t x594 = INT32_MIN; static volatile int8_t x595 = -1; uint32_t x596 = UINT32_MAX; int32_t t145 = 0; t145 = ((x593|x594)+(x595!=x596)); if (t145 != -1) { NG(); } else { ; } } void f146(void) { int64_t x598 = -1LL; int64_t x599 = 929050527679672LL; static volatile int32_t x600 = INT32_MIN; volatile int64_t t146 = -9LL; t146 = ((x597|x598)+(x599!=x600)); if (t146 != 0LL) { NG(); } else { ; } } void f147(void) { uint16_t x601 = UINT16_MAX; int16_t x602 = INT16_MAX; int8_t x603 = INT8_MAX; int64_t x604 = -1LL; static volatile int32_t t147 = 139546; t147 = ((x601|x602)+(x603!=x604)); if (t147 != 65536) { NG(); } else { ; } } void f148(void) { uint32_t x606 = 34U; uint16_t x607 = 10292U; int16_t x608 = 1; uint32_t t148 = 5583U; t148 = ((x605|x606)+(x607!=x608)); if (t148 != 4294934563U) { NG(); } else { ; } } void f149(void) { volatile int64_t x609 = -1LL; int16_t x610 = INT16_MIN; int32_t x611 = INT32_MAX; int64_t t149 = 7158265564209LL; t149 = ((x609|x610)+(x611!=x612)); if (t149 != 0LL) { NG(); } else { ; } } void f150(void) { uint32_t x614 = 122664110U; uint8_t x615 = 1U; volatile uint32_t x616 = UINT32_MAX; t150 = ((x613|x614)+(x615!=x616)); if (t150 != 122664112U) { NG(); } else { ; } } void f151(void) { int32_t x617 = 714264821; int32_t x618 = -751410; int16_t x620 = INT16_MIN; static volatile int32_t t151 = 2368; t151 = ((x617|x618)+(x619!=x620)); if (t151 != -599808) { NG(); } else { ; } } void f152(void) { static uint64_t x621 = 6137016LLU; volatile uint64_t t152 = 1LLU; t152 = ((x621|x622)+(x623!=x624)); if (t152 != 6139069LLU) { NG(); } else { ; } } void f153(void) { int32_t x626 = INT32_MAX; volatile int32_t x627 = 21; static int64_t x628 = INT64_MIN; t153 = ((x625|x626)+(x627!=x628)); if (t153 != 4613703671656480768LLU) { NG(); } else { ; } } void f154(void) { int8_t x630 = INT8_MIN; int32_t x631 = INT32_MIN; volatile uint8_t x632 = 105U; t154 = ((x629|x630)+(x631!=x632)); if (t154 != -95LL) { NG(); } else { ; } } void f155(void) { static volatile int16_t x633 = INT16_MAX; static int64_t x634 = -1LL; uint64_t x635 = 33288686LLU; int8_t x636 = 6; volatile int64_t t155 = 2LL; t155 = ((x633|x634)+(x635!=x636)); if (t155 != 0LL) { NG(); } else { ; } } void f156(void) { static volatile uint32_t x641 = UINT32_MAX; int64_t x643 = INT64_MIN; int8_t x644 = -1; static uint32_t t156 = 1534548397U; t156 = ((x641|x642)+(x643!=x644)); if (t156 != 0U) { NG(); } else { ; } } void f157(void) { uint64_t x645 = UINT64_MAX; uint8_t x646 = UINT8_MAX; int8_t x647 = -52; uint8_t x648 = 6U; volatile uint64_t t157 = 27890988416LLU; t157 = ((x645|x646)+(x647!=x648)); if (t157 != 0LLU) { NG(); } else { ; } } void f158(void) { int64_t x650 = -264408896399LL; static int32_t x651 = -1; static volatile int8_t x652 = INT8_MIN; t158 = ((x649|x650)+(x651!=x652)); if (t158 != 0LL) { NG(); } else { ; } } void f159(void) { int64_t x653 = -4701884LL; int16_t x654 = -1; int8_t x655 = INT8_MAX; int16_t x656 = INT16_MIN; volatile int64_t t159 = 1LL; t159 = ((x653|x654)+(x655!=x656)); if (t159 != 0LL) { NG(); } else { ; } } void f160(void) { volatile uint64_t x657 = UINT64_MAX; static uint64_t x658 = 8235366685989260789LLU; int16_t x659 = INT16_MAX; int8_t x660 = INT8_MIN; volatile uint64_t t160 = 219687LLU; t160 = ((x657|x658)+(x659!=x660)); if (t160 != 0LLU) { NG(); } else { ; } } void f161(void) { static int32_t x661 = INT32_MAX; volatile uint64_t x662 = 3LLU; int64_t x664 = INT64_MIN; static uint64_t t161 = 12652859277LLU; t161 = ((x661|x662)+(x663!=x664)); if (t161 != 2147483648LLU) { NG(); } else { ; } } void f162(void) { static int64_t x669 = INT64_MIN; volatile uint16_t x670 = UINT16_MAX; volatile uint16_t x671 = UINT16_MAX; static volatile int64_t t162 = 261585235403174730LL; t162 = ((x669|x670)+(x671!=x672)); if (t162 != -9223372036854710272LL) { NG(); } else { ; } } void f163(void) { uint32_t x674 = UINT32_MAX; int32_t x675 = INT32_MIN; volatile int32_t x676 = -16207; static volatile uint32_t t163 = 108U; t163 = ((x673|x674)+(x675!=x676)); if (t163 != 0U) { NG(); } else { ; } } void f164(void) { static int8_t x677 = INT8_MAX; uint32_t x678 = UINT32_MAX; static int16_t x679 = INT16_MIN; volatile uint32_t t164 = 6U; t164 = ((x677|x678)+(x679!=x680)); if (t164 != 0U) { NG(); } else { ; } } void f165(void) { int64_t x681 = INT64_MAX; int64_t x682 = -1LL; int64_t x684 = -91606384346073LL; t165 = ((x681|x682)+(x683!=x684)); if (t165 != 0LL) { NG(); } else { ; } } void f166(void) { volatile int8_t x685 = -1; static uint64_t x686 = UINT64_MAX; int64_t x687 = -1LL; static int16_t x688 = -1; uint64_t t166 = UINT64_MAX; t166 = ((x685|x686)+(x687!=x688)); if (t166 != UINT64_MAX) { NG(); } else { ; } } void f167(void) { static int8_t x689 = -10; uint16_t x690 = UINT16_MAX; uint16_t x691 = 5U; uint64_t x692 = 45LLU; volatile int32_t t167 = -835; t167 = ((x689|x690)+(x691!=x692)); if (t167 != 0) { NG(); } else { ; } } void f168(void) { int16_t x693 = 0; uint32_t x694 = 471521977U; int64_t x695 = 1566107911046407LL; int32_t x696 = -1; uint32_t t168 = 3U; t168 = ((x693|x694)+(x695!=x696)); if (t168 != 471521978U) { NG(); } else { ; } } void f169(void) { uint32_t x697 = 3U; int32_t x698 = INT32_MIN; int64_t x700 = 6269094150LL; t169 = ((x697|x698)+(x699!=x700)); if (t169 != 2147483652U) { NG(); } else { ; } } void f170(void) { uint8_t x701 = UINT8_MAX; uint32_t x702 = 1328215U; volatile int32_t x703 = -1; int64_t x704 = -1LL; volatile uint32_t t170 = 3987453U; t170 = ((x701|x702)+(x703!=x704)); if (t170 != 1328383U) { NG(); } else { ; } } void f171(void) { volatile int32_t x705 = 217; uint8_t x706 = 114U; uint16_t x708 = 115U; static int32_t t171 = 60; t171 = ((x705|x706)+(x707!=x708)); if (t171 != 252) { NG(); } else { ; } } void f172(void) { uint8_t x711 = 1U; static volatile uint64_t x712 = UINT64_MAX; volatile uint64_t t172 = 1LLU; t172 = ((x709|x710)+(x711!=x712)); if (t172 != 0LLU) { NG(); } else { ; } } void f173(void) { static volatile int8_t x713 = INT8_MIN; volatile uint16_t x715 = 20729U; static int64_t x716 = INT64_MIN; int32_t t173 = -826440074; t173 = ((x713|x714)+(x715!=x716)); if (t173 != -127) { NG(); } else { ; } } void f174(void) { uint16_t x717 = 74U; int32_t x718 = 10; int16_t x720 = INT16_MIN; int32_t t174 = -1; t174 = ((x717|x718)+(x719!=x720)); if (t174 != 75) { NG(); } else { ; } } void f175(void) { int32_t x721 = -1; volatile uint64_t x722 = 25109LLU; int8_t x723 = -59; uint8_t x724 = 1U; static volatile uint64_t t175 = 3LLU; t175 = ((x721|x722)+(x723!=x724)); if (t175 != 0LLU) { NG(); } else { ; } } void f176(void) { static int16_t x725 = INT16_MAX; int64_t x727 = INT64_MAX; int64_t x728 = -1778561LL; static volatile int32_t t176 = 110; t176 = ((x725|x726)+(x727!=x728)); if (t176 != 0) { NG(); } else { ; } } void f177(void) { int32_t x729 = INT32_MAX; static int64_t x730 = -1071124010537LL; int16_t x731 = 9; int64_t x732 = -1LL; int64_t t177 = 14LL; t177 = ((x729|x730)+(x731!=x732)); if (t177 != -1069446856704LL) { NG(); } else { ; } } void f178(void) { int64_t x733 = -3LL; static volatile int64_t x735 = INT64_MIN; uint64_t x736 = 124178309511LLU; static int64_t t178 = -1LL; t178 = ((x733|x734)+(x735!=x736)); if (t178 != 0LL) { NG(); } else { ; } } void f179(void) { int16_t x737 = 437; int32_t x738 = -4; int64_t x740 = -1LL; volatile int32_t t179 = 1498458; t179 = ((x737|x738)+(x739!=x740)); if (t179 != -2) { NG(); } else { ; } } void f180(void) { volatile int32_t t180 = -736909; t180 = ((x741|x742)+(x743!=x744)); if (t180 != 0) { NG(); } else { ; } } void f181(void) { static int64_t x745 = 274931239676695LL; uint32_t x746 = 95U; static int8_t x747 = -1; uint16_t x748 = 8U; int64_t t181 = -586596699LL; t181 = ((x745|x746)+(x747!=x748)); if (t181 != 274931239676768LL) { NG(); } else { ; } } void f182(void) { int16_t x749 = INT16_MIN; static uint32_t x750 = UINT32_MAX; int64_t x751 = INT64_MIN; volatile int32_t x752 = 1; volatile uint32_t t182 = 770U; t182 = ((x749|x750)+(x751!=x752)); if (t182 != 0U) { NG(); } else { ; } } void f183(void) { int16_t x753 = INT16_MIN; int64_t x754 = INT64_MAX; uint8_t x755 = 0U; static int32_t x756 = INT32_MIN; int64_t t183 = 16979845081218LL; t183 = ((x753|x754)+(x755!=x756)); if (t183 != 0LL) { NG(); } else { ; } } void f184(void) { static int64_t x757 = INT64_MIN; uint8_t x758 = UINT8_MAX; int8_t x759 = INT8_MIN; static int32_t x760 = 1827933; volatile int64_t t184 = 2353980889LL; t184 = ((x757|x758)+(x759!=x760)); if (t184 != -9223372036854775552LL) { NG(); } else { ; } } void f185(void) { int8_t x761 = 16; volatile int64_t x762 = -24863672LL; int8_t x763 = INT8_MIN; int64_t x764 = INT64_MAX; int64_t t185 = 3LL; t185 = ((x761|x762)+(x763!=x764)); if (t185 != -24863655LL) { NG(); } else { ; } } void f186(void) { uint16_t x765 = 1U; int16_t x766 = -3; uint64_t x767 = UINT64_MAX; int32_t t186 = -2904; t186 = ((x765|x766)+(x767!=x768)); if (t186 != -2) { NG(); } else { ; } } void f187(void) { int32_t x769 = -51; int32_t x771 = 0; uint16_t x772 = 140U; t187 = ((x769|x770)+(x771!=x772)); if (t187 != -50) { NG(); } else { ; } } void f188(void) { static int64_t x775 = -3405LL; static int32_t t188 = -16649; t188 = ((x773|x774)+(x775!=x776)); if (t188 != 0) { NG(); } else { ; } } void f189(void) { int8_t x777 = 6; int16_t x778 = INT16_MAX; static int16_t x779 = INT16_MIN; int8_t x780 = 4; volatile int32_t t189 = -1; t189 = ((x777|x778)+(x779!=x780)); if (t189 != 32768) { NG(); } else { ; } } void f190(void) { volatile uint16_t x781 = 119U; static uint8_t x782 = 0U; int8_t x783 = INT8_MAX; volatile int32_t t190 = 760373; t190 = ((x781|x782)+(x783!=x784)); if (t190 != 120) { NG(); } else { ; } } void f191(void) { int64_t x786 = -1LL; static int32_t x787 = 230539; volatile int16_t x788 = -1; volatile int64_t t191 = 32628403617LL; t191 = ((x785|x786)+(x787!=x788)); if (t191 != 0LL) { NG(); } else { ; } } void f192(void) { int8_t x789 = INT8_MIN; int8_t x790 = INT8_MIN; static uint32_t x791 = 702639U; volatile int32_t t192 = 0; t192 = ((x789|x790)+(x791!=x792)); if (t192 != -127) { NG(); } else { ; } } void f193(void) { static int64_t x794 = INT64_MIN; int32_t x795 = 471; int8_t x796 = -19; volatile int64_t t193 = -2111351LL; t193 = ((x793|x794)+(x795!=x796)); if (t193 != -9223372034707292160LL) { NG(); } else { ; } } void f194(void) { static int32_t x799 = 653700; int32_t x800 = 1; int64_t t194 = -144119318321LL; t194 = ((x797|x798)+(x799!=x800)); if (t194 != 0LL) { NG(); } else { ; } } void f195(void) { uint8_t x801 = 5U; int16_t x802 = -1; int16_t x803 = INT16_MAX; uint64_t x804 = 27382LLU; static volatile int32_t t195 = -666; t195 = ((x801|x802)+(x803!=x804)); if (t195 != 0) { NG(); } else { ; } } void f196(void) { int8_t x805 = 1; uint64_t x806 = UINT64_MAX; int32_t x808 = 614737; volatile uint64_t t196 = 31295333063201477LLU; t196 = ((x805|x806)+(x807!=x808)); if (t196 != 0LLU) { NG(); } else { ; } } void f197(void) { int64_t x809 = INT64_MAX; int64_t x810 = -1LL; static uint32_t x811 = 65U; t197 = ((x809|x810)+(x811!=x812)); if (t197 != 0LL) { NG(); } else { ; } } void f198(void) { static volatile int16_t x813 = INT16_MAX; int8_t x814 = -1; uint16_t x816 = 1U; int32_t t198 = 3513049; t198 = ((x813|x814)+(x815!=x816)); if (t198 != 0) { NG(); } else { ; } } void f199(void) { uint8_t x817 = 6U; volatile int32_t x818 = -58683255; int16_t x819 = INT16_MIN; static volatile int16_t x820 = INT16_MAX; t199 = ((x817|x818)+(x819!=x820)); if (t199 != -58683248) { NG(); } else { ; } } int main(void) { f0(); f1(); f2(); f3(); f4(); f5(); f6(); f7(); f8(); f9(); f10(); f11(); f12(); f13(); f14(); f15(); f16(); f17(); f18(); f19(); f20(); f21(); f22(); f23(); f24(); f25(); f26(); f27(); f28(); f29(); f30(); f31(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
410293.c
// 2 september 2015 #include <stdio.h> #include <string.h> #include "../../ui.h" // TODOs // - rename variables in main() // - make both columns the same size? static uiWindow *mainwin; static int onClosing(uiWindow *w, void *data) { uiControlDestroy(uiControl(mainwin)); uiQuit(); return 0; } static int shouldQuit(void *data) { uiControlDestroy(uiControl(mainwin)); return 1; } static void openClicked(uiMenuItem *item, uiWindow *w, void *data) { char *filename; filename = uiOpenFile(mainwin); if (filename == NULL) { uiMsgBoxError(mainwin, "No file selected", "Don't be alarmed!"); return; } uiMsgBox(mainwin, "File selected", filename); uiFreeText(filename); } static void saveClicked(uiMenuItem *item, uiWindow *w, void *data) { char *filename; filename = uiSaveFile(mainwin); if (filename == NULL) { uiMsgBoxError(mainwin, "No file selected", "Don't be alarmed!"); return; } uiMsgBox(mainwin, "File selected (don't worry, it's still there)", filename); uiFreeText(filename); } static uiSpinbox *spinbox; static uiSlider *slider; static uiProgressBar *progressbar; static void update(intmax_t value) { uiSpinboxSetValue(spinbox, value); uiSliderSetValue(slider, value); uiProgressBarSetValue(progressbar, value); } static void onSpinboxChanged(uiSpinbox *s, void *data) { update(uiSpinboxValue(spinbox)); } static void onSliderChanged(uiSlider *s, void *data) { update(uiSliderValue(slider)); } int main(void) { uiInitOptions o; const char *err; uiMenu *menu; uiMenuItem *item; uiBox *box; uiBox *hbox; uiGroup *group; uiBox *inner; uiBox *inner2; uiEntry *entry; uiCombobox *cbox; uiRadioButtons *rb; uiTab *tab; memset(&o, 0, sizeof (uiInitOptions)); err = uiInit(&o); if (err != NULL) { fprintf(stderr, "error initializing ui: %s\n", err); uiFreeInitError(err); return 1; } menu = uiNewMenu("File"); item = uiMenuAppendItem(menu, "Open"); uiMenuItemOnClicked(item, openClicked, NULL); item = uiMenuAppendItem(menu, "Save"); uiMenuItemOnClicked(item, saveClicked, NULL); item = uiMenuAppendQuitItem(menu); uiOnShouldQuit(shouldQuit, NULL); menu = uiNewMenu("Edit"); item = uiMenuAppendCheckItem(menu, "Checkable Item"); uiMenuAppendSeparator(menu); item = uiMenuAppendItem(menu, "Disabled Item"); uiMenuItemDisable(item); item = uiMenuAppendPreferencesItem(menu); menu = uiNewMenu("Help"); item = uiMenuAppendItem(menu, "Help"); item = uiMenuAppendAboutItem(menu); mainwin = uiNewWindow("libui Control Gallery", 640, 480, 1); uiWindowSetMargined(mainwin, 1); uiWindowOnClosing(mainwin, onClosing, NULL); box = uiNewVerticalBox(); uiBoxSetPadded(box, 1); uiWindowSetChild(mainwin, uiControl(box)); hbox = uiNewHorizontalBox(); uiBoxSetPadded(hbox, 1); uiBoxAppend(box, uiControl(hbox), 1); group = uiNewGroup("Basic Controls"); uiGroupSetMargined(group, 1); uiBoxAppend(hbox, uiControl(group), 0); inner = uiNewVerticalBox(); uiBoxSetPadded(inner, 1); uiGroupSetChild(group, uiControl(inner)); uiBoxAppend(inner, uiControl(uiNewButton("Button")), 0); uiBoxAppend(inner, uiControl(uiNewCheckbox("Checkbox")), 0); entry = uiNewEntry(); uiEntrySetText(entry, "Entry"); uiBoxAppend(inner, uiControl(entry), 0); uiBoxAppend(inner, uiControl(uiNewLabel("Label")), 0); uiBoxAppend(inner, uiControl(uiNewHorizontalSeparator()), 0); uiBoxAppend(inner, uiControl(uiNewDatePicker()), 0); uiBoxAppend(inner, uiControl(uiNewTimePicker()), 0); uiBoxAppend(inner, uiControl(uiNewDateTimePicker()), 0); uiBoxAppend(inner, uiControl(uiNewFontButton()), 0); uiBoxAppend(inner, uiControl(uiNewColorButton()), 0); inner2 = uiNewVerticalBox(); uiBoxSetPadded(inner2, 1); uiBoxAppend(hbox, uiControl(inner2), 1); group = uiNewGroup("Numbers"); uiGroupSetMargined(group, 1); uiBoxAppend(inner2, uiControl(group), 0); inner = uiNewVerticalBox(); uiBoxSetPadded(inner, 1); uiGroupSetChild(group, uiControl(inner)); spinbox = uiNewSpinbox(0, 100); uiSpinboxOnChanged(spinbox, onSpinboxChanged, NULL); uiBoxAppend(inner, uiControl(spinbox), 0); slider = uiNewSlider(0, 100); uiSliderOnChanged(slider, onSliderChanged, NULL); uiBoxAppend(inner, uiControl(slider), 0); progressbar = uiNewProgressBar(); uiBoxAppend(inner, uiControl(progressbar), 0); group = uiNewGroup("Lists"); uiGroupSetMargined(group, 1); uiBoxAppend(inner2, uiControl(group), 0); inner = uiNewVerticalBox(); uiBoxSetPadded(inner, 1); uiGroupSetChild(group, uiControl(inner)); cbox = uiNewCombobox(); uiComboboxAppend(cbox, "Combobox Item 1"); uiComboboxAppend(cbox, "Combobox Item 2"); uiComboboxAppend(cbox, "Combobox Item 3"); uiBoxAppend(inner, uiControl(cbox), 0); cbox = uiNewEditableCombobox(); uiComboboxAppend(cbox, "Editable Item 1"); uiComboboxAppend(cbox, "Editable Item 2"); uiComboboxAppend(cbox, "Editable Item 3"); uiBoxAppend(inner, uiControl(cbox), 0); rb = uiNewRadioButtons(); uiRadioButtonsAppend(rb, "Radio Button 1"); uiRadioButtonsAppend(rb, "Radio Button 2"); uiRadioButtonsAppend(rb, "Radio Button 3"); uiBoxAppend(inner, uiControl(rb), 1); tab = uiNewTab(); uiTabAppend(tab, "Page 1", uiControl(uiNewHorizontalBox())); uiTabAppend(tab, "Page 2", uiControl(uiNewHorizontalBox())); uiTabAppend(tab, "Page 3", uiControl(uiNewHorizontalBox())); uiBoxAppend(inner2, uiControl(tab), 1); uiControlShow(uiControl(mainwin)); uiMain(); uiUninit(); return 0; }
111946.c
/**************************************************************************** * * Copyright (C) 2012 PX4 Development Team. All rights reserved. * Author: Lorenz Meier <[email protected]> * * 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 PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file ardrone_motor_control.c * Implementation of AR.Drone 1.0 / 2.0 motor control interface */ #include <nuttx/config.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <drivers/drv_gpio.h> #include <drivers/drv_hrt.h> #include <uORB/uORB.h> #include <uORB/topics/actuator_outputs.h> #include <systemlib/err.h> #include "ardrone_motor_control.h" static unsigned long motor_gpios = GPIO_EXT_1 | GPIO_EXT_2 | GPIO_MULTI_1 | GPIO_MULTI_2; static unsigned long motor_gpio[4] = { GPIO_EXT_1, GPIO_EXT_2, GPIO_MULTI_1, GPIO_MULTI_2 }; typedef union { uint16_t motor_value; uint8_t bytes[2]; } motor_union_t; #define UART_TRANSFER_TIME_BYTE_US (9+50) /**< 9 us per byte at 115200k plus overhead */ /** * @brief Generate the 8-byte motor set packet * * @return the number of bytes (8) */ void ar_get_motor_packet(uint8_t *motor_buf, uint16_t motor1, uint16_t motor2, uint16_t motor3, uint16_t motor4) { motor_buf[0] = 0x20; motor_buf[1] = 0x00; motor_buf[2] = 0x00; motor_buf[3] = 0x00; motor_buf[4] = 0x00; /* * {0x20, 0x00, 0x00, 0x00, 0x00}; * 0x20 is start sign / motor command */ motor_union_t curr_motor; uint16_t nineBitMask = 0x1FF; /* Set motor 1 */ curr_motor.motor_value = (motor1 & nineBitMask) << 4; motor_buf[0] |= curr_motor.bytes[1]; motor_buf[1] |= curr_motor.bytes[0]; /* Set motor 2 */ curr_motor.motor_value = (motor2 & nineBitMask) << 3; motor_buf[1] |= curr_motor.bytes[1]; motor_buf[2] |= curr_motor.bytes[0]; /* Set motor 3 */ curr_motor.motor_value = (motor3 & nineBitMask) << 2; motor_buf[2] |= curr_motor.bytes[1]; motor_buf[3] |= curr_motor.bytes[0]; /* Set motor 4 */ curr_motor.motor_value = (motor4 & nineBitMask) << 1; motor_buf[3] |= curr_motor.bytes[1]; motor_buf[4] |= curr_motor.bytes[0]; } void ar_enable_broadcast(int fd) { ar_select_motor(fd, 0); } int ar_multiplexing_init() { int fd; fd = open(PX4FMU_DEVICE_PATH, 0); if (fd < 0) { warn("GPIO: open fail"); return fd; } /* deactivate all outputs */ if (ioctl(fd, GPIO_SET, motor_gpios)) { warn("GPIO: clearing pins fail"); close(fd); return -1; } /* configure all motor select GPIOs as outputs */ if (ioctl(fd, GPIO_SET_OUTPUT, motor_gpios) != 0) { warn("GPIO: output set fail"); close(fd); return -1; } return fd; } int ar_multiplexing_deinit(int fd) { if (fd < 0) { printf("GPIO: no valid descriptor\n"); return fd; } int ret = 0; /* deselect motor 1-4 */ ret += ioctl(fd, GPIO_SET, motor_gpios); if (ret != 0) { printf("GPIO: clear failed %d times\n", ret); } if (ioctl(fd, GPIO_SET_INPUT, motor_gpios) != 0) { printf("GPIO: input set fail\n"); return -1; } close(fd); return ret; } int ar_select_motor(int fd, uint8_t motor) { int ret = 0; /* * Four GPIOS: * GPIO_EXT1 * GPIO_EXT2 * GPIO_UART2_CTS * GPIO_UART2_RTS */ /* select motor 0 to enable broadcast */ if (motor == 0) { /* select motor 1-4 */ ret += ioctl(fd, GPIO_CLEAR, motor_gpios); } else { /* select reqested motor */ ret += ioctl(fd, GPIO_CLEAR, motor_gpio[motor - 1]); } return ret; } int ar_deselect_motor(int fd, uint8_t motor) { int ret = 0; /* * Four GPIOS: * GPIO_EXT1 * GPIO_EXT2 * GPIO_UART2_CTS * GPIO_UART2_RTS */ if (motor == 0) { /* deselect motor 1-4 */ ret += ioctl(fd, GPIO_SET, motor_gpios); } else { /* deselect reqested motor */ ret = ioctl(fd, GPIO_SET, motor_gpio[motor - 1]); } return ret; } int ar_init_motors(int ardrone_uart, int gpios) { /* Write ARDrone commands on UART2 */ uint8_t initbuf[] = {0xE0, 0x91, 0xA1, 0x00, 0x40}; uint8_t multicastbuf[] = {0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0}; /* deselect all motors */ ar_deselect_motor(gpios, 0); /* initialize all motors * - select one motor at a time * - configure motor */ int i; int errcounter = 0; /* initial setup run */ for (i = 1; i < 5; ++i) { /* Initialize motors 1-4 */ errcounter += ar_select_motor(gpios, i); usleep(200); /* * write 0xE0 - request status * receive one status byte */ write(ardrone_uart, &(initbuf[0]), 1); fsync(ardrone_uart); usleep(UART_TRANSFER_TIME_BYTE_US*1); /* * write 0x91 - request checksum * receive 120 status bytes */ write(ardrone_uart, &(initbuf[1]), 1); fsync(ardrone_uart); usleep(UART_TRANSFER_TIME_BYTE_US*120); /* * write 0xA1 - set status OK * receive one status byte - should be A0 * to confirm status is OK */ write(ardrone_uart, &(initbuf[2]), 1); fsync(ardrone_uart); usleep(UART_TRANSFER_TIME_BYTE_US*1); /* * set as motor i, where i = 1..4 * receive nothing */ initbuf[3] = (uint8_t)i; write(ardrone_uart, &(initbuf[3]), 1); fsync(ardrone_uart); /* * write 0x40 - check version * receive 11 bytes encoding the version */ write(ardrone_uart, &(initbuf[4]), 1); fsync(ardrone_uart); usleep(UART_TRANSFER_TIME_BYTE_US*11); ar_deselect_motor(gpios, i); /* sleep 200 ms */ usleep(200000); } /* start the multicast part */ errcounter += ar_select_motor(gpios, 0); usleep(200); /* * first round * write six times A0 - enable broadcast * receive nothing */ write(ardrone_uart, multicastbuf, sizeof(multicastbuf)); fsync(ardrone_uart); usleep(UART_TRANSFER_TIME_BYTE_US * sizeof(multicastbuf)); /* * second round * write six times A0 - enable broadcast * receive nothing */ write(ardrone_uart, multicastbuf, sizeof(multicastbuf)); fsync(ardrone_uart); usleep(UART_TRANSFER_TIME_BYTE_US * sizeof(multicastbuf)); /* set motors to zero speed (fsync is part of the write command */ ardrone_write_motor_commands(ardrone_uart, 0, 0, 0, 0); if (errcounter != 0) { fprintf(stderr, "[ardrone_interface] init sequence incomplete, failed %d times", -errcounter); fflush(stdout); } return errcounter; } /** * Sets the leds on the motor controllers, 1 turns led on, 0 off. */ void ar_set_leds(int ardrone_uart, uint8_t led1_red, uint8_t led1_green, uint8_t led2_red, uint8_t led2_green, uint8_t led3_red, uint8_t led3_green, uint8_t led4_red, uint8_t led4_green) { /* * 2 bytes are sent. The first 3 bits describe the command: 011 means led control * the following 4 bits are the red leds for motor 4, 3, 2, 1 * then 4 bits with unknown function, then 4 bits for green leds for motor 4, 3, 2, 1 * the last bit is unknown. * * The packet is therefore: * 011 rrrr 0000 gggg 0 */ uint8_t leds[2]; leds[0] = 0x60 | ((led4_red & 0x01) << 4) | ((led3_red & 0x01) << 3) | ((led2_red & 0x01) << 2) | ((led1_red & 0x01) << 1); leds[1] = ((led4_green & 0x01) << 4) | ((led3_green & 0x01) << 3) | ((led2_green & 0x01) << 2) | ((led1_green & 0x01) << 1); write(ardrone_uart, leds, 2); } int ardrone_write_motor_commands(int ardrone_fd, uint16_t motor1, uint16_t motor2, uint16_t motor3, uint16_t motor4) { const unsigned int min_motor_interval = 4900; static uint64_t last_motor_time = 0; static struct actuator_outputs_s outputs; outputs.timestamp = hrt_absolute_time(); outputs.output[0] = motor1; outputs.output[1] = motor2; outputs.output[2] = motor3; outputs.output[3] = motor4; static orb_advert_t pub = 0; if (pub == 0) { pub = orb_advertise(ORB_ID_VEHICLE_CONTROLS, &outputs); } if (hrt_absolute_time() - last_motor_time > min_motor_interval) { uint8_t buf[5] = {0}; ar_get_motor_packet(buf, motor1, motor2, motor3, motor4); int ret; ret = write(ardrone_fd, buf, sizeof(buf)); fsync(ardrone_fd); /* publish just written values */ orb_publish(ORB_ID_VEHICLE_CONTROLS, pub, &outputs); if (ret == sizeof(buf)) { return OK; } else { return ret; } } else { return -ERROR; } } void ardrone_mixing_and_output(int ardrone_write, const struct actuator_controls_s *actuators) { float roll_control = actuators->control[0]; float pitch_control = actuators->control[1]; float yaw_control = actuators->control[2]; float motor_thrust = actuators->control[3]; const float min_thrust = 0.02f; /**< 2% minimum thrust */ const float max_thrust = 1.0f; /**< 100% max thrust */ const float scaling = 510.0f; /**< 100% thrust equals a value of 510 which works, 512 leads to cutoff */ const float min_gas = min_thrust * scaling; /**< value range sent to motors, minimum */ const float max_gas = max_thrust * scaling; /**< value range sent to motors, maximum */ /* initialize all fields to zero */ uint16_t motor_pwm[4] = {0}; float motor_calc[4] = {0}; float output_band = 0.0f; const float startpoint_full_control = 0.25f; /**< start full control at 25% thrust */ /* linearly scale the control inputs from 0 to startpoint_full_control */ if (motor_thrust < startpoint_full_control) { output_band = motor_thrust/startpoint_full_control; // linear from 0 to 1 } else { output_band = 1.0f; } roll_control *= output_band; pitch_control *= output_band; yaw_control *= output_band; //add the yaw, nick and roll components to the basic thrust //TODO:this should be done by the mixer // FRONT (MOTOR 1) motor_calc[0] = motor_thrust + (roll_control / 2 + pitch_control / 2 - yaw_control); // RIGHT (MOTOR 2) motor_calc[1] = motor_thrust + (-roll_control / 2 + pitch_control / 2 + yaw_control); // BACK (MOTOR 3) motor_calc[2] = motor_thrust + (-roll_control / 2 - pitch_control / 2 - yaw_control); // LEFT (MOTOR 4) motor_calc[3] = motor_thrust + (roll_control / 2 - pitch_control / 2 + yaw_control); /* if one motor is saturated, reduce throttle */ float saturation = fmaxf(fmaxf(motor_calc[0], motor_calc[1]),fmaxf(motor_calc[2], motor_calc[3])) - max_thrust; if (saturation > 0.0f) { /* reduce the motor thrust according to the saturation */ motor_thrust = motor_thrust - saturation; // FRONT (MOTOR 1) motor_calc[0] = motor_thrust + (roll_control / 2 + pitch_control / 2 - yaw_control); // RIGHT (MOTOR 2) motor_calc[1] = motor_thrust + (-roll_control / 2 + pitch_control / 2 + yaw_control); // BACK (MOTOR 3) motor_calc[2] = motor_thrust + (-roll_control / 2 - pitch_control / 2 - yaw_control); // LEFT (MOTOR 4) motor_calc[3] = motor_thrust + (roll_control / 2 - pitch_control / 2 + yaw_control); } /* set the motor values */ /* scale up from 0..1 to 10..500) */ motor_pwm[0] = (uint16_t) (motor_calc[0] * ((float)max_gas - min_gas) + min_gas); motor_pwm[1] = (uint16_t) (motor_calc[1] * ((float)max_gas - min_gas) + min_gas); motor_pwm[2] = (uint16_t) (motor_calc[2] * ((float)max_gas - min_gas) + min_gas); motor_pwm[3] = (uint16_t) (motor_calc[3] * ((float)max_gas - min_gas) + min_gas); /* scale up from 0..1 to 10..500) */ motor_pwm[0] = (uint16_t) (motor_calc[0] * (float)((max_gas - min_gas) + min_gas)); motor_pwm[1] = (uint16_t) (motor_calc[1] * (float)((max_gas - min_gas) + min_gas)); motor_pwm[2] = (uint16_t) (motor_calc[2] * (float)((max_gas - min_gas) + min_gas)); motor_pwm[3] = (uint16_t) (motor_calc[3] * (float)((max_gas - min_gas) + min_gas)); /* Failsafe logic for min values - should never be necessary */ motor_pwm[0] = (motor_pwm[0] > 0) ? motor_pwm[0] : min_gas; motor_pwm[1] = (motor_pwm[1] > 0) ? motor_pwm[1] : min_gas; motor_pwm[2] = (motor_pwm[2] > 0) ? motor_pwm[2] : min_gas; motor_pwm[3] = (motor_pwm[3] > 0) ? motor_pwm[3] : min_gas; /* Failsafe logic for max values - should never be necessary */ motor_pwm[0] = (motor_pwm[0] <= max_gas) ? motor_pwm[0] : max_gas; motor_pwm[1] = (motor_pwm[1] <= max_gas) ? motor_pwm[1] : max_gas; motor_pwm[2] = (motor_pwm[2] <= max_gas) ? motor_pwm[2] : max_gas; motor_pwm[3] = (motor_pwm[3] <= max_gas) ? motor_pwm[3] : max_gas; /* send motors via UART */ ardrone_write_motor_commands(ardrone_write, motor_pwm[0], motor_pwm[1], motor_pwm[2], motor_pwm[3]); }
964025.c
// autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <endian.h> #include <fcntl.h> #include <net/if.h> #include <netinet/in.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <linux/genetlink.h> #include <linux/if_addr.h> #include <linux/if_link.h> #include <linux/in6.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/veth.h> struct nlmsg { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; }; static struct nlmsg nlmsg; static void netlink_init(struct nlmsg* nlmsg, int typ, int flags, const void* data, int size) { memset(nlmsg, 0, sizeof(*nlmsg)); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_type = typ; hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; memcpy(hdr + 1, data, size); nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size); } static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data, int size) { struct nlattr* attr = (struct nlattr*)nlmsg->pos; attr->nla_len = sizeof(*attr) + size; attr->nla_type = typ; memcpy(attr + 1, data, size); nlmsg->pos += NLMSG_ALIGN(attr->nla_len); } static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type, int* reply_len) { if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting) exit(1); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_len = nlmsg->pos - nlmsg->buf; struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != hdr->nlmsg_len) exit(1); n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); if (hdr->nlmsg_type == NLMSG_DONE) { *reply_len = 0; return 0; } if (n < sizeof(struct nlmsghdr)) exit(1); if (reply_len && hdr->nlmsg_type == reply_type) { *reply_len = n; return 0; } if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static int netlink_send(struct nlmsg* nlmsg, int sock) { return netlink_send_ext(nlmsg, sock, 0, NULL); } static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset, unsigned int total_len) { struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset); if (offset == total_len || offset + hdr->nlmsg_len > total_len) return -1; return hdr->nlmsg_len; } static void netlink_device_change(struct nlmsg* nlmsg, int sock, const char* name, bool up, const char* master, const void* mac, int macsize, const char* new_name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; hdr.ifi_index = if_nametoindex(name); netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr)); if (new_name) netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize); int err = netlink_send(nlmsg, sock); (void)err; } const int kInitNetNsFd = 239; #define DEVLINK_FAMILY_NAME "devlink" #define DEVLINK_CMD_PORT_GET 5 #define DEVLINK_CMD_RELOAD 37 #define DEVLINK_ATTR_BUS_NAME 1 #define DEVLINK_ATTR_DEV_NAME 2 #define DEVLINK_ATTR_NETDEV_NAME 7 #define DEVLINK_ATTR_NETNS_FD 138 static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock) { struct genlmsghdr genlhdr; struct nlattr* attr; int err, n; uint16_t id = 0; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = CTRL_CMD_GETFAMILY; netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME, strlen(DEVLINK_FAMILY_NAME) + 1); err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg->buf + n; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == CTRL_ATTR_FAMILY_ID) { id = *(uint16_t*)(attr + 1); break; } } if (!id) { return -1; } recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */ return id; } static void netlink_devlink_netns_move(const char* bus_name, const char* dev_name, int netns_fd) { struct genlmsghdr genlhdr; int sock; int id, err; sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) exit(1); id = netlink_devlink_id_get(&nlmsg, sock); if (id == -1) goto error; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = DEVLINK_CMD_RELOAD; netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_NETNS_FD, &netns_fd, sizeof(netns_fd)); err = netlink_send(&nlmsg, sock); if (err) { } error: close(sock); } static struct nlmsg nlmsg2; static void initialize_devlink_ports(const char* bus_name, const char* dev_name, const char* netdev_prefix) { struct genlmsghdr genlhdr; int len, total_len, id, err, offset; uint16_t netdev_index; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) exit(1); int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (rtsock == -1) exit(1); id = netlink_devlink_id_get(&nlmsg, sock); if (id == -1) goto error; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = DEVLINK_CMD_PORT_GET; netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1); err = netlink_send_ext(&nlmsg, sock, id, &total_len); if (err) { goto error; } offset = 0; netdev_index = 0; while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) { struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg.buf + offset + len; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) { char* port_name; char netdev_name[IFNAMSIZ]; port_name = (char*)(attr + 1); snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix, netdev_index); netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0, netdev_name); break; } } offset += len; netdev_index++; } error: close(rtsock); close(sock); } static void initialize_devlink_pci(void) { int netns = open("/proc/self/ns/net", O_RDONLY); if (netns == -1) exit(1); int ret = setns(kInitNetNsFd, 0); if (ret == -1) exit(1); netlink_devlink_netns_move("pci", "0000:00:10.0", netns); ret = setns(netns, 0); if (ret == -1) exit(1); close(netns); initialize_devlink_ports("pci", "0000:00:10.0", "netpci"); } #ifndef __NR_watch_devices #define __NR_watch_devices 436 #endif uint64_t r[1] = {0xffffffffffffffff}; int main(void) { syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0); intptr_t res = 0; memcpy((void*)0x20000000, "/dev/watch_queue\000", 17); res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000000ul, 0ul, 0ul); if (res != -1) r[0] = res; syscall(__NR_watch_devices, r[0], 0x42ul, 0ul); return 0; }
677787.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68a.c Label Definition File: CWE680_Integer_Overflow_To_Buffer_Overflow__malloc.label.xml Template File: sources-sink-68a.tmpl.c */ /* * @description * CWE: 680 Integer Overflow to Buffer Overflow * BadSource: fgets Read data from the console using fgets() * GoodSource: Small number greater than zero that will not cause an integer overflow in the sink * Sink: * BadSink : Attempt to allocate array using length value from source * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files * * */ #include "std_testcase.h" #define CHAR_ARRAY_SIZE sizeof(data)*sizeof(data) int CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68_bad_data; int CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68_goodG2B_data; #ifndef OMITBAD /* bad function declaration */ void CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68b_bad_sink(); void CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68_bad() { int data; /* Initialize data */ data = -1; { char input_buf[CHAR_ARRAY_SIZE] = ""; fgets(input_buf, CHAR_ARRAY_SIZE, stdin); /* Convert to int */ data = atoi(input_buf); } CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68_bad_data = data; CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68b_bad_sink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68b_goodG2B_sink(); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int data; /* Initialize data */ data = -1; /* FIX: Set data to a relatively small number greater than zero */ data = 20; CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68_goodG2B_data = data; CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68b_goodG2B_sink(); } void CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68_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()..."); CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE680_Integer_Overflow_To_Buffer_Overflow__malloc_fgets_68_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
943763.c
/**************************************************************************//** * @file main.c * @version V2.10 * $Revision: 2 $ * $Date: 16/10/25 4:26p $ * @brief Hardware Divider Sample Code * * @note * Copyright (C) 2016 Nuvoton Technology Corp. All rights reserved. * ******************************************************************************/ #include <stdio.h> #include "NUC1261.h" #define PLLCTL_SETTING CLK_PLLCTL_72MHz_HXT #define PLL_CLOCK 72000000 void SYS_Init(void) { int32_t i; /*---------------------------------------------------------------------------------------------------------*/ /* Init System Clock */ /*---------------------------------------------------------------------------------------------------------*/ /* Enable External XTAL (4~24 MHz) */ CLK->PWRCTL |= CLK_PWRCTL_HXTEN_Msk; CLK->PLLCTL = PLLCTL_SETTING; /* Waiting for clock ready */ i = 22000000; // For timeout while(i-- > 0) { if((CLK->STATUS & (CLK_STATUS_PLLSTB_Msk | CLK_STATUS_HXTSTB_Msk)) == (CLK_STATUS_PLLSTB_Msk | CLK_STATUS_HXTSTB_Msk)) break; } /* Switch HCLK clock source to PLL */ CLK->CLKSEL0 = CLK_CLKSEL0_HCLKSEL_PLL; /* Enable IP clock */ CLK->APBCLK0 = CLK_APBCLK0_UART0CKEN_Msk; /* Select IP clock source */ CLK->CLKSEL1 = CLK_CLKSEL1_UARTSEL_PLL; /* Update System Core Clock */ /* User can use SystemCoreClockUpdate() to calculate PllClock, SystemCoreClock and CycylesPerUs automatically. */ //SystemCoreClockUpdate(); PllClock = PLL_CLOCK; // PLL SystemCoreClock = PLL_CLOCK / 1; // HCLK CyclesPerUs = PLL_CLOCK / 1000000; // For SYS_SysTickDelay() /*---------------------------------------------------------------------------------------------------------*/ /* Init I/O Multi-function */ /*---------------------------------------------------------------------------------------------------------*/ /* Set PA multi-function pins for UART0 RXD and TXD */ SYS->GPA_MFPL &= ~(SYS_GPA_MFPL_PA3MFP_Msk | SYS_GPA_MFPL_PA2MFP_Msk); SYS->GPA_MFPL |= (SYS_GPA_MFPL_PA3MFP_UART0_RXD | SYS_GPA_MFPL_PA2MFP_UART0_TXD); } void UART0_Init(void) { /*---------------------------------------------------------------------------------------------------------*/ /* Init UART */ /*---------------------------------------------------------------------------------------------------------*/ /* Reset IP */ SYS->IPRST1 |= SYS_IPRST1_UART0RST_Msk; SYS->IPRST1 &= ~SYS_IPRST1_UART0RST_Msk; /* Configure UART0 and set UART0 Baudrate */ UART0->BAUD = UART_BAUD_MODE2 | UART_BAUD_MODE2_DIVIDER(PLL_CLOCK, 115200); UART0->LINE = UART_WORD_LEN_8 | UART_PARITY_NONE | UART_STOP_BIT_1; } void HDIV_Init(void) { /* Enable Hardware Divider Clock */ CLK->AHBCLK |= CLK_AHBCLK_HDIVCKEN_Msk; } /*---------------------------------------------------------------------------------------------------------*/ /* MAIN function */ /*---------------------------------------------------------------------------------------------------------*/ int main(void) { /* Disable register write-protection function */ SYS_UnlockReg(); /* Init System, IP clock and multi-function I/O */ SYS_Init(); /* Init UART0 for printf */ UART0_Init(); /* Init Divider */ HDIV_Init(); printf("+----------------------------------------------+\n"); printf("| Hardware Divider Sample Code |\n"); printf("+----------------------------------------------+\n"); printf("\n"); printf("12341 / 123 = %d\n", HDIV_Div(12341, 123)); printf("12341 %% 123 = %d\n", HDIV_Mod(12341, 123)); HDIV->DIVIDEND = 12341; HDIV->DIVISOR = 123; printf("12341 / 123 = %d, remainder = %d\n", HDIV->DIVQUO, HDIV->DIVREM); /* Lock protected registers */ SYS_LockReg(); printf("Done\n"); while(SYS->PDID); return 0; } /*** (C) COPYRIGHT 2016 Nuvoton Technology Corp. ***/
678791.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_int_declare_loop_67b.c Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.label.xml Template File: sources-sink-67b.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 int array 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" typedef struct _CWE121_Stack_Based_Buffer_Overflow__CWE805_int_declare_loop_67_structType { int * structFirst; } CWE121_Stack_Based_Buffer_Overflow__CWE805_int_declare_loop_67_structType; #ifndef OMITBAD void CWE121_Stack_Based_Buffer_Overflow__CWE805_int_declare_loop_67b_badSink(CWE121_Stack_Based_Buffer_Overflow__CWE805_int_declare_loop_67_structType myStruct) { int * data = myStruct.structFirst; { int source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printIntLine(data[0]); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE121_Stack_Based_Buffer_Overflow__CWE805_int_declare_loop_67b_goodG2BSink(CWE121_Stack_Based_Buffer_Overflow__CWE805_int_declare_loop_67_structType myStruct) { int * data = myStruct.structFirst; { int source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printIntLine(data[0]); } } } #endif /* OMITGOOD */
196654.c
/**************************************************************************** * modules/asmp/worker/arch/cpuid.c * * Copyright 2018 Sony Semiconductor Solutions Corporation * * 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 Sony Semiconductor Solutions Corporation nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include <asmp/types.h> #include "arm_arch.h" #include "chip.h" #define CPU_ID (CXD56_CPU_BASE + 0x40) cpuid_t asmp_getglobalcpuid(void) { return getreg32(CPU_ID); } cpuid_t asmp_getlocalcpuid(void) { return asmp_getglobalcpuid() - 2; }
883688.c
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2001, 2017 Oracle and/or its affiliates. All rights reserved. * * $Id$ */ #include "db_config.h" #include "db_int.h" #include "dbinc/db_page.h" #include "dbinc/db_am.h" #ifdef HAVE_STATISTICS static int __rep_print_all __P((ENV *, u_int32_t)); static int __rep_print_stats __P((ENV *, u_int32_t)); static int __rep_stat __P((ENV *, DB_REP_STAT **, u_int32_t)); static int __rep_stat_summary_print __P((ENV *)); static const char *__rep_syncstate_to_string __P((repsync_t)); /* * Print the individual statistic for items that appear both in the full and * the summary replication statistics output. */ #define PRINT_LOGQUEUED(sp) do { \ __db_dl(env, "Number of log records currently queued", \ (u_long)(sp)->st_log_queued); \ } while (0) #define PRINT_MAXPERMLSN(sp) do { \ __db_msg(env, "%lu/%lu\t%s", \ (u_long)(sp)->st_max_perm_lsn.file, \ (u_long)(sp)->st_max_perm_lsn.offset, \ (sp)->st_max_perm_lsn.file == 0 ? \ "No maximum permanent LSN" : \ "Maximum permanent LSN"); \ } while (0) #define PRINT_MSGSRECOVER(sp) do { \ __db_dl(env, "Number of messages ignored due to pending recovery", \ (u_long)(sp)->st_msgs_recover); \ } while (0) #define PRINT_MSGSSENDFAILURES(sp) do { \ __db_dl(env, "Number of failed message sends", \ (u_long)(sp)->st_msgs_send_failures); \ } while (0) #define PRINT_STARTUPCOMPLETE(sp) do { \ if ((sp)->st_startup_complete == 0) \ __db_msg(env, "Startup incomplete"); \ else \ __db_msg(env, "Startup complete"); \ } while (0) #define PRINT_STATUS(sp, is_client) do { \ is_client = 0; \ switch ((sp)->st_status) { \ case DB_REP_MASTER: \ __db_msg(env, \ "Environment configured as a replication master"); \ break; \ case DB_REP_CLIENT: \ __db_msg(env, \ "Environment configured as a replication client"); \ is_client = 1; \ break; \ default: \ __db_msg(env, \ "Environment not configured for replication"); \ break; \ } \ } while (0) #define PRINT_VIEW(sp) do { \ if ((sp)->st_view != 0) \ __db_msg(env, "Environment configured as view site"); \ else \ __db_msg(env, "Environment not configured as view site");\ } while (0) /* * __rep_stat_pp -- * ENV->rep_stat pre/post processing. * * PUBLIC: int __rep_stat_pp __P((DB_ENV *, DB_REP_STAT **, u_int32_t)); */ int __rep_stat_pp(dbenv, statp, flags) DB_ENV *dbenv; DB_REP_STAT **statp; u_int32_t flags; { DB_THREAD_INFO *ip; ENV *env; int ret; env = dbenv->env; ENV_REQUIRES_CONFIG_XX( env, rep_handle, "DB_ENV->rep_stat", DB_INIT_REP); if ((ret = __db_fchk(env, "DB_ENV->rep_stat", flags, DB_STAT_CLEAR)) != 0) return (ret); ENV_ENTER(env, ip); ret = __rep_stat(env, statp, flags); ENV_LEAVE(env, ip); return (ret); } /* * __rep_stat -- * ENV->rep_stat. */ static int __rep_stat(env, statp, flags) ENV *env; DB_REP_STAT **statp; u_int32_t flags; { DB_LOG *dblp; DB_REP *db_rep; DB_REP_STAT *stats; LOG *lp; REP *rep; u_int32_t startupdone, view; uintmax_t queued; int dolock, ret; db_rep = env->rep_handle; rep = db_rep->region; dblp = env->lg_handle; lp = dblp->reginfo.primary; *statp = NULL; /* Allocate a stat struct to return to the user. */ if ((ret = __os_umalloc(env, sizeof(DB_REP_STAT), &stats)) != 0) return (ret); /* * Read without holding the lock. If we are in client recovery, we * copy just the stats struct so we won't block. We only copy out * those stats that don't require acquiring any mutex. */ dolock = IS_REP_RECOVERING(rep) ? 0 : 1; memcpy(stats, &rep->stat, sizeof(*stats)); /* Copy out election stats. */ if (FLD_ISSET(rep->elect_flags, REP_E_PHASE1)) stats->st_election_status = 1; else if (FLD_ISSET(rep->elect_flags, REP_E_PHASE2)) stats->st_election_status = 2; stats->st_election_nsites = rep->sites; stats->st_election_cur_winner = rep->winner; stats->st_election_priority = rep->w_priority; stats->st_election_gen = rep->w_gen; stats->st_election_datagen = rep->w_datagen; stats->st_election_lsn = rep->w_lsn; stats->st_election_votes = rep->votes; stats->st_election_nvotes = rep->nvotes; stats->st_election_tiebreaker = rep->w_tiebreaker; /* Copy out other info that's protected by the rep mutex. */ stats->st_env_id = rep->eid; stats->st_env_priority = rep->priority; stats->st_nsites = rep->nsites; stats->st_master = rep->master_id; stats->st_gen = rep->gen; stats->st_egen = rep->egen; if (F_ISSET(rep, REP_F_MASTER)) stats->st_status = DB_REP_MASTER; else if (F_ISSET(rep, REP_F_CLIENT)) stats->st_status = DB_REP_CLIENT; else stats->st_status = 0; if (LF_ISSET(DB_STAT_CLEAR)) { queued = rep->stat.st_log_queued; startupdone = rep->stat.st_startup_complete; view = rep->stat.st_view; memset(&rep->stat, 0, sizeof(rep->stat)); rep->stat.st_log_queued = rep->stat.st_log_queued_total = rep->stat.st_log_queued_max = queued; rep->stat.st_startup_complete = startupdone; rep->stat.st_view = view; } /* * Log-related replication info is stored in the log system and * protected by the log region lock. */ if (dolock) MUTEX_LOCK(env, rep->mtx_clientdb); if (F_ISSET(rep, REP_F_CLIENT)) { stats->st_next_lsn = lp->ready_lsn; stats->st_waiting_lsn = lp->waiting_lsn; stats->st_next_pg = rep->ready_pg; stats->st_waiting_pg = rep->waiting_pg; stats->st_max_lease_sec = (u_int32_t)lp->max_lease_ts.tv_sec; stats->st_max_lease_usec = (u_int32_t) (lp->max_lease_ts.tv_nsec / NS_PER_US); } else { if (F_ISSET(rep, REP_F_MASTER)) { LOG_SYSTEM_LOCK(env); stats->st_next_lsn = lp->lsn; LOG_SYSTEM_UNLOCK(env); } else ZERO_LSN(stats->st_next_lsn); ZERO_LSN(stats->st_waiting_lsn); stats->st_max_lease_sec = 0; stats->st_max_lease_usec = 0; } stats->st_max_perm_lsn = lp->max_perm_lsn; if (dolock) MUTEX_UNLOCK(env, rep->mtx_clientdb); *statp = stats; return (0); } /* * __rep_stat_print_pp -- * ENV->rep_stat_print pre/post processing. * * PUBLIC: int __rep_stat_print_pp __P((DB_ENV *, u_int32_t)); */ int __rep_stat_print_pp(dbenv, flags) DB_ENV *dbenv; u_int32_t flags; { DB_THREAD_INFO *ip; ENV *env; int ret; env = dbenv->env; ENV_REQUIRES_CONFIG_XX( env, rep_handle, "DB_ENV->rep_stat_print", DB_INIT_REP); if ((ret = __db_fchk(env, "DB_ENV->rep_stat_print", flags, DB_STAT_ALL | DB_STAT_CLEAR | DB_STAT_SUMMARY)) != 0) return (ret); ENV_ENTER(env, ip); ret = __rep_stat_print(env, flags); ENV_LEAVE(env, ip); return (ret); } /* * __rep_stat_print -- * ENV->rep_stat_print method. * * PUBLIC: int __rep_stat_print __P((ENV *, u_int32_t)); */ int __rep_stat_print(env, flags) ENV *env; u_int32_t flags; { u_int32_t orig_flags; int ret; orig_flags = flags; LF_CLR(DB_STAT_CLEAR | DB_STAT_SUBSYSTEM); if (LF_ISSET(DB_STAT_SUMMARY)) return (__rep_stat_summary_print(env)); if (flags == 0 || LF_ISSET(DB_STAT_ALL)) { ret = __rep_print_stats(env, orig_flags); if (flags == 0 || ret != 0) return (ret); } if (LF_ISSET(DB_STAT_ALL) && (ret = __rep_print_all(env, orig_flags)) != 0) return (ret); return (0); } /* * __rep_print_stats -- * Print out default statistics. */ static int __rep_print_stats(env, flags) ENV *env; u_int32_t flags; { DB_REP_STAT *sp; int is_client, ret; char *p; if ((ret = __rep_stat(env, &sp, flags)) != 0) return (ret); if (LF_ISSET(DB_STAT_ALL)) __db_msg(env, "Default replication region information:"); PRINT_STATUS(sp, is_client); __db_msg(env, "%lu/%lu\t%s", (u_long)sp->st_next_lsn.file, (u_long)sp->st_next_lsn.offset, is_client ? "Next LSN expected" : "Next LSN to be used"); __db_msg(env, "%lu/%lu\t%s", (u_long)sp->st_waiting_lsn.file, (u_long)sp->st_waiting_lsn.offset, sp->st_waiting_lsn.file == 0 ? "Not waiting for any missed log records" : "LSN of first log record we have after missed log records"); PRINT_MAXPERMLSN(sp); __db_dl(env, "Next page number expected", (u_long)sp->st_next_pg); p = sp->st_waiting_pg == PGNO_INVALID ? "Not waiting for any missed pages" : "Page number of first page we have after missed pages"; __db_msg(env, "%lu\t%s", (u_long)sp->st_waiting_pg, p); __db_dl(env, "Number of duplicate external file data messages received", (u_long)sp->st_ext_duplicated); __db_dl(env, "Number of external file data messages written to disk", (u_long)sp->st_ext_records); __db_dl(env, "Number of external file data messages re-requested", (u_long)sp->st_ext_rereq); __db_dl(env, "Number of external file update messages re-requested", (u_long)sp->st_ext_update_rereq); __db_dl(env, "Number of duplicate master conditions originally detected at this site", (u_long)sp->st_dupmasters); if (sp->st_env_id != DB_EID_INVALID) __db_dl(env, "Current environment ID", (u_long)sp->st_env_id); else __db_msg(env, "No current environment ID"); __db_dl(env, "Current environment priority", (u_long)sp->st_env_priority); __db_dl(env, "Current generation number", (u_long)sp->st_gen); __db_dl(env, "Election generation number for the current or next election", (u_long)sp->st_egen); __db_dl(env, "Number of lease validity checks", (u_long)sp->st_lease_chk); __db_dl(env, "Number of invalid lease validity checks", (u_long)sp->st_lease_chk_misses); __db_dl(env, "Number of lease refresh attempts during lease validity checks", (u_long)sp->st_lease_chk_refresh); __db_dl(env, "Number of live messages sent while using leases", (u_long)sp->st_lease_sends); __db_dl(env, "Number of duplicate log records received", (u_long)sp->st_log_duplicated); PRINT_LOGQUEUED(sp); __db_dl(env, "Maximum number of log records ever queued at once", (u_long)sp->st_log_queued_max); __db_dl(env, "Total number of log records queued", (u_long)sp->st_log_queued_total); __db_dl(env, "Number of log records received and appended to the log", (u_long)sp->st_log_records); __db_dl(env, "Number of log records missed and requested", (u_long)sp->st_log_requested); if (sp->st_master != DB_EID_INVALID) __db_dl(env, "Current master ID", (u_long)sp->st_master); else __db_msg(env, "No current master ID"); __db_dl(env, "Number of times the master has changed", (u_long)sp->st_master_changes); __db_dl(env, "Number of messages received with a bad generation number", (u_long)sp->st_msgs_badgen); __db_dl(env, "Number of messages received and processed", (u_long)sp->st_msgs_processed); PRINT_MSGSRECOVER(sp); PRINT_MSGSSENDFAILURES(sp); __db_dl(env, "Number of messages sent", (u_long)sp->st_msgs_sent); __db_dl(env, "Number of new site messages received", (u_long)sp->st_newsites); __db_dl(env, "Number of environments used in the last election", (u_long)(sp)->st_nsites); __db_dl(env, "Transmission limited", (u_long)sp->st_nthrottles); __db_dl(env, "Number of outdated conditions detected", (u_long)sp->st_outdated); __db_dl(env, "Number of duplicate page records received", (u_long)sp->st_pg_duplicated); __db_dl(env, "Number of page records received and added to databases", (u_long)sp->st_pg_records); __db_dl(env, "Number of page records missed and requested", (u_long)sp->st_pg_requested); PRINT_STARTUPCOMPLETE(sp); PRINT_VIEW(sp); __db_dl(env, "Number of transactions applied", (u_long)sp->st_txns_applied); __db_dl(env, "Number of startsync messages delayed", (u_long)sp->st_startsync_delayed); __db_dl(env, "Number of elections held", (u_long)sp->st_elections); __db_dl(env, "Number of elections won", (u_long)sp->st_elections_won); if (sp->st_election_status == 0) { __db_msg(env, "No election in progress"); if (sp->st_election_sec > 0 || sp->st_election_usec > 0) __db_msg(env, "%lu.%.6lu\tDuration of last election (seconds)", (u_long)sp->st_election_sec, (u_long)sp->st_election_usec); } else { __db_dl(env, "Current election phase", (u_long)sp->st_election_status); __db_dl(env, "Environment ID of the winner of the current or last election", (u_long)sp->st_election_cur_winner); __db_dl(env, "Master generation number of the winner of the current or last election", (u_long)sp->st_election_gen); __db_dl(env, "Master data generation number of the winner of the current or last election", (u_long)sp->st_election_datagen); __db_msg(env, "%lu/%lu\tMaximum LSN of the winner of the current or last election", (u_long)sp->st_election_lsn.file, (u_long)sp->st_election_lsn.offset); __db_dl(env, "Number of sites responding to this site during the current election", (u_long)sp->st_election_nsites); __db_dl(env, "Number of votes required in the current or last election", (u_long)sp->st_election_nvotes); __db_dl(env, "Priority of the winner of the current or last election", (u_long)sp->st_election_priority); __db_dl(env, "Tiebreaker value of the winner of the current or last election", (u_long)sp->st_election_tiebreaker); __db_dl(env, "Number of votes received during the current election", (u_long)sp->st_election_votes); } __db_dl(env, "Number of bulk buffer sends triggered by full buffer", (u_long)sp->st_bulk_fills); __db_dl(env, "Number of single records exceeding bulk buffer size", (u_long)sp->st_bulk_overflows); __db_dl(env, "Number of records added to a bulk buffer", (u_long)sp->st_bulk_records); __db_dl(env, "Number of bulk buffers sent", (u_long)sp->st_bulk_transfers); __db_dl(env, "Number of re-request messages received", (u_long)sp->st_client_rerequests); __db_dl(env, "Number of request messages this client failed to process", (u_long)sp->st_client_svc_miss); __db_dl(env, "Number of request messages received by this client", (u_long)sp->st_client_svc_req); if (sp->st_max_lease_sec > 0 || sp->st_max_lease_usec > 0) __db_msg(env, "%lu.%.6lu\tDuration of maximum lease (seconds)", (u_long)sp->st_max_lease_sec, (u_long)sp->st_max_lease_usec); __os_ufree(env, sp); return (0); } /* * __rep_print_all -- * Display debugging replication region statistics. */ static int __rep_print_all(env, flags) ENV *env; u_int32_t flags; { static const FN rep_cfn[] = { { REP_C_2SITE_STRICT, "REP_C_2SITE_STRICT" }, { REP_C_AUTOINIT, "REP_C_AUTOINIT" }, { REP_C_AUTOROLLBACK, "REP_C_AUTOROLLBACK" }, { REP_C_AUTOTAKEOVER, "REP_C_AUTOTAKEOVER" }, { REP_C_BULK, "REP_C_BULK" }, { REP_C_DELAYCLIENT, "REP_C_DELAYCLIENT" }, { REP_C_ELECT_LOGLENGTH, "REP_C_ELECT_LOGLENGTH" }, { REP_C_ELECTIONS, "REP_C_ELECTIONS" }, { REP_C_FORWARD_WRITES, "REP_C_FORWARD_WRITES" }, { REP_C_INMEM, "REP_C_INMEM" }, { REP_C_LEASE, "REP_C_LEASE" }, { REP_C_NOWAIT, "REP_C_NOWAIT" }, { REP_C_PREFMAS_CLIENT, "REP_C_PREFMAS_CLIENT" }, { REP_C_PREFMAS_MASTER, "REP_C_PREFMAS_MASTER" }, { 0, NULL } }; static const FN rep_efn[] = { { REP_E_PHASE0, "REP_E_PHASE0" }, { REP_E_PHASE1, "REP_E_PHASE1" }, { REP_E_PHASE2, "REP_E_PHASE2" }, { REP_E_TALLY, "REP_E_TALLY" }, { 0, NULL } }; static const FN rep_fn[] = { { REP_F_ABBREVIATED, "REP_F_ABBREVIATED" }, { REP_F_APP_BASEAPI, "REP_F_APP_BASEAPI" }, { REP_F_APP_REPMGR, "REP_F_APP_REPMGR" }, { REP_F_CLIENT, "REP_F_CLIENT" }, { REP_F_DELAY, "REP_F_DELAY" }, { REP_F_GROUP_ESTD, "REP_F_GROUP_ESTD" }, { REP_F_HOLD_GEN, "REP_F_HOLD_GEN" }, { REP_F_LEASE_EXPIRED, "REP_F_LEASE_EXPIRED" }, { REP_F_MASTER, "REP_F_MASTER" }, { REP_F_MASTERELECT, "REP_F_MASTERELECT" }, { REP_F_NEWFILE, "REP_F_NEWFILE" }, { REP_F_NIMDBS_LOADED, "REP_F_NIMDBS_LOADED" }, { REP_F_READONLY_MASTER, "REP_F_READONLY_MASTER" }, { REP_F_SKIPPED_APPLY, "REP_F_SKIPPED_APPLY" }, { REP_F_START_CALLED, "REP_F_START_CALLED" }, { 0, NULL } }; static const FN rep_lfn[] = { { REP_LOCKOUT_API, "REP_LOCKOUT_API" }, { REP_LOCKOUT_APPLY, "REP_LOCKOUT_APPLY" }, { REP_LOCKOUT_ARCHIVE, "REP_LOCKOUT_ARCHIVE" }, { REP_LOCKOUT_MSG, "REP_LOCKOUT_MSG" }, { REP_LOCKOUT_OP, "REP_LOCKOUT_OP" }, { 0, NULL } }; static const FN dbrep_fn[] = { { DBREP_APP_BASEAPI, "DBREP_APP_BASEAPI" }, { DBREP_APP_REPMGR, "DBREP_APP_REPMGR" }, { DBREP_OPENFILES, "DBREP_OPENFILES" }, { 0, NULL } }; DB_LOG *dblp; DB_REP *db_rep; DB_THREAD_INFO *ip; LOG *lp; REGENV *renv; REGINFO *infop; REP *rep; char time_buf[CTIME_BUFLEN]; db_rep = env->rep_handle; rep = db_rep->region; infop = env->reginfo; renv = infop->primary; __db_msg(env, "%s", DB_GLOBAL(db_line)); __db_msg(env, "DB_REP handle information:"); if (db_rep->rep_db == NULL) STAT_ISSET("Bookkeeping database", db_rep->rep_db); else { ENV_GET_THREAD_INFO(env, ip); (void)__db_stat_print(db_rep->rep_db, ip, flags); } __db_prflags(env, NULL, db_rep->flags, dbrep_fn, NULL, "\tFlags"); __db_msg(env, "%s", DB_GLOBAL(db_line)); __db_msg(env, "REP handle information:"); __mutex_print_debug_single(env, "Replication region mutex", rep->mtx_region, flags); __mutex_print_debug_single(env, "Bookkeeping database mutex", rep->mtx_clientdb, flags); STAT_LONG("Environment ID", rep->eid); STAT_LONG("Master environment ID", rep->master_id); STAT_ULONG("Election generation", rep->egen); STAT_ULONG("Last active egen", rep->spent_egen); STAT_ULONG("Master generation", rep->gen); STAT_LONG("Space allocated for sites", rep->asites); STAT_LONG("Sites in group", rep->nsites); STAT_LONG("Votes needed for election", rep->nvotes); STAT_LONG("Priority in election", rep->priority); __db_dlbytes(env, "Limit on data sent in a single call", rep->gbytes, (u_long)0, rep->bytes); STAT_LONG("Request gap seconds", rep->request_gap.tv_sec); STAT_LONG("Request gap microseconds", rep->request_gap.tv_nsec / NS_PER_US); STAT_LONG("Maximum gap seconds", rep->max_gap.tv_sec); STAT_LONG("Maximum gap microseconds", rep->max_gap.tv_nsec / NS_PER_US); STAT_ULONG("Callers in rep_proc_msg", rep->msg_th); STAT_ULONG("Callers in rep_elect", rep->elect_th); STAT_ULONG("Library handle count", rep->handle_cnt); STAT_ULONG("Multi-step operation count", rep->op_cnt); __db_msg(env, "%.24s\tRecovery timestamp", renv->rep_timestamp == 0 ? "0" : __os_ctime(&renv->rep_timestamp, time_buf)); STAT_LONG("Sites heard from", rep->sites); STAT_LONG("Current winner", rep->winner); STAT_LONG("Winner priority", rep->w_priority); STAT_ULONG("Winner generation", rep->w_gen); STAT_ULONG("Winner data generation", rep->w_datagen); STAT_LSN("Winner LSN", &rep->w_lsn); STAT_LONG("Winner tiebreaker", rep->w_tiebreaker); STAT_LONG("Votes for this site", rep->votes); STAT_STRING("Synchronization State", __rep_syncstate_to_string(rep->sync_state)); __db_prflags(env, NULL, rep->config, rep_cfn, NULL, "\tConfig Flags"); __db_prflags(env, NULL, rep->elect_flags, rep_efn, NULL, "\tElect Flags"); __db_prflags(env, NULL, rep->lockout_flags, rep_lfn, NULL, "\tLockout Flags"); __db_prflags(env, NULL, rep->flags, rep_fn, NULL, "\tFlags"); __db_msg(env, "%s", DB_GLOBAL(db_line)); __db_msg(env, "LOG replication information:"); MUTEX_LOCK(env, rep->mtx_clientdb); dblp = env->lg_handle; lp = (LOG *)dblp->reginfo.primary; STAT_LSN("First log record after a gap", &lp->waiting_lsn); STAT_LSN("Maximum permanent LSN processed", &lp->max_perm_lsn); STAT_LSN("LSN waiting to verify", &lp->verify_lsn); STAT_LSN("Maximum LSN requested", &lp->max_wait_lsn); STAT_LONG("Time to wait before requesting seconds", lp->wait_ts.tv_sec); STAT_LONG("Time to wait before requesting microseconds", lp->wait_ts.tv_nsec / NS_PER_US); STAT_LSN("Next LSN expected", &lp->ready_lsn); STAT_LONG("Maximum lease timestamp seconds", lp->max_lease_ts.tv_sec); STAT_LONG("Maximum lease timestamp microseconds", lp->max_lease_ts.tv_nsec / NS_PER_US); MUTEX_UNLOCK(env, rep->mtx_clientdb); return (0); } static const char * __rep_syncstate_to_string(state) repsync_t state; { switch (state) { case SYNC_OFF: return ("Not Synchronizing"); case SYNC_LOG: return ("SYNC_LOG"); case SYNC_PAGE: return ("SYNC_PAGE"); case SYNC_UPDATE: return ("SYNC_UPDATE"); case SYNC_VERIFY: return ("SYNC_VERIFY"); default: break; } return ("UNKNOWN STATE"); } /* * __rep_stat_summary_print -- * Print out a brief summary of replication statistics. */ static int __rep_stat_summary_print(env) ENV *env; { DB_REP *db_rep; DB_REP_STAT *sp; REP *rep; int is_client, ret; db_rep = env->rep_handle; rep = db_rep->region; ret = 0; if ((ret = __rep_stat(env, &sp, 0)) == 0) { PRINT_STATUS(sp, is_client); if (is_client) { PRINT_STARTUPCOMPLETE(sp); PRINT_VIEW(sp); } PRINT_MAXPERMLSN(sp); /* * Use the number of sites that is kept up-to-date most * frequently. The rep_stat st_nsites is only current * as of the last election. */ __db_dl(env, "Number of environments in the replication group", (u_long)rep->config_nsites); PRINT_MSGSSENDFAILURES(sp); PRINT_MSGSRECOVER(sp); PRINT_LOGQUEUED(sp); __os_ufree(env, sp); } return (ret); } #else /* !HAVE_STATISTICS */ int __rep_stat_pp(dbenv, statp, flags) DB_ENV *dbenv; DB_REP_STAT **statp; u_int32_t flags; { COMPQUIET(statp, NULL); COMPQUIET(flags, 0); return (__db_stat_not_built(dbenv->env)); } int __rep_stat_print_pp(dbenv, flags) DB_ENV *dbenv; u_int32_t flags; { COMPQUIET(flags, 0); return (__db_stat_not_built(dbenv->env)); } #endif
61280.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "X2AP-PDU-Contents" * found in "/home/vesh/openairinterface5g/openair2/X2AP/MESSAGES/ASN1/R14/x2ap-14.6.0.asn1" * `asn1c -pdu=all -fcompound-names -fno-include-deps -gen-PER -gen-OER -no-gen-example -D /home/vesh/openairinterface5g/cmake_targets/lte_build_oai/build/CMakeFiles/X2AP_R14` */ #include "X2AP_E-RABs-ToBeAdded-List.h" #include "X2AP_ProtocolIE-Single-Container.h" static asn_oer_constraints_t asn_OER_type_X2AP_E_RABs_ToBeAdded_List_constr_1 CC_NOTUSED = { { 0, 0 }, -1 /* (SIZE(1..256)) */}; static asn_per_constraints_t asn_PER_type_X2AP_E_RABs_ToBeAdded_List_constr_1 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 8, 8, 1, 256 } /* (SIZE(1..256)) */, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t asn_MBR_X2AP_E_RABs_ToBeAdded_List_1[] = { { ATF_POINTER, 0, 0, (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)), 0, &asn_DEF_X2AP_ProtocolIE_Single_Container_4992P9, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "" }, }; static const ber_tlv_tag_t asn_DEF_X2AP_E_RABs_ToBeAdded_List_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static asn_SET_OF_specifics_t asn_SPC_X2AP_E_RABs_ToBeAdded_List_specs_1 = { sizeof(struct X2AP_E_RABs_ToBeAdded_List), offsetof(struct X2AP_E_RABs_ToBeAdded_List, _asn_ctx), 0, /* XER encoding is XMLDelimitedItemList */ }; asn_TYPE_descriptor_t asn_DEF_X2AP_E_RABs_ToBeAdded_List = { "E-RABs-ToBeAdded-List", "E-RABs-ToBeAdded-List", &asn_OP_SEQUENCE_OF, asn_DEF_X2AP_E_RABs_ToBeAdded_List_tags_1, sizeof(asn_DEF_X2AP_E_RABs_ToBeAdded_List_tags_1) /sizeof(asn_DEF_X2AP_E_RABs_ToBeAdded_List_tags_1[0]), /* 1 */ asn_DEF_X2AP_E_RABs_ToBeAdded_List_tags_1, /* Same as above */ sizeof(asn_DEF_X2AP_E_RABs_ToBeAdded_List_tags_1) /sizeof(asn_DEF_X2AP_E_RABs_ToBeAdded_List_tags_1[0]), /* 1 */ { &asn_OER_type_X2AP_E_RABs_ToBeAdded_List_constr_1, &asn_PER_type_X2AP_E_RABs_ToBeAdded_List_constr_1, SEQUENCE_OF_constraint }, asn_MBR_X2AP_E_RABs_ToBeAdded_List_1, 1, /* Single element */ &asn_SPC_X2AP_E_RABs_ToBeAdded_List_specs_1 /* Additional specs */ };
845700.c
/***************************************************************************** Copyright (c) 2014, Intel Corp. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************** * Contents: Native high-level C interface to LAPACK function cgeequ * Author: Intel Corporation * Generated November 2015 *****************************************************************************/ #include "lapacke_utils.h" lapack_int LAPACKE_cgeequ( int matrix_layout, lapack_int m, lapack_int n, const lapack_complex_float* a, lapack_int lda, float* r, float* c, float* rowcnd, float* colcnd, float* amax ) { if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { LAPACKE_xerbla( "LAPACKE_cgeequ", -1 ); return -1; } #ifndef LAPACK_DISABLE_NAN_CHECK if( LAPACKE_get_nancheck() ) { /* Optionally check input matrices for NaNs */ if( LAPACKE_cge_nancheck( matrix_layout, m, n, a, lda ) ) { return -4; } } #endif return LAPACKE_cgeequ_work( matrix_layout, m, n, a, lda, r, c, rowcnd, colcnd, amax ); }
862046.c
// Copyright 2016-2018 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <esp_types.h> #include <stdlib.h> #include <ctype.h> #include "esp32/rom/ets_sys.h" #include "esp_log.h" #include "soc/rtc_io_reg.h" #include "soc/rtc_io_struct.h" #include "soc/sens_reg.h" #include "soc/sens_struct.h" #include "soc/rtc_cntl_reg.h" #include "soc/rtc_cntl_struct.h" #include "soc/syscon_reg.h" #include "soc/syscon_struct.h" #include "soc/rtc.h" #include "rtc_io.h" #include "touch_pad.h" #include "adc.h" #include "dac.h" #include "freertos/FreeRTOS.h" #include "freertos/xtensa_api.h" #include "freertos/semphr.h" #include "freertos/timers.h" #include "esp_intr_alloc.h" #include "sys/lock.h" #include "driver/rtc_cntl.h" #include "driver/gpio.h" #include "adc1_i2s_private.h" #ifndef NDEBUG // Enable built-in checks in queue.h in debug builds #define INVARIANTS #endif #include "sys/queue.h" #define ADC_FSM_RSTB_WAIT_DEFAULT (8) #define ADC_FSM_START_WAIT_DEFAULT (5) #define ADC_FSM_STANDBY_WAIT_DEFAULT (100) #define ADC_FSM_TIME_KEEP (-1) #define ADC_MAX_MEAS_NUM_DEFAULT (255) #define ADC_MEAS_NUM_LIM_DEFAULT (1) #define SAR_ADC_CLK_DIV_DEFUALT (2) #define ADC_PATT_LEN_MAX (16) #define TOUCH_PAD_FILTER_FACTOR_DEFAULT (4) // IIR filter coefficient. #define TOUCH_PAD_SHIFT_DEFAULT (4) // Increase computing accuracy. #define TOUCH_PAD_SHIFT_ROUND_DEFAULT (8) // ROUND = 2^(n-1); rounding off for fractional. #define DAC_ERR_STR_CHANNEL_ERROR "DAC channel error" static const char *RTC_MODULE_TAG = "RTC_MODULE"; #define RTC_MODULE_CHECK(a, str, ret_val) if (!(a)) { \ ESP_LOGE(RTC_MODULE_TAG,"%s:%d (%s):%s", __FILE__, __LINE__, __FUNCTION__, str); \ return (ret_val); \ } #define RTC_RES_CHECK(res, ret_val) if ( (a) != ESP_OK) { \ ESP_LOGE(RTC_MODULE_TAG,"%s:%d (%s)", __FILE__, __LINE__, __FUNCTION__); \ return (ret_val); \ } #define ADC_CHECK_UNIT(unit) RTC_MODULE_CHECK(adc_unit < ADC_UNIT_2, "ADC unit error, only support ADC1 for now", ESP_ERR_INVALID_ARG) #define ADC1_CHECK_FUNCTION_RET(fun_ret) if(fun_ret!=ESP_OK){\ ESP_LOGE(RTC_MODULE_TAG,"%s:%d\n",__FUNCTION__,__LINE__);\ return ESP_FAIL;\ } #define ADC2_CHECK_FUNCTION_RET(fun_ret) do { if(fun_ret!=ESP_OK){\ ESP_LOGE(RTC_MODULE_TAG,"%s:%d\n",__FUNCTION__,__LINE__);\ return ESP_FAIL;\ } }while (0) portMUX_TYPE rtc_spinlock = portMUX_INITIALIZER_UNLOCKED; static SemaphoreHandle_t rtc_touch_mux = NULL; /* In ADC2, there're two locks used for different cases: 1. lock shared with app and WIFI: when wifi using the ADC2, we assume it will never stop, so app checks the lock and returns immediately if failed. 2. lock shared between tasks: when several tasks sharing the ADC2, we want to guarantee all the requests will be handled. Since conversions are short (about 31us), app returns the lock very soon, we use a spinlock to stand there waiting to do conversions one by one. adc2_spinlock should be acquired first, then adc2_wifi_lock or rtc_spinlock. */ //prevent ADC2 being used by wifi and other tasks at the same time. static _lock_t adc2_wifi_lock; //prevent ADC2 being used by tasks (regardless of WIFI) portMUX_TYPE adc2_spinlock = portMUX_INITIALIZER_UNLOCKED; //prevent ADC1 being used by I2S dma and other tasks at the same time. static _lock_t adc1_i2s_lock; typedef struct { TimerHandle_t timer; uint16_t filtered_val[TOUCH_PAD_MAX]; uint16_t raw_val[TOUCH_PAD_MAX]; uint32_t filter_period; uint32_t period; bool enable; } touch_pad_filter_t; static touch_pad_filter_t *s_touch_pad_filter = NULL; // check if touch pad be inited. static uint16_t s_touch_pad_init_bit = 0x0000; static filter_cb_t s_filter_cb = NULL; typedef enum { ADC_CTRL_RTC = 0, ADC_CTRL_ULP = 1, ADC_CTRL_DIG = 2, ADC2_CTRL_PWDET = 3, } adc_controller_t ; static const char TAG[] = "adc"; static inline void dac_output_set_enable(dac_channel_t channel, bool enable); static inline void adc1_hall_enable(bool enable); /*--------------------------------------------------------------- RTC IO ---------------------------------------------------------------*/ esp_err_t rtc_gpio_init(gpio_num_t gpio_num) { RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); // 0: GPIO connected to digital GPIO module. 1: GPIO connected to analog RTC module. SET_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, (rtc_gpio_desc[gpio_num].mux)); //0:RTC FUNCIOTN 1,2,3:Reserved SET_PERI_REG_BITS(rtc_gpio_desc[gpio_num].reg, RTC_IO_TOUCH_PAD1_FUN_SEL_V, 0x0, rtc_gpio_desc[gpio_num].func); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_deinit(gpio_num_t gpio_num) { RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); //Select Gpio as Digital Gpio CLEAR_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, (rtc_gpio_desc[gpio_num].mux)); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } static esp_err_t rtc_gpio_output_enable(gpio_num_t gpio_num) { int rtc_gpio_num = rtc_gpio_desc[gpio_num].rtc_num; RTC_MODULE_CHECK(rtc_gpio_num != -1, "RTC_GPIO number error", ESP_ERR_INVALID_ARG); SET_PERI_REG_MASK(RTC_GPIO_ENABLE_W1TS_REG, (1 << (rtc_gpio_num + RTC_GPIO_ENABLE_W1TS_S))); CLEAR_PERI_REG_MASK(RTC_GPIO_ENABLE_W1TC_REG, (1 << (rtc_gpio_num + RTC_GPIO_ENABLE_W1TC_S))); return ESP_OK; } static esp_err_t rtc_gpio_output_disable(gpio_num_t gpio_num) { int rtc_gpio_num = rtc_gpio_desc[gpio_num].rtc_num; RTC_MODULE_CHECK(rtc_gpio_num != -1, "RTC_GPIO number error", ESP_ERR_INVALID_ARG); CLEAR_PERI_REG_MASK(RTC_GPIO_ENABLE_W1TS_REG, (1 << (rtc_gpio_num + RTC_GPIO_ENABLE_W1TS_S))); SET_PERI_REG_MASK(RTC_GPIO_ENABLE_W1TC_REG, (1 << ( rtc_gpio_num + RTC_GPIO_ENABLE_W1TC_S))); return ESP_OK; } static esp_err_t rtc_gpio_input_enable(gpio_num_t gpio_num) { RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); SET_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].ie); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } static esp_err_t rtc_gpio_input_disable(gpio_num_t gpio_num) { RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); CLEAR_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].ie); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_set_level(gpio_num_t gpio_num, uint32_t level) { int rtc_gpio_num = rtc_gpio_num = rtc_gpio_desc[gpio_num].rtc_num;; RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); if (level) { WRITE_PERI_REG(RTC_GPIO_OUT_W1TS_REG, (1 << (rtc_gpio_num + RTC_GPIO_OUT_DATA_W1TS_S))); } else { WRITE_PERI_REG(RTC_GPIO_OUT_W1TC_REG, (1 << (rtc_gpio_num + RTC_GPIO_OUT_DATA_W1TC_S))); } return ESP_OK; } uint32_t rtc_gpio_get_level(gpio_num_t gpio_num) { uint32_t level = 0; int rtc_gpio_num = rtc_gpio_desc[gpio_num].rtc_num; RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); level = READ_PERI_REG(RTC_GPIO_IN_REG); portEXIT_CRITICAL(&rtc_spinlock); return ((level >> (RTC_GPIO_IN_NEXT_S + rtc_gpio_num)) & 0x01); } esp_err_t rtc_gpio_set_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t strength) { RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(GPIO_IS_VALID_OUTPUT_GPIO(gpio_num), "Output pad only", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(strength < GPIO_DRIVE_CAP_MAX, "GPIO drive capability error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); SET_PERI_REG_BITS(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].drv_v, strength, rtc_gpio_desc[gpio_num].drv_s); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t* strength) { RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(GPIO_IS_VALID_OUTPUT_GPIO(gpio_num), "Output pad only", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(strength != NULL, "GPIO drive pointer error", ESP_ERR_INVALID_ARG); *strength = GET_PERI_REG_BITS2(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].drv_v, rtc_gpio_desc[gpio_num].drv_s); return ESP_OK; } esp_err_t rtc_gpio_set_direction(gpio_num_t gpio_num, rtc_gpio_mode_t mode) { RTC_MODULE_CHECK(rtc_gpio_is_valid_gpio(gpio_num), "RTC_GPIO number error", ESP_ERR_INVALID_ARG); switch (mode) { case RTC_GPIO_MODE_INPUT_ONLY: rtc_gpio_output_disable(gpio_num); rtc_gpio_input_enable(gpio_num); break; case RTC_GPIO_MODE_OUTPUT_ONLY: rtc_gpio_output_enable(gpio_num); rtc_gpio_input_disable(gpio_num); break; case RTC_GPIO_MODE_INPUT_OUTPUT: rtc_gpio_output_enable(gpio_num); rtc_gpio_input_enable(gpio_num); break; case RTC_GPIO_MODE_DISABLED: rtc_gpio_output_disable(gpio_num); rtc_gpio_input_disable(gpio_num); break; } return ESP_OK; } esp_err_t rtc_gpio_pullup_en(gpio_num_t gpio_num) { //this is a digital pad if (rtc_gpio_desc[gpio_num].pullup == 0) { return ESP_ERR_INVALID_ARG; } //this is a rtc pad portENTER_CRITICAL(&rtc_spinlock); SET_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].pullup); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_pulldown_en(gpio_num_t gpio_num) { //this is a digital pad if (rtc_gpio_desc[gpio_num].pulldown == 0) { return ESP_ERR_INVALID_ARG; } //this is a rtc pad portENTER_CRITICAL(&rtc_spinlock); SET_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].pulldown); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_pullup_dis(gpio_num_t gpio_num) { //this is a digital pad if ( rtc_gpio_desc[gpio_num].pullup == 0 ) { return ESP_ERR_INVALID_ARG; } //this is a rtc pad portENTER_CRITICAL(&rtc_spinlock); CLEAR_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].pullup); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_pulldown_dis(gpio_num_t gpio_num) { //this is a digital pad if (rtc_gpio_desc[gpio_num].pulldown == 0) { return ESP_ERR_INVALID_ARG; } //this is a rtc pad portENTER_CRITICAL(&rtc_spinlock); CLEAR_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].pulldown); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_hold_en(gpio_num_t gpio_num) { // check if an RTC IO if (rtc_gpio_desc[gpio_num].pullup == 0) { return ESP_ERR_INVALID_ARG; } portENTER_CRITICAL(&rtc_spinlock); SET_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].hold); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_hold_dis(gpio_num_t gpio_num) { // check if an RTC IO if (rtc_gpio_desc[gpio_num].pullup == 0) { return ESP_ERR_INVALID_ARG; } portENTER_CRITICAL(&rtc_spinlock); CLEAR_PERI_REG_MASK(rtc_gpio_desc[gpio_num].reg, rtc_gpio_desc[gpio_num].hold); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t rtc_gpio_isolate(gpio_num_t gpio_num) { if (rtc_gpio_desc[gpio_num].reg == 0) { return ESP_ERR_INVALID_ARG; } rtc_gpio_pullup_dis(gpio_num); rtc_gpio_pulldown_dis(gpio_num); rtc_gpio_set_direction(gpio_num, RTC_GPIO_MODE_DISABLED); rtc_gpio_hold_en(gpio_num); return ESP_OK; } void rtc_gpio_force_hold_dis_all() { for (int gpio = 0; gpio < GPIO_PIN_COUNT; ++gpio) { const rtc_gpio_desc_t* desc = &rtc_gpio_desc[gpio]; if (desc->hold_force != 0) { REG_CLR_BIT(RTC_CNTL_HOLD_FORCE_REG, desc->hold_force); } } } esp_err_t rtc_gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type) { int rtc_num = rtc_gpio_desc[gpio_num].rtc_num; if (rtc_num < 0) { return ESP_ERR_INVALID_ARG; } if (( intr_type != GPIO_INTR_LOW_LEVEL ) && ( intr_type != GPIO_INTR_HIGH_LEVEL )) { return ESP_ERR_INVALID_ARG; } uint32_t reg = RTC_GPIO_PIN0_REG + rtc_num * sizeof(uint32_t); /* each pin has its own register, spinlock not needed */ REG_SET_BIT(reg, RTC_GPIO_PIN0_WAKEUP_ENABLE); REG_SET_FIELD(reg, RTC_GPIO_PIN0_INT_TYPE, intr_type); return ESP_OK; } esp_err_t rtc_gpio_wakeup_disable(gpio_num_t gpio_num) { int rtc_num = rtc_gpio_desc[gpio_num].rtc_num; if (rtc_num < 0) { return ESP_ERR_INVALID_ARG; } uint32_t reg = RTC_GPIO_PIN0_REG + rtc_num * sizeof(uint32_t); /* each pin has its own register, spinlock not needed */ REG_CLR_BIT(reg, RTC_GPIO_PIN0_WAKEUP_ENABLE); REG_SET_FIELD(reg, RTC_GPIO_PIN0_INT_TYPE, 0); return ESP_OK; } /*--------------------------------------------------------------- Touch Pad ---------------------------------------------------------------*/ //Some register bits of touch sensor 8 and 9 are mismatched, we need to swap the bits. #define BITSWAP(data, n, m) (((data >> n) & 0x1) == ((data >> m) & 0x1) ? (data) : ((data) ^ ((0x1 <<n) | (0x1 << m)))) #define TOUCH_BITS_SWAP(v) BITSWAP(v, TOUCH_PAD_NUM8, TOUCH_PAD_NUM9) static esp_err_t _touch_pad_read(touch_pad_t touch_num, uint16_t *touch_value, touch_fsm_mode_t mode); //Some registers of touch sensor 8 and 9 are mismatched, we need to swap register index inline static touch_pad_t touch_pad_num_wrap(touch_pad_t touch_num) { if (touch_num == TOUCH_PAD_NUM8) { return TOUCH_PAD_NUM9; } else if (touch_num == TOUCH_PAD_NUM9) { return TOUCH_PAD_NUM8; } return touch_num; } esp_err_t touch_pad_isr_handler_register(void (*fn)(void *), void *arg, int no_use, intr_handle_t *handle_no_use) { RTC_MODULE_CHECK(fn, "Touch_Pad ISR null", ESP_ERR_INVALID_ARG); return rtc_isr_register(fn, arg, RTC_CNTL_TOUCH_INT_ST_M); } esp_err_t touch_pad_isr_register(intr_handler_t fn, void* arg) { RTC_MODULE_CHECK(fn, "Touch_Pad ISR null", ESP_ERR_INVALID_ARG); return rtc_isr_register(fn, arg, RTC_CNTL_TOUCH_INT_ST_M); } esp_err_t touch_pad_isr_deregister(intr_handler_t fn, void *arg) { return rtc_isr_deregister(fn, arg); } static esp_err_t touch_pad_get_io_num(touch_pad_t touch_num, gpio_num_t *gpio_num) { switch (touch_num) { case TOUCH_PAD_NUM0: *gpio_num = TOUCH_PAD_NUM0_GPIO_NUM; break; case TOUCH_PAD_NUM1: *gpio_num = TOUCH_PAD_NUM1_GPIO_NUM; break; case TOUCH_PAD_NUM2: *gpio_num = TOUCH_PAD_NUM2_GPIO_NUM; break; case TOUCH_PAD_NUM3: *gpio_num = TOUCH_PAD_NUM3_GPIO_NUM; break; case TOUCH_PAD_NUM4: *gpio_num = TOUCH_PAD_NUM4_GPIO_NUM; break; case TOUCH_PAD_NUM5: *gpio_num = TOUCH_PAD_NUM5_GPIO_NUM; break; case TOUCH_PAD_NUM6: *gpio_num = TOUCH_PAD_NUM6_GPIO_NUM; break; case TOUCH_PAD_NUM7: *gpio_num = TOUCH_PAD_NUM7_GPIO_NUM; break; case TOUCH_PAD_NUM8: *gpio_num = TOUCH_PAD_NUM8_GPIO_NUM; break; case TOUCH_PAD_NUM9: *gpio_num = TOUCH_PAD_NUM9_GPIO_NUM; break; default: return ESP_ERR_INVALID_ARG; } return ESP_OK; } static uint32_t _touch_filter_iir(uint32_t in_now, uint32_t out_last, uint32_t k) { if (k == 0) { return in_now; } else { uint32_t out_now = (in_now + (k - 1) * out_last) / k; return out_now; } } esp_err_t touch_pad_set_filter_read_cb(filter_cb_t read_cb) { s_filter_cb = read_cb; return ESP_OK; } static void touch_pad_filter_cb(void *arg) { static uint32_t s_filtered_temp[TOUCH_PAD_MAX] = {0}; if (s_touch_pad_filter == NULL || rtc_touch_mux == NULL) { return; } uint16_t val = 0; touch_fsm_mode_t mode; xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); touch_pad_get_fsm_mode(&mode); for (int i = 0; i < TOUCH_PAD_MAX; i++) { if ((s_touch_pad_init_bit >> i) & 0x1) { _touch_pad_read(i, &val, mode); s_touch_pad_filter->raw_val[i] = val; s_filtered_temp[i] = s_filtered_temp[i] == 0 ? ((uint32_t)val << TOUCH_PAD_SHIFT_DEFAULT) : s_filtered_temp[i]; s_filtered_temp[i] = _touch_filter_iir((val << TOUCH_PAD_SHIFT_DEFAULT), s_filtered_temp[i], TOUCH_PAD_FILTER_FACTOR_DEFAULT); s_touch_pad_filter->filtered_val[i] = (s_filtered_temp[i] + TOUCH_PAD_SHIFT_ROUND_DEFAULT) >> TOUCH_PAD_SHIFT_DEFAULT; } } xTimerReset(s_touch_pad_filter->timer, portMAX_DELAY); xSemaphoreGive(rtc_touch_mux); if(s_filter_cb != NULL) { //return the raw data and filtered data. s_filter_cb(s_touch_pad_filter->raw_val, s_touch_pad_filter->filtered_val); } } esp_err_t touch_pad_set_meas_time(uint16_t sleep_cycle, uint16_t meas_cycle) { xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); portENTER_CRITICAL(&rtc_spinlock); //touch sensor sleep cycle Time = sleep_cycle / RTC_SLOW_CLK( can be 150k or 32k depending on the options) SENS.sar_touch_ctrl2.touch_sleep_cycles = sleep_cycle; //touch sensor measure time= meas_cycle / 8Mhz SENS.sar_touch_ctrl1.touch_meas_delay = meas_cycle; //the waiting cycles (in 8MHz) between TOUCH_START and TOUCH_XPD SENS.sar_touch_ctrl1.touch_xpd_wait = TOUCH_PAD_MEASURE_WAIT_DEFAULT; portEXIT_CRITICAL(&rtc_spinlock); xSemaphoreGive(rtc_touch_mux); return ESP_OK; } esp_err_t touch_pad_get_meas_time(uint16_t *sleep_cycle, uint16_t *meas_cycle) { portENTER_CRITICAL(&rtc_spinlock); if (sleep_cycle) { *sleep_cycle = SENS.sar_touch_ctrl2.touch_sleep_cycles; } if (meas_cycle) { *meas_cycle = SENS.sar_touch_ctrl1.touch_meas_delay; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_set_voltage(touch_high_volt_t refh, touch_low_volt_t refl, touch_volt_atten_t atten) { RTC_MODULE_CHECK(((refh < TOUCH_HVOLT_MAX) && (refh >= (int )TOUCH_HVOLT_KEEP)), "touch refh error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(((refl < TOUCH_LVOLT_MAX) && (refh >= (int )TOUCH_LVOLT_KEEP)), "touch refl error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(((atten < TOUCH_HVOLT_ATTEN_MAX) && (refh >= (int )TOUCH_HVOLT_ATTEN_KEEP)), "touch atten error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); if (refh > TOUCH_HVOLT_KEEP) { RTCIO.touch_cfg.drefh = refh; } if (refl > TOUCH_LVOLT_KEEP) { RTCIO.touch_cfg.drefl = refl; } if (atten > TOUCH_HVOLT_ATTEN_KEEP) { RTCIO.touch_cfg.drange = atten; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_get_voltage(touch_high_volt_t *refh, touch_low_volt_t *refl, touch_volt_atten_t *atten) { portENTER_CRITICAL(&rtc_spinlock); if (refh) { *refh = RTCIO.touch_cfg.drefh; } if (refl) { *refl = RTCIO.touch_cfg.drefl; } if (atten) { *atten = RTCIO.touch_cfg.drange; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_set_cnt_mode(touch_pad_t touch_num, touch_cnt_slope_t slope, touch_tie_opt_t opt) { RTC_MODULE_CHECK((slope < TOUCH_PAD_SLOPE_MAX), "touch slope error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK((opt < TOUCH_PAD_TIE_OPT_MAX), "touch opt error", ESP_ERR_INVALID_ARG); touch_pad_t touch_pad_wrap = touch_pad_num_wrap(touch_num); portENTER_CRITICAL(&rtc_spinlock); RTCIO.touch_pad[touch_pad_wrap].tie_opt = opt; RTCIO.touch_pad[touch_num].dac = slope; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_get_cnt_mode(touch_pad_t touch_num, touch_cnt_slope_t *slope, touch_tie_opt_t *opt) { RTC_MODULE_CHECK((touch_num < TOUCH_PAD_MAX), "touch IO error", ESP_ERR_INVALID_ARG); touch_pad_t touch_pad_wrap = touch_pad_num_wrap(touch_num); portENTER_CRITICAL(&rtc_spinlock); if(opt) { *opt = RTCIO.touch_pad[touch_pad_wrap].tie_opt; } if(slope) { *slope = RTCIO.touch_pad[touch_num].dac; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_io_init(touch_pad_t touch_num) { RTC_MODULE_CHECK((touch_num < TOUCH_PAD_MAX), "touch IO error", ESP_ERR_INVALID_ARG); gpio_num_t gpio_num = GPIO_NUM_0; touch_pad_get_io_num(touch_num, &gpio_num); rtc_gpio_init(gpio_num); rtc_gpio_set_direction(gpio_num, RTC_GPIO_MODE_DISABLED); rtc_gpio_pulldown_dis(gpio_num); rtc_gpio_pullup_dis(gpio_num); return ESP_OK; } esp_err_t touch_pad_set_fsm_mode(touch_fsm_mode_t mode) { RTC_MODULE_CHECK((mode < TOUCH_FSM_MODE_MAX), "touch fsm mode error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); SENS.sar_touch_ctrl2.touch_start_en = 0; SENS.sar_touch_ctrl2.touch_start_force = mode; RTCCNTL.state0.touch_slp_timer_en = (mode == TOUCH_FSM_MODE_TIMER ? 1 : 0); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_get_fsm_mode(touch_fsm_mode_t *mode) { if (mode) { *mode = SENS.sar_touch_ctrl2.touch_start_force; } return ESP_OK; } esp_err_t touch_pad_sw_start() { portENTER_CRITICAL(&rtc_spinlock); SENS.sar_touch_ctrl2.touch_start_en = 0; SENS.sar_touch_ctrl2.touch_start_en = 1; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_set_thresh(touch_pad_t touch_num, uint16_t threshold) { RTC_MODULE_CHECK((touch_num < TOUCH_PAD_MAX), "touch IO error", ESP_ERR_INVALID_ARG); touch_pad_t tp_wrap = touch_pad_num_wrap(touch_num); portENTER_CRITICAL(&rtc_spinlock); if (tp_wrap & 0x1) { SENS.touch_thresh[tp_wrap / 2].l_thresh = threshold; } else { SENS.touch_thresh[tp_wrap / 2].h_thresh = threshold; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_get_thresh(touch_pad_t touch_num, uint16_t *threshold) { RTC_MODULE_CHECK((touch_num < TOUCH_PAD_MAX), "touch IO error", ESP_ERR_INVALID_ARG); touch_pad_t tp_wrap = touch_pad_num_wrap(touch_num); if (threshold) { *threshold = (tp_wrap & 0x1 )? \ SENS.touch_thresh[tp_wrap / 2].l_thresh : \ SENS.touch_thresh[tp_wrap / 2].h_thresh; } return ESP_OK; } esp_err_t touch_pad_set_trigger_mode(touch_trigger_mode_t mode) { RTC_MODULE_CHECK((mode < TOUCH_TRIGGER_MAX), "touch trigger mode error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); SENS.sar_touch_ctrl1.touch_out_sel = mode; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_get_trigger_mode(touch_trigger_mode_t *mode) { if (mode) { *mode = SENS.sar_touch_ctrl1.touch_out_sel; } return ESP_OK; } esp_err_t touch_pad_set_trigger_source(touch_trigger_src_t src) { RTC_MODULE_CHECK((src < TOUCH_TRIGGER_SOURCE_MAX), "touch trigger source error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); SENS.sar_touch_ctrl1.touch_out_1en = src; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_get_trigger_source(touch_trigger_src_t *src) { if (src) { *src = SENS.sar_touch_ctrl1.touch_out_1en; } return ESP_OK; } esp_err_t touch_pad_set_group_mask(uint16_t set1_mask, uint16_t set2_mask, uint16_t en_mask) { RTC_MODULE_CHECK((set1_mask <= TOUCH_PAD_BIT_MASK_MAX), "touch set1 bitmask error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK((set2_mask <= TOUCH_PAD_BIT_MASK_MAX), "touch set2 bitmask error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK((en_mask <= TOUCH_PAD_BIT_MASK_MAX), "touch work_en bitmask error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); SENS.sar_touch_enable.touch_pad_outen1 |= TOUCH_BITS_SWAP(set1_mask); SENS.sar_touch_enable.touch_pad_outen2 |= TOUCH_BITS_SWAP(set2_mask); SENS.sar_touch_enable.touch_pad_worken |= TOUCH_BITS_SWAP(en_mask); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_get_group_mask(uint16_t *set1_mask, uint16_t *set2_mask, uint16_t *en_mask) { portENTER_CRITICAL(&rtc_spinlock); if (set1_mask) { *set1_mask = TOUCH_BITS_SWAP(SENS.sar_touch_enable.touch_pad_outen1); } if (set2_mask) { *set2_mask = TOUCH_BITS_SWAP(SENS.sar_touch_enable.touch_pad_outen2); } if (en_mask) { *en_mask = TOUCH_BITS_SWAP(SENS.sar_touch_enable.touch_pad_worken); } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_clear_group_mask(uint16_t set1_mask, uint16_t set2_mask, uint16_t en_mask) { RTC_MODULE_CHECK((set1_mask <= TOUCH_PAD_BIT_MASK_MAX), "touch set1 bitmask error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK((set2_mask <= TOUCH_PAD_BIT_MASK_MAX), "touch set2 bitmask error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK((en_mask <= TOUCH_PAD_BIT_MASK_MAX), "touch work_en bitmask error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); SENS.sar_touch_enable.touch_pad_outen1 &= TOUCH_BITS_SWAP(~set1_mask); SENS.sar_touch_enable.touch_pad_outen2 &= TOUCH_BITS_SWAP(~set2_mask); SENS.sar_touch_enable.touch_pad_worken &= TOUCH_BITS_SWAP(~en_mask); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } uint32_t IRAM_ATTR touch_pad_get_status() { uint32_t status = SENS.sar_touch_ctrl2.touch_meas_en; return TOUCH_BITS_SWAP(status); } esp_err_t IRAM_ATTR touch_pad_clear_status() { portENTER_CRITICAL(&rtc_spinlock); SENS.sar_touch_ctrl2.touch_meas_en_clr = 1; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_intr_enable() { portENTER_CRITICAL(&rtc_spinlock); RTCCNTL.int_ena.rtc_touch = 1; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_intr_disable() { portENTER_CRITICAL(&rtc_spinlock); RTCCNTL.int_ena.rtc_touch = 0; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t touch_pad_config(touch_pad_t touch_num, uint16_t threshold) { RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_FAIL); RTC_MODULE_CHECK(touch_num < TOUCH_PAD_MAX, "Touch_Pad Num Err", ESP_ERR_INVALID_ARG); touch_fsm_mode_t mode; touch_pad_set_thresh(touch_num, threshold); touch_pad_io_init(touch_num); touch_pad_set_cnt_mode(touch_num, TOUCH_PAD_SLOPE_7, TOUCH_PAD_TIE_OPT_LOW); touch_pad_get_fsm_mode(&mode); if (TOUCH_FSM_MODE_SW == mode) { touch_pad_clear_group_mask((1 << touch_num), (1 << touch_num), (1 << touch_num)); s_touch_pad_init_bit |= (1 << touch_num); } else if (TOUCH_FSM_MODE_TIMER == mode){ uint16_t sleep_time = 0; uint16_t meas_cycle = 0; uint32_t wait_time_ms = 0; uint32_t wait_tick = 0; uint32_t rtc_clk = rtc_clk_slow_freq_get_hz(); touch_pad_set_group_mask((1 << touch_num), (1 << touch_num), (1 << touch_num)); touch_pad_get_meas_time(&sleep_time, &meas_cycle); //If the FSM mode is 'TOUCH_FSM_MODE_TIMER', The data will be ready after one measurement cycle //after this function is executed, otherwise, the "touch_value" by "touch_pad_read" is 0. wait_time_ms = sleep_time/(rtc_clk/1000) + meas_cycle/(RTC_FAST_CLK_FREQ_APPROX/1000); wait_tick = wait_time_ms/portTICK_RATE_MS; vTaskDelay(wait_tick ? wait_tick : 1); s_touch_pad_init_bit |= (1 << touch_num); } else { return ESP_FAIL; } return ESP_OK; } esp_err_t touch_pad_init() { if (rtc_touch_mux == NULL) { rtc_touch_mux = xSemaphoreCreateMutex(); } if (rtc_touch_mux == NULL) { return ESP_FAIL; } touch_pad_intr_disable(); touch_pad_clear_group_mask(TOUCH_PAD_BIT_MASK_MAX, TOUCH_PAD_BIT_MASK_MAX, TOUCH_PAD_BIT_MASK_MAX); touch_pad_set_trigger_mode(TOUCH_TRIGGER_MODE_DEFAULT); touch_pad_set_trigger_source(TOUCH_TRIGGER_SOURCE_DEFAULT); touch_pad_clear_status(); touch_pad_set_meas_time(TOUCH_PAD_SLEEP_CYCLE_DEFAULT, TOUCH_PAD_MEASURE_CYCLE_DEFAULT); touch_pad_set_fsm_mode(TOUCH_FSM_MODE_DEFAULT); return ESP_OK; } esp_err_t touch_pad_deinit() { RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_FAIL); if (s_touch_pad_filter != NULL) { touch_pad_filter_stop(); touch_pad_filter_delete(); } xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); s_touch_pad_init_bit = 0x0000; touch_pad_set_fsm_mode(TOUCH_FSM_MODE_SW); touch_pad_clear_status(); touch_pad_intr_disable(); xSemaphoreGive(rtc_touch_mux); vSemaphoreDelete(rtc_touch_mux); rtc_touch_mux = NULL; return ESP_OK; } static esp_err_t _touch_pad_read(touch_pad_t touch_num, uint16_t *touch_value, touch_fsm_mode_t mode) { esp_err_t res = ESP_OK; touch_pad_t tp_wrap = touch_pad_num_wrap(touch_num); if (TOUCH_FSM_MODE_SW == mode) { touch_pad_set_group_mask((1 << touch_num), (1 << touch_num), (1 << touch_num)); touch_pad_sw_start(); while (SENS.sar_touch_ctrl2.touch_meas_done == 0) {}; *touch_value = (tp_wrap & 0x1) ? \ SENS.touch_meas[tp_wrap / 2].l_val: \ SENS.touch_meas[tp_wrap / 2].h_val; touch_pad_clear_group_mask((1 << touch_num), (1 << touch_num), (1 << touch_num)); } else if (TOUCH_FSM_MODE_TIMER == mode) { while (SENS.sar_touch_ctrl2.touch_meas_done == 0) {}; *touch_value = (tp_wrap & 0x1) ? \ SENS.touch_meas[tp_wrap / 2].l_val: \ SENS.touch_meas[tp_wrap / 2].h_val; } else { res = ESP_FAIL; } if (*touch_value == 0) { res = ESP_ERR_INVALID_STATE; } return res; } esp_err_t touch_pad_read(touch_pad_t touch_num, uint16_t *touch_value) { RTC_MODULE_CHECK(touch_num < TOUCH_PAD_MAX, "Touch_Pad Num Err", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(touch_value != NULL, "touch_value", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_FAIL); esp_err_t res = ESP_OK; touch_fsm_mode_t mode; touch_pad_get_fsm_mode(&mode); xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); res = _touch_pad_read(touch_num, touch_value, mode); xSemaphoreGive(rtc_touch_mux); return res; } IRAM_ATTR esp_err_t touch_pad_read_raw_data(touch_pad_t touch_num, uint16_t *touch_value) { RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_FAIL); RTC_MODULE_CHECK(touch_num < TOUCH_PAD_MAX, "Touch_Pad Num Err", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(touch_value != NULL, "touch_value", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(s_touch_pad_filter != NULL, "Touch pad filter not initialized", ESP_FAIL); *touch_value = s_touch_pad_filter->raw_val[touch_num]; if (*touch_value == 0) { return ESP_ERR_INVALID_STATE; } return ESP_OK; } IRAM_ATTR esp_err_t touch_pad_read_filtered(touch_pad_t touch_num, uint16_t *touch_value) { RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_FAIL); RTC_MODULE_CHECK(touch_num < TOUCH_PAD_MAX, "Touch_Pad Num Err", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(touch_value != NULL, "touch_value", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(s_touch_pad_filter != NULL, "Touch pad filter not initialized", ESP_FAIL); *touch_value = (s_touch_pad_filter->filtered_val[touch_num]); if (*touch_value == 0) { return ESP_ERR_INVALID_STATE; } return ESP_OK; } esp_err_t touch_pad_set_filter_period(uint32_t new_period_ms) { RTC_MODULE_CHECK(s_touch_pad_filter != NULL, "Touch pad filter not initialized", ESP_ERR_INVALID_STATE); RTC_MODULE_CHECK(new_period_ms > 0, "Touch pad filter period error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_ERR_INVALID_STATE); esp_err_t ret = ESP_OK; xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); if (s_touch_pad_filter != NULL) { xTimerChangePeriod(s_touch_pad_filter->timer, new_period_ms / portTICK_PERIOD_MS, portMAX_DELAY); s_touch_pad_filter->period = new_period_ms; } else { ESP_LOGE(RTC_MODULE_TAG, "Touch pad filter deleted"); ret = ESP_ERR_INVALID_STATE; } xSemaphoreGive(rtc_touch_mux); return ret; } esp_err_t touch_pad_get_filter_period(uint32_t* p_period_ms) { RTC_MODULE_CHECK(s_touch_pad_filter != NULL, "Touch pad filter not initialized", ESP_ERR_INVALID_STATE); RTC_MODULE_CHECK(p_period_ms != NULL, "Touch pad period pointer error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_ERR_INVALID_STATE); esp_err_t ret = ESP_OK; xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); if (s_touch_pad_filter != NULL) { *p_period_ms = s_touch_pad_filter->period; } else { ESP_LOGE(RTC_MODULE_TAG, "Touch pad filter deleted"); ret = ESP_ERR_INVALID_STATE; } xSemaphoreGive(rtc_touch_mux); return ret; } esp_err_t touch_pad_filter_start(uint32_t filter_period_ms) { RTC_MODULE_CHECK(filter_period_ms >= portTICK_PERIOD_MS, "Touch pad filter period error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_ERR_INVALID_STATE); esp_err_t ret = ESP_OK; xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); if (s_touch_pad_filter == NULL) { s_touch_pad_filter = (touch_pad_filter_t *) calloc(1, sizeof(touch_pad_filter_t)); if (s_touch_pad_filter == NULL) { ret = ESP_ERR_NO_MEM; } } if (s_touch_pad_filter->timer == NULL) { s_touch_pad_filter->timer = xTimerCreate("filter_tmr", filter_period_ms / portTICK_PERIOD_MS, pdFALSE, NULL, touch_pad_filter_cb); if (s_touch_pad_filter->timer == NULL) { ret = ESP_ERR_NO_MEM; } s_touch_pad_filter->period = filter_period_ms; } xSemaphoreGive(rtc_touch_mux); touch_pad_filter_cb(NULL); return ret; } esp_err_t touch_pad_filter_stop() { RTC_MODULE_CHECK(s_touch_pad_filter != NULL, "Touch pad filter not initialized", ESP_ERR_INVALID_STATE); RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_ERR_INVALID_STATE); esp_err_t ret = ESP_OK; xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); if (s_touch_pad_filter != NULL) { xTimerStop(s_touch_pad_filter->timer, portMAX_DELAY); } else { ESP_LOGE(RTC_MODULE_TAG, "Touch pad filter deleted"); ret = ESP_ERR_INVALID_STATE; } xSemaphoreGive(rtc_touch_mux); return ret; } esp_err_t touch_pad_filter_delete() { RTC_MODULE_CHECK(s_touch_pad_filter != NULL, "Touch pad filter not initialized", ESP_ERR_INVALID_STATE); RTC_MODULE_CHECK(rtc_touch_mux != NULL, "Touch pad not initialized", ESP_ERR_INVALID_STATE); xSemaphoreTake(rtc_touch_mux, portMAX_DELAY); if (s_touch_pad_filter != NULL) { if (s_touch_pad_filter->timer != NULL) { xTimerStop(s_touch_pad_filter->timer, portMAX_DELAY); xTimerDelete(s_touch_pad_filter->timer, portMAX_DELAY); s_touch_pad_filter->timer = NULL; } free(s_touch_pad_filter); s_touch_pad_filter = NULL; } xSemaphoreGive(rtc_touch_mux); return ESP_OK; } esp_err_t touch_pad_get_wakeup_status(touch_pad_t *pad_num) { uint32_t touch_mask = SENS.sar_touch_ctrl2.touch_meas_en; if(touch_mask == 0) { return ESP_FAIL; } *pad_num = touch_pad_num_wrap((touch_pad_t)(__builtin_ffs(touch_mask) - 1)); return ESP_OK; } /*--------------------------------------------------------------- ADC Common ---------------------------------------------------------------*/ static esp_err_t adc_set_fsm_time(int rst_wait, int start_wait, int standby_wait, int sample_cycle) { portENTER_CRITICAL(&rtc_spinlock); // Internal FSM reset wait time if (rst_wait >= 0) { SYSCON.saradc_fsm.rstb_wait = rst_wait; } // Internal FSM start wait time if (start_wait >= 0) { SYSCON.saradc_fsm.start_wait = start_wait; } // Internal FSM standby wait time if (standby_wait >= 0) { SYSCON.saradc_fsm.standby_wait = standby_wait; } // Internal FSM standby sample cycle if (sample_cycle >= 0) { SYSCON.saradc_fsm.sample_cycle = sample_cycle; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } static esp_err_t adc_set_data_format(adc_i2s_encode_t mode) { portENTER_CRITICAL(&rtc_spinlock); //data format: //0: ADC_ENCODE_12BIT [15:12]-channel [11:0]-12 bits ADC data //1: ADC_ENCODE_11BIT [15]-1 [14:11]-channel [10:0]-11 bits ADC data, the resolution should not be larger than 11 bits in this case. SYSCON.saradc_ctrl.data_sar_sel = mode; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } static esp_err_t adc_set_measure_limit(uint8_t meas_num, bool lim_en) { portENTER_CRITICAL(&rtc_spinlock); // Set max measure number SYSCON.saradc_ctrl2.max_meas_num = meas_num; // Enable max measure number limit SYSCON.saradc_ctrl2.meas_num_limit = lim_en; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } static esp_err_t adc_set_work_mode(adc_unit_t adc_unit) { portENTER_CRITICAL(&rtc_spinlock); if (adc_unit == ADC_UNIT_1) { // saradc mode sel : 0--single saradc; 1--double saradc; 2--alternative saradc SYSCON.saradc_ctrl.work_mode = 0; //ENABLE ADC 0: ADC1 1: ADC2, only work for single SAR mode SYSCON.saradc_ctrl.sar_sel = 0; } else if (adc_unit == ADC_UNIT_2) { // saradc mode sel : 0--single saradc; 1--double saradc; 2--alternative saradc SYSCON.saradc_ctrl.work_mode = 0; //ENABLE ADC1 0: SAR1 1: SAR2 only work for single SAR mode SYSCON.saradc_ctrl.sar_sel = 1; } else if (adc_unit == ADC_UNIT_BOTH) { // saradc mode sel : 0--single saradc; 1--double saradc; 2--alternative saradc SYSCON.saradc_ctrl.work_mode = 1; } else if (adc_unit == ADC_UNIT_ALTER) { // saradc mode sel : 0--single saradc; 1--double saradc; 2--alternative saradc SYSCON.saradc_ctrl.work_mode = 2; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } static esp_err_t adc_set_atten(adc_unit_t adc_unit, adc_channel_t channel, adc_atten_t atten) { ADC_CHECK_UNIT(adc_unit); if (adc_unit & ADC_UNIT_1) { RTC_MODULE_CHECK((adc1_channel_t)channel < ADC1_CHANNEL_MAX, "ADC Channel Err", ESP_ERR_INVALID_ARG); } RTC_MODULE_CHECK(atten < ADC_ATTEN_MAX, "ADC Atten Err", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); if (adc_unit & ADC_UNIT_1) { //SAR1_atten SET_PERI_REG_BITS(SENS_SAR_ATTEN1_REG, SENS_SAR1_ATTEN_VAL_MASK, atten, (channel * 2)); } if (adc_unit & ADC_UNIT_2) { //SAR2_atten SET_PERI_REG_BITS(SENS_SAR_ATTEN2_REG, SENS_SAR2_ATTEN_VAL_MASK, atten, (channel * 2)); } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } void adc_power_always_on() { portENTER_CRITICAL(&rtc_spinlock); SENS.sar_meas_wait2.force_xpd_sar = SENS_FORCE_XPD_SAR_PU; portEXIT_CRITICAL(&rtc_spinlock); } void adc_power_on() { portENTER_CRITICAL(&rtc_spinlock); //The power FSM controlled mode saves more power, while the ADC noise may get increased. #ifndef CONFIG_ADC_FORCE_XPD_FSM //Set the power always on to increase precision. SENS.sar_meas_wait2.force_xpd_sar = SENS_FORCE_XPD_SAR_PU; #else //Use the FSM to turn off the power while not used to save power. if (SENS.sar_meas_wait2.force_xpd_sar & SENS_FORCE_XPD_SAR_SW_M) { SENS.sar_meas_wait2.force_xpd_sar = SENS_FORCE_XPD_SAR_PU; } else { SENS.sar_meas_wait2.force_xpd_sar = SENS_FORCE_XPD_SAR_FSM; } #endif portEXIT_CRITICAL(&rtc_spinlock); } void adc_power_off() { portENTER_CRITICAL(&rtc_spinlock); //Bit1 0:Fsm 1: SW mode //Bit0 0:SW mode power down 1: SW mode power on SENS.sar_meas_wait2.force_xpd_sar = SENS_FORCE_XPD_SAR_PD; portEXIT_CRITICAL(&rtc_spinlock); } esp_err_t adc_set_clk_div(uint8_t clk_div) { portENTER_CRITICAL(&rtc_spinlock); // ADC clock devided from APB clk, 80 / 2 = 40Mhz, SYSCON.saradc_ctrl.sar_clk_div = clk_div; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t adc_set_i2s_data_source(adc_i2s_source_t src) { RTC_MODULE_CHECK(src < ADC_I2S_DATA_SRC_MAX, "ADC i2s data source error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); // 1: I2S input data is from SAR ADC (for DMA) 0: I2S input data is from GPIO matrix SYSCON.saradc_ctrl.data_to_i2s = src; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t adc_gpio_init(adc_unit_t adc_unit, adc_channel_t channel) { ADC_CHECK_UNIT(adc_unit); gpio_num_t gpio_num = 0; if (adc_unit & ADC_UNIT_1) { RTC_MODULE_CHECK((adc1_channel_t) channel < ADC1_CHANNEL_MAX, "ADC1 channel error", ESP_ERR_INVALID_ARG); ADC1_CHECK_FUNCTION_RET(adc1_pad_get_io_num((adc1_channel_t) channel, &gpio_num)); ADC1_CHECK_FUNCTION_RET(rtc_gpio_init(gpio_num)); ADC1_CHECK_FUNCTION_RET(rtc_gpio_output_disable(gpio_num)); ADC1_CHECK_FUNCTION_RET(rtc_gpio_input_disable(gpio_num)); ADC1_CHECK_FUNCTION_RET(gpio_set_pull_mode(gpio_num, GPIO_FLOATING)); } return ESP_OK; } esp_err_t adc_set_data_inv(adc_unit_t adc_unit, bool inv_en) { portENTER_CRITICAL(&rtc_spinlock); if (adc_unit & ADC_UNIT_1) { // Enable ADC data invert SENS.sar_read_ctrl.sar1_data_inv = inv_en; } if (adc_unit & ADC_UNIT_2) { // Enable ADC data invert SENS.sar_read_ctrl2.sar2_data_inv = inv_en; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t adc_set_data_width(adc_unit_t adc_unit, adc_bits_width_t bits) { ADC_CHECK_UNIT(adc_unit); RTC_MODULE_CHECK(bits < ADC_WIDTH_MAX, "ADC bit width error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); if (adc_unit & ADC_UNIT_1) { SENS.sar_start_force.sar1_bit_width = bits; SENS.sar_read_ctrl.sar1_sample_bit = bits; } if (adc_unit & ADC_UNIT_2) { SENS.sar_start_force.sar2_bit_width = bits; SENS.sar_read_ctrl2.sar2_sample_bit = bits; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } // this function should be called in the critical section static void adc_set_controller(adc_unit_t unit, adc_controller_t ctrl ) { if ( unit == ADC_UNIT_1 ) { switch( ctrl ) { case ADC_CTRL_RTC: SENS.sar_read_ctrl.sar1_dig_force = false; //RTC controller controls the ADC, not digital controller SENS.sar_meas_start1.meas1_start_force = true; //RTC controller controls the ADC,not ulp coprocessor SENS.sar_meas_start1.sar1_en_pad_force = true; //RTC controller controls the data port, not ulp coprocessor SENS.sar_touch_ctrl1.xpd_hall_force = true; // RTC controller controls the hall sensor power,not ulp coprocessor SENS.sar_touch_ctrl1.hall_phase_force = true; // RTC controller controls the hall sensor phase,not ulp coprocessor break; case ADC_CTRL_ULP: SENS.sar_read_ctrl.sar1_dig_force = false; SENS.sar_meas_start1.meas1_start_force = false; SENS.sar_meas_start1.sar1_en_pad_force = false; SENS.sar_touch_ctrl1.xpd_hall_force = false; SENS.sar_touch_ctrl1.hall_phase_force = false; break; case ADC_CTRL_DIG: SENS.sar_read_ctrl.sar1_dig_force = true; SENS.sar_meas_start1.meas1_start_force = true; SENS.sar_meas_start1.sar1_en_pad_force = true; SENS.sar_touch_ctrl1.xpd_hall_force = true; SENS.sar_touch_ctrl1.hall_phase_force = true; break; default: ESP_LOGE(TAG, "adc1 selects invalid controller"); break; } } else if ( unit == ADC_UNIT_2) { switch( ctrl ) { case ADC_CTRL_RTC: SENS.sar_meas_start2.meas2_start_force = true; //RTC controller controls the ADC,not ulp coprocessor SENS.sar_meas_start2.sar2_en_pad_force = true; //RTC controller controls the data port, not ulp coprocessor SENS.sar_read_ctrl2.sar2_dig_force = false; //RTC controller controls the ADC, not digital controller SENS.sar_read_ctrl2.sar2_pwdet_force = false; //RTC controller controls the ADC, not PWDET SYSCON.saradc_ctrl.sar2_mux = true; //RTC controller controls the ADC, not PWDET break; case ADC_CTRL_ULP: SENS.sar_meas_start2.meas2_start_force = false; SENS.sar_meas_start2.sar2_en_pad_force = false; SENS.sar_read_ctrl2.sar2_dig_force = false; SENS.sar_read_ctrl2.sar2_pwdet_force = false; SYSCON.saradc_ctrl.sar2_mux = true; break; case ADC_CTRL_DIG: SENS.sar_meas_start2.meas2_start_force = true; SENS.sar_meas_start2.sar2_en_pad_force = true; SENS.sar_read_ctrl2.sar2_dig_force = true; SENS.sar_read_ctrl2.sar2_pwdet_force = false; SYSCON.saradc_ctrl.sar2_mux = true; break; case ADC2_CTRL_PWDET: //currently only used by Wi-Fi SENS.sar_meas_start2.meas2_start_force = true; SENS.sar_meas_start2.sar2_en_pad_force = true; SENS.sar_read_ctrl2.sar2_dig_force = false; SENS.sar_read_ctrl2.sar2_pwdet_force = true; SYSCON.saradc_ctrl.sar2_mux = false; break; default: ESP_LOGE(TAG, "adc2 selects invalid controller"); break; } } else { ESP_LOGE(TAG, "invalid adc unit"); assert(0); } } // this function should be called in the critical section static int adc_convert( adc_unit_t unit, int channel) { uint16_t adc_value; if ( unit == ADC_UNIT_1 ) { SENS.sar_meas_start1.sar1_en_pad = (1 << channel); //only one channel is selected. while (SENS.sar_slave_addr1.meas_status != 0); SENS.sar_meas_start1.meas1_start_sar = 0; SENS.sar_meas_start1.meas1_start_sar = 1; while (SENS.sar_meas_start1.meas1_done_sar == 0); adc_value = SENS.sar_meas_start1.meas1_data_sar; } else if ( unit == ADC_UNIT_2 ) { SENS.sar_meas_start2.sar2_en_pad = (1 << channel); //only one channel is selected. SENS.sar_meas_start2.meas2_start_sar = 0; //start force 0 SENS.sar_meas_start2.meas2_start_sar = 1; //start force 1 while (SENS.sar_meas_start2.meas2_done_sar == 0) {}; //read done adc_value = SENS.sar_meas_start2.meas2_data_sar; } else { ESP_LOGE(TAG, "invalid adc unit"); return ESP_ERR_INVALID_ARG; } return adc_value; } /*------------------------------------------------------------------------------------- * ADC I2S *------------------------------------------------------------------------------------*/ static esp_err_t adc_set_i2s_data_len(adc_unit_t adc_unit, int patt_len) { ADC_CHECK_UNIT(adc_unit); RTC_MODULE_CHECK((patt_len < ADC_PATT_LEN_MAX) && (patt_len > 0), "ADC pattern length error", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); if(adc_unit & ADC_UNIT_1) { SYSCON.saradc_ctrl.sar1_patt_len = patt_len - 1; } if(adc_unit & ADC_UNIT_2) { SYSCON.saradc_ctrl.sar2_patt_len = patt_len - 1; } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } static esp_err_t adc_set_i2s_data_pattern(adc_unit_t adc_unit, int seq_num, adc_channel_t channel, adc_bits_width_t bits, adc_atten_t atten) { ADC_CHECK_UNIT(adc_unit); if (adc_unit & ADC_UNIT_1) { RTC_MODULE_CHECK((adc1_channel_t) channel < ADC1_CHANNEL_MAX, "ADC1 channel error", ESP_ERR_INVALID_ARG); } RTC_MODULE_CHECK(bits < ADC_WIDTH_MAX, "ADC bit width error", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(atten < ADC_ATTEN_MAX, "ADC Atten Err", ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); //Configure pattern table, each 8 bit defines one channel //[7:4]-channel [3:2]-bit width [1:0]- attenuation //BIT WIDTH: 3: 12BIT 2: 11BIT 1: 10BIT 0: 9BIT //ATTEN: 3: ATTEN = 11dB 2: 6dB 1: 2.5dB 0: 0dB uint8_t val = (channel << 4) | (bits << 2) | (atten << 0); if (adc_unit & ADC_UNIT_1) { SYSCON.saradc_sar1_patt_tab[seq_num / 4] &= (~(0xff << ((3 - (seq_num % 4)) * 8))); SYSCON.saradc_sar1_patt_tab[seq_num / 4] |= (val << ((3 - (seq_num % 4)) * 8)); } if (adc_unit & ADC_UNIT_2) { SYSCON.saradc_sar2_patt_tab[seq_num / 4] &= (~(0xff << ((3 - (seq_num % 4)) * 8))); SYSCON.saradc_sar2_patt_tab[seq_num / 4] |= (val << ((3 - (seq_num % 4)) * 8)); } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t adc_i2s_mode_init(adc_unit_t adc_unit, adc_channel_t channel) { ADC_CHECK_UNIT(adc_unit); if (adc_unit & ADC_UNIT_1) { RTC_MODULE_CHECK((adc1_channel_t) channel < ADC1_CHANNEL_MAX, "ADC1 channel error", ESP_ERR_INVALID_ARG); } uint8_t table_len = 1; //POWER ON SAR adc_power_always_on(); adc_gpio_init(adc_unit, channel); adc_set_i2s_data_len(adc_unit, table_len); adc_set_i2s_data_pattern(adc_unit, 0, channel, ADC_WIDTH_BIT_12, ADC_ATTEN_DB_11); portENTER_CRITICAL(&rtc_spinlock); if (adc_unit & ADC_UNIT_1) { adc_set_controller( ADC_UNIT_1, ADC_CTRL_DIG ); } if (adc_unit & ADC_UNIT_2) { adc_set_controller( ADC_UNIT_2, ADC_CTRL_DIG ); } portEXIT_CRITICAL(&rtc_spinlock); adc_set_i2s_data_source(ADC_I2S_DATA_SRC_ADC); adc_set_clk_div(SAR_ADC_CLK_DIV_DEFUALT); // Set internal FSM wait time. adc_set_fsm_time(ADC_FSM_RSTB_WAIT_DEFAULT, ADC_FSM_START_WAIT_DEFAULT, ADC_FSM_STANDBY_WAIT_DEFAULT, ADC_FSM_TIME_KEEP); adc_set_work_mode(adc_unit); adc_set_data_format(ADC_ENCODE_12BIT); adc_set_measure_limit(ADC_MAX_MEAS_NUM_DEFAULT, ADC_MEAS_NUM_LIM_DEFAULT); //Invert The Level, Invert SAR ADC1 data adc_set_data_inv(adc_unit, true); return ESP_OK; } /*------------------------------------------------------------------------------------- * ADC1 *------------------------------------------------------------------------------------*/ esp_err_t adc1_pad_get_io_num(adc1_channel_t channel, gpio_num_t *gpio_num) { RTC_MODULE_CHECK(channel < ADC1_CHANNEL_MAX, "ADC1 Channel Err", ESP_ERR_INVALID_ARG); switch (channel) { case ADC1_CHANNEL_0: *gpio_num = ADC1_CHANNEL_0_GPIO_NUM; break; case ADC1_CHANNEL_1: *gpio_num = ADC1_CHANNEL_1_GPIO_NUM; break; case ADC1_CHANNEL_2: *gpio_num = ADC1_CHANNEL_2_GPIO_NUM; break; case ADC1_CHANNEL_3: *gpio_num = ADC1_CHANNEL_3_GPIO_NUM; break; case ADC1_CHANNEL_4: *gpio_num = ADC1_CHANNEL_4_GPIO_NUM; break; case ADC1_CHANNEL_5: *gpio_num = ADC1_CHANNEL_5_GPIO_NUM; break; case ADC1_CHANNEL_6: *gpio_num = ADC1_CHANNEL_6_GPIO_NUM; break; case ADC1_CHANNEL_7: *gpio_num = ADC1_CHANNEL_7_GPIO_NUM; break; default: return ESP_ERR_INVALID_ARG; } return ESP_OK; } esp_err_t adc1_config_channel_atten(adc1_channel_t channel, adc_atten_t atten) { RTC_MODULE_CHECK(channel < ADC1_CHANNEL_MAX, "ADC Channel Err", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(atten < ADC_ATTEN_MAX, "ADC Atten Err", ESP_ERR_INVALID_ARG); adc_gpio_init(ADC_UNIT_1, channel); adc_set_atten(ADC_UNIT_1, channel, atten); return ESP_OK; } esp_err_t adc1_config_width(adc_bits_width_t width_bit) { RTC_MODULE_CHECK(width_bit < ADC_WIDTH_MAX, "ADC bit width error", ESP_ERR_INVALID_ARG); adc_set_data_width(ADC_UNIT_1, width_bit); adc_set_data_inv(ADC_UNIT_1, true); return ESP_OK; } static inline void adc1_fsm_disable() { //channel is set in the convert function SENS.sar_meas_wait2.force_xpd_amp = SENS_FORCE_XPD_AMP_PD; //disable FSM, it's only used by the LNA. SENS.sar_meas_ctrl.amp_rst_fb_fsm = 0; SENS.sar_meas_ctrl.amp_short_ref_fsm = 0; SENS.sar_meas_ctrl.amp_short_ref_gnd_fsm = 0; SENS.sar_meas_wait1.sar_amp_wait1 = 1; SENS.sar_meas_wait1.sar_amp_wait2 = 1; SENS.sar_meas_wait2.sar_amp_wait3 = 1; } esp_err_t adc1_i2s_mode_acquire() { //lazy initialization //for i2s, block until acquire the lock _lock_acquire( &adc1_i2s_lock ); ESP_LOGD( RTC_MODULE_TAG, "i2s mode takes adc1 lock." ); portENTER_CRITICAL(&rtc_spinlock); SENS.sar_meas_wait2.force_xpd_sar = SENS_FORCE_XPD_SAR_PU; //switch SARADC into DIG channel SENS.sar_read_ctrl.sar1_dig_force = 1; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t adc1_adc_mode_acquire() { //lazy initialization //for adc1, block until acquire the lock _lock_acquire( &adc1_i2s_lock ); portENTER_CRITICAL(&rtc_spinlock); // for now the WiFi would use ADC2 and set xpd_sar force on. // so we can not reset xpd_sar to fsm mode directly. // We should handle this after the synchronization mechanism is established. //switch SARADC into RTC channel SENS.sar_read_ctrl.sar1_dig_force = 0; portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t adc1_lock_release() { RTC_MODULE_CHECK((uint32_t*)adc1_i2s_lock != NULL, "adc1 lock release called before acquire", ESP_ERR_INVALID_STATE ); // for now the WiFi would use ADC2 and set xpd_sar force on. // so we can not reset xpd_sar to fsm mode directly. // We should handle this after the synchronization mechanism is established. _lock_release( &adc1_i2s_lock ); return ESP_OK; } int adc1_get_raw(adc1_channel_t channel) { uint16_t adc_value; RTC_MODULE_CHECK(channel < ADC1_CHANNEL_MAX, "ADC Channel Err", ESP_ERR_INVALID_ARG); adc1_adc_mode_acquire(); adc_power_on(); portENTER_CRITICAL(&rtc_spinlock); //disable other peripherals adc1_hall_enable(false); adc1_fsm_disable(); //currently the LNA is not open, close it by default //set controller adc_set_controller( ADC_UNIT_1, ADC_CTRL_RTC ); //start conversion adc_value = adc_convert( ADC_UNIT_1, channel ); portEXIT_CRITICAL(&rtc_spinlock); adc1_lock_release(); return adc_value; } int adc1_get_voltage(adc1_channel_t channel) //Deprecated. Use adc1_get_raw() instead { return adc1_get_raw(channel); } void adc1_ulp_enable(void) { adc_power_on(); portENTER_CRITICAL(&rtc_spinlock); adc_set_controller( ADC_UNIT_1, ADC_CTRL_ULP ); // since most users do not need LNA and HALL with uLP, we disable them here // open them in the uLP if needed. adc1_fsm_disable(); adc1_hall_enable(false); portEXIT_CRITICAL(&rtc_spinlock); } /*--------------------------------------------------------------- ADC2 ---------------------------------------------------------------*/ esp_err_t adc2_pad_get_io_num(adc2_channel_t channel, gpio_num_t *gpio_num) { RTC_MODULE_CHECK(channel < ADC2_CHANNEL_MAX, "ADC2 Channel Err", ESP_ERR_INVALID_ARG); switch (channel) { case ADC2_CHANNEL_0: *gpio_num = ADC2_CHANNEL_0_GPIO_NUM; break; case ADC2_CHANNEL_1: *gpio_num = ADC2_CHANNEL_1_GPIO_NUM; break; case ADC2_CHANNEL_2: *gpio_num = ADC2_CHANNEL_2_GPIO_NUM; break; case ADC2_CHANNEL_3: *gpio_num = ADC2_CHANNEL_3_GPIO_NUM; break; case ADC2_CHANNEL_4: *gpio_num = ADC2_CHANNEL_4_GPIO_NUM; break; case ADC2_CHANNEL_5: *gpio_num = ADC2_CHANNEL_5_GPIO_NUM; break; case ADC2_CHANNEL_6: *gpio_num = ADC2_CHANNEL_6_GPIO_NUM; break; case ADC2_CHANNEL_7: *gpio_num = ADC2_CHANNEL_7_GPIO_NUM; break; case ADC2_CHANNEL_8: *gpio_num = ADC2_CHANNEL_8_GPIO_NUM; break; case ADC2_CHANNEL_9: *gpio_num = ADC2_CHANNEL_9_GPIO_NUM; break; default: return ESP_ERR_INVALID_ARG; } return ESP_OK; } esp_err_t adc2_wifi_acquire() { //lazy initialization //for wifi, block until acquire the lock _lock_acquire( &adc2_wifi_lock ); ESP_LOGD( RTC_MODULE_TAG, "Wi-Fi takes adc2 lock." ); return ESP_OK; } esp_err_t adc2_wifi_release() { RTC_MODULE_CHECK((uint32_t*)adc2_wifi_lock != NULL, "wifi release called before acquire", ESP_ERR_INVALID_STATE ); _lock_release( &adc2_wifi_lock ); ESP_LOGD( RTC_MODULE_TAG, "Wi-Fi returns adc2 lock." ); return ESP_OK; } static esp_err_t adc2_pad_init(adc2_channel_t channel) { gpio_num_t gpio_num = 0; ADC2_CHECK_FUNCTION_RET(adc2_pad_get_io_num(channel, &gpio_num)); ADC2_CHECK_FUNCTION_RET(rtc_gpio_init(gpio_num)); ADC2_CHECK_FUNCTION_RET(rtc_gpio_output_disable(gpio_num)); ADC2_CHECK_FUNCTION_RET(rtc_gpio_input_disable(gpio_num)); ADC2_CHECK_FUNCTION_RET(gpio_set_pull_mode(gpio_num, GPIO_FLOATING)); return ESP_OK; } esp_err_t adc2_config_channel_atten(adc2_channel_t channel, adc_atten_t atten) { RTC_MODULE_CHECK(channel < ADC2_CHANNEL_MAX, "ADC2 Channel Err", ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(atten <= ADC_ATTEN_11db, "ADC2 Atten Err", ESP_ERR_INVALID_ARG); adc2_pad_init(channel); portENTER_CRITICAL( &adc2_spinlock ); //lazy initialization //avoid collision with other tasks if ( _lock_try_acquire( &adc2_wifi_lock ) == -1 ) { //try the lock, return if failed (wifi using). portEXIT_CRITICAL( &adc2_spinlock ); return ESP_ERR_TIMEOUT; } SENS.sar_atten2 = ( SENS.sar_atten2 & ~(3<<(channel*2)) ) | ((atten&3) << (channel*2)); _lock_release( &adc2_wifi_lock ); portEXIT_CRITICAL( &adc2_spinlock ); return ESP_OK; } static inline void adc2_config_width(adc_bits_width_t width_bit) { portENTER_CRITICAL(&rtc_spinlock); //sar_start_force shared with ADC1 SENS.sar_start_force.sar2_bit_width = width_bit; //cct set to the same value with PHY SENS.sar_start_force.sar2_pwdet_cct = 4; portEXIT_CRITICAL(&rtc_spinlock); //Invert the adc value,the Output value is invert SENS.sar_read_ctrl2.sar2_data_inv = 1; //Set The adc sample width,invert adc value,must digital sar2_bit_width[1:0]=3 SENS.sar_read_ctrl2.sar2_sample_bit = width_bit; } static inline void adc2_dac_disable( adc2_channel_t channel) { if ( channel == ADC2_CHANNEL_8 ) { // the same as DAC channel 1 dac_output_set_enable( DAC_CHANNEL_1, false ); } else if ( channel == ADC2_CHANNEL_9 ) { dac_output_set_enable( DAC_CHANNEL_2, false ); } } //registers in critical section with adc1: //SENS_SAR_START_FORCE_REG, esp_err_t adc2_get_raw(adc2_channel_t channel, adc_bits_width_t width_bit, int* raw_out) { uint16_t adc_value = 0; RTC_MODULE_CHECK(channel < ADC2_CHANNEL_MAX, "ADC Channel Err", ESP_ERR_INVALID_ARG); //in critical section with whole rtc module adc_power_on(); //avoid collision with other tasks portENTER_CRITICAL(&adc2_spinlock); //lazy initialization //try the lock, return if failed (wifi using). if ( _lock_try_acquire( &adc2_wifi_lock ) == -1 ) { portEXIT_CRITICAL( &adc2_spinlock ); return ESP_ERR_TIMEOUT; } //disable other peripherals #ifdef CONFIG_ADC2_DISABLE_DAC adc2_dac_disable( channel ); #endif // set controller // in critical section with whole rtc module // because the PWDET use the same registers, place it here. adc2_config_width( width_bit ); adc_set_controller( ADC_UNIT_2, ADC_CTRL_RTC ); //start converting adc_value = adc_convert( ADC_UNIT_2, channel ); _lock_release( &adc2_wifi_lock ); portEXIT_CRITICAL(&adc2_spinlock); *raw_out = (int)adc_value; return ESP_OK; } esp_err_t adc2_vref_to_gpio(gpio_num_t gpio) { int channel; if(gpio == GPIO_NUM_25){ channel = 8; //Channel 8 bit }else if (gpio == GPIO_NUM_26){ channel = 9; //Channel 9 bit }else if (gpio == GPIO_NUM_27){ channel = 7; //Channel 7 bit }else{ return ESP_ERR_INVALID_ARG; } //Configure RTC gpio rtc_gpio_init(gpio); rtc_gpio_output_disable(gpio); rtc_gpio_input_disable(gpio); rtc_gpio_pullup_dis(gpio); rtc_gpio_pulldown_dis(gpio); //force fsm adc_power_always_on(); //Select power source of ADC RTCCNTL.bias_conf.dbg_atten = 0; //Check DBG effect outside sleep mode //set dtest (MUX_SEL : 0 -> RTC; 1-> vdd_sar2) RTCCNTL.test_mux.dtest_rtc = 1; //Config test mux to route v_ref to ADC2 Channels //set ent RTCCNTL.test_mux.ent_rtc = 1; //set sar2_en_test SENS.sar_start_force.sar2_en_test = 1; //set sar2 en force SENS.sar_meas_start2.sar2_en_pad_force = 1; //Pad bitmap controlled by SW //set en_pad for channels 7,8,9 (bits 0x380) SENS.sar_meas_start2.sar2_en_pad = 1<<channel; return ESP_OK; } /*--------------------------------------------------------------- DAC ---------------------------------------------------------------*/ esp_err_t dac_pad_get_io_num(dac_channel_t channel, gpio_num_t *gpio_num) { RTC_MODULE_CHECK((channel >= DAC_CHANNEL_1) && (channel < DAC_CHANNEL_MAX), DAC_ERR_STR_CHANNEL_ERROR, ESP_ERR_INVALID_ARG); RTC_MODULE_CHECK(gpio_num, "Param null", ESP_ERR_INVALID_ARG); switch (channel) { case DAC_CHANNEL_1: *gpio_num = DAC_CHANNEL_1_GPIO_NUM; break; case DAC_CHANNEL_2: *gpio_num = DAC_CHANNEL_2_GPIO_NUM; break; default: return ESP_ERR_INVALID_ARG; } return ESP_OK; } static esp_err_t dac_rtc_pad_init(dac_channel_t channel) { RTC_MODULE_CHECK((channel >= DAC_CHANNEL_1) && (channel < DAC_CHANNEL_MAX), DAC_ERR_STR_CHANNEL_ERROR, ESP_ERR_INVALID_ARG); gpio_num_t gpio_num = 0; dac_pad_get_io_num(channel, &gpio_num); rtc_gpio_init(gpio_num); rtc_gpio_output_disable(gpio_num); rtc_gpio_input_disable(gpio_num); rtc_gpio_pullup_dis(gpio_num); rtc_gpio_pulldown_dis(gpio_num); return ESP_OK; } static inline void dac_output_set_enable(dac_channel_t channel, bool enable) { RTCIO.pad_dac[channel-DAC_CHANNEL_1].dac_xpd_force = enable; RTCIO.pad_dac[channel-DAC_CHANNEL_1].xpd_dac = enable; } esp_err_t dac_output_enable(dac_channel_t channel) { RTC_MODULE_CHECK((channel >= DAC_CHANNEL_1) && (channel < DAC_CHANNEL_MAX), DAC_ERR_STR_CHANNEL_ERROR, ESP_ERR_INVALID_ARG); dac_rtc_pad_init(channel); portENTER_CRITICAL(&rtc_spinlock); dac_output_set_enable(channel, true); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t dac_output_disable(dac_channel_t channel) { RTC_MODULE_CHECK((channel >= DAC_CHANNEL_1) && (channel < DAC_CHANNEL_MAX), DAC_ERR_STR_CHANNEL_ERROR, ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); dac_output_set_enable(channel, false); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t dac_output_voltage(dac_channel_t channel, uint8_t dac_value) { RTC_MODULE_CHECK((channel >= DAC_CHANNEL_1) && (channel < DAC_CHANNEL_MAX), DAC_ERR_STR_CHANNEL_ERROR, ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); //Disable Tone CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL1_REG, SENS_SW_TONE_EN); //Disable Channel Tone if (channel == DAC_CHANNEL_1) { CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL2_REG, SENS_DAC_CW_EN1_M); } else if (channel == DAC_CHANNEL_2) { CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL2_REG, SENS_DAC_CW_EN2_M); } //Set the Dac value if (channel == DAC_CHANNEL_1) { SET_PERI_REG_BITS(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_DAC, dac_value, RTC_IO_PDAC1_DAC_S); //dac_output } else if (channel == DAC_CHANNEL_2) { SET_PERI_REG_BITS(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_DAC, dac_value, RTC_IO_PDAC2_DAC_S); //dac_output } portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t dac_out_voltage(dac_channel_t channel, uint8_t dac_value) { RTC_MODULE_CHECK((channel >= DAC_CHANNEL_1) && (channel < DAC_CHANNEL_MAX), DAC_ERR_STR_CHANNEL_ERROR, ESP_ERR_INVALID_ARG); portENTER_CRITICAL(&rtc_spinlock); //Disable Tone CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL1_REG, SENS_SW_TONE_EN); //Disable Channel Tone if (channel == DAC_CHANNEL_1) { CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL2_REG, SENS_DAC_CW_EN1_M); } else if (channel == DAC_CHANNEL_2) { CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL2_REG, SENS_DAC_CW_EN2_M); } //Set the Dac value if (channel == DAC_CHANNEL_1) { SET_PERI_REG_BITS(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_DAC, dac_value, RTC_IO_PDAC1_DAC_S); //dac_output } else if (channel == DAC_CHANNEL_2) { SET_PERI_REG_BITS(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_DAC, dac_value, RTC_IO_PDAC2_DAC_S); //dac_output } portEXIT_CRITICAL(&rtc_spinlock); //dac pad init dac_rtc_pad_init(channel); dac_output_enable(channel); return ESP_OK; } esp_err_t dac_i2s_enable() { portENTER_CRITICAL(&rtc_spinlock); SET_PERI_REG_MASK(SENS_SAR_DAC_CTRL1_REG, SENS_DAC_DIG_FORCE_M | SENS_DAC_CLK_INV_M); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } esp_err_t dac_i2s_disable() { portENTER_CRITICAL(&rtc_spinlock); CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL1_REG, SENS_DAC_DIG_FORCE_M | SENS_DAC_CLK_INV_M); portEXIT_CRITICAL(&rtc_spinlock); return ESP_OK; } /*--------------------------------------------------------------- HALL SENSOR ---------------------------------------------------------------*/ static inline void adc1_hall_enable(bool enable) { RTCIO.hall_sens.xpd_hall = enable; } static int hall_sensor_get_value() //hall sensor without LNA { int Sens_Vp0; int Sens_Vn0; int Sens_Vp1; int Sens_Vn1; int hall_value; adc_power_on(); portENTER_CRITICAL(&rtc_spinlock); //disable other peripherals adc1_fsm_disable();//currently the LNA is not open, close it by default adc1_hall_enable(true); // set controller adc_set_controller( ADC_UNIT_1, ADC_CTRL_RTC ); // convert for 4 times with different phase and outputs RTCIO.hall_sens.hall_phase = 0; // hall phase Sens_Vp0 = adc_convert( ADC_UNIT_1, ADC1_CHANNEL_0 ); Sens_Vn0 = adc_convert( ADC_UNIT_1, ADC1_CHANNEL_3 ); RTCIO.hall_sens.hall_phase = 1; Sens_Vp1 = adc_convert( ADC_UNIT_1, ADC1_CHANNEL_0 ); Sens_Vn1 = adc_convert( ADC_UNIT_1, ADC1_CHANNEL_3 ); portEXIT_CRITICAL(&rtc_spinlock); hall_value = (Sens_Vp1 - Sens_Vp0) - (Sens_Vn1 - Sens_Vn0); return hall_value; } int hall_sensor_read() { adc_gpio_init(ADC_UNIT_1, ADC1_CHANNEL_0); adc_gpio_init(ADC_UNIT_1, ADC1_CHANNEL_3); adc1_config_channel_atten(ADC1_CHANNEL_0, ADC_ATTEN_DB_0); adc1_config_channel_atten(ADC1_CHANNEL_3, ADC_ATTEN_DB_0); return hall_sensor_get_value(); } /*--------------------------------------------------------------- INTERRUPT HANDLER ---------------------------------------------------------------*/ typedef struct rtc_isr_handler_ { uint32_t mask; intr_handler_t handler; void* handler_arg; SLIST_ENTRY(rtc_isr_handler_) next; } rtc_isr_handler_t; static SLIST_HEAD(rtc_isr_handler_list_, rtc_isr_handler_) s_rtc_isr_handler_list = SLIST_HEAD_INITIALIZER(s_rtc_isr_handler_list); portMUX_TYPE s_rtc_isr_handler_list_lock = portMUX_INITIALIZER_UNLOCKED; static intr_handle_t s_rtc_isr_handle; static void rtc_isr(void* arg) { uint32_t status = REG_READ(RTC_CNTL_INT_ST_REG); rtc_isr_handler_t* it; portENTER_CRITICAL_ISR(&s_rtc_isr_handler_list_lock); SLIST_FOREACH(it, &s_rtc_isr_handler_list, next) { if (it->mask & status) { portEXIT_CRITICAL_ISR(&s_rtc_isr_handler_list_lock); (*it->handler)(it->handler_arg); portENTER_CRITICAL_ISR(&s_rtc_isr_handler_list_lock); } } portEXIT_CRITICAL_ISR(&s_rtc_isr_handler_list_lock); REG_WRITE(RTC_CNTL_INT_CLR_REG, status); } static esp_err_t rtc_isr_ensure_installed() { esp_err_t err = ESP_OK; portENTER_CRITICAL(&s_rtc_isr_handler_list_lock); if (s_rtc_isr_handle) { goto out; } REG_WRITE(RTC_CNTL_INT_ENA_REG, 0); REG_WRITE(RTC_CNTL_INT_CLR_REG, UINT32_MAX); err = esp_intr_alloc(ETS_RTC_CORE_INTR_SOURCE, 0, &rtc_isr, NULL, &s_rtc_isr_handle); if (err != ESP_OK) { goto out; } out: portEXIT_CRITICAL(&s_rtc_isr_handler_list_lock); return err; } esp_err_t rtc_isr_register(intr_handler_t handler, void* handler_arg, uint32_t rtc_intr_mask) { esp_err_t err = rtc_isr_ensure_installed(); if (err != ESP_OK) { return err; } rtc_isr_handler_t* item = malloc(sizeof(*item)); if (item == NULL) { return ESP_ERR_NO_MEM; } item->handler = handler; item->handler_arg = handler_arg; item->mask = rtc_intr_mask; portENTER_CRITICAL(&s_rtc_isr_handler_list_lock); SLIST_INSERT_HEAD(&s_rtc_isr_handler_list, item, next); portEXIT_CRITICAL(&s_rtc_isr_handler_list_lock); return ESP_OK; } esp_err_t rtc_isr_deregister(intr_handler_t handler, void* handler_arg) { rtc_isr_handler_t* it; rtc_isr_handler_t* prev = NULL; bool found = false; portENTER_CRITICAL(&s_rtc_isr_handler_list_lock); SLIST_FOREACH(it, &s_rtc_isr_handler_list, next) { if (it->handler == handler && it->handler_arg == handler_arg) { if (it == SLIST_FIRST(&s_rtc_isr_handler_list)) { SLIST_REMOVE_HEAD(&s_rtc_isr_handler_list, next); } else { SLIST_REMOVE_AFTER(prev, next); } found = true; free(it); break; } prev = it; } portEXIT_CRITICAL(&s_rtc_isr_handler_list_lock); return found ? ESP_OK : ESP_ERR_INVALID_STATE; }
399902.c
/* * Copyright 1995-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 <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include "dh_locl.h" #include <openssl/engine.h> int DH_set_method(DH *dh, const DH_METHOD *meth) { /* * NB: The caller is specifically setting a method, so it's not up to us * to deal with which ENGINE it comes from. */ const DH_METHOD *mtmp; mtmp = dh->meth; if (mtmp->finish) mtmp->finish(dh); #ifndef OPENSSL_NO_ENGINE ENGINE_finish(dh->engine); dh->engine = NULL; #endif dh->meth = meth; if (meth->init) meth->init(dh); return 1; } DH *DH_new(void) { return DH_new_method(NULL); } DH *DH_new_method(ENGINE *engine) { DH *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) { DHerr(DH_F_DH_NEW_METHOD, ERR_R_MALLOC_FAILURE); return NULL; } ret->references = 1; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { DHerr(DH_F_DH_NEW_METHOD, ERR_R_MALLOC_FAILURE); OPENSSL_free(ret); return NULL; } ret->meth = DH_get_default_method(); #ifndef OPENSSL_NO_ENGINE ret->flags = ret->meth->flags; /* early default init */ if (engine) { if (!ENGINE_init(engine)) { DHerr(DH_F_DH_NEW_METHOD, ERR_R_ENGINE_LIB); goto err; } ret->engine = engine; } else ret->engine = ENGINE_get_default_DH(); if (ret->engine) { ret->meth = ENGINE_get_DH(ret->engine); if (ret->meth == NULL) { DHerr(DH_F_DH_NEW_METHOD, ERR_R_ENGINE_LIB); goto err; } } #endif ret->flags = ret->meth->flags; if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_DH, ret, &ret->ex_data)) goto err; if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { DHerr(DH_F_DH_NEW_METHOD, ERR_R_INIT_FAIL); err: DH_free(ret); ret = NULL; } return ret; } void DH_free(DH *r) { int i; if (r == NULL) return; CRYPTO_DOWN_REF(&r->references, &i, r->lock); REF_PRINT_COUNT("DH", r); if (i > 0) return; REF_ASSERT_ISNT(i < 0); if (r->meth->finish) r->meth->finish(r); #ifndef OPENSSL_NO_ENGINE ENGINE_finish(r->engine); #endif CRYPTO_free_ex_data(CRYPTO_EX_INDEX_DH, r, &r->ex_data); CRYPTO_THREAD_lock_free(r->lock); BN_clear_free(r->p); BN_clear_free(r->g); BN_clear_free(r->q); BN_clear_free(r->j); OPENSSL_free(r->seed); BN_clear_free(r->counter); BN_clear_free(r->pub_key); BN_clear_free(r->priv_key); OPENSSL_free(r); } int DH_up_ref(DH *r) { int i; if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0) return 0; REF_PRINT_COUNT("DH", r); REF_ASSERT_ISNT(i < 2); return ((i > 1) ? 1 : 0); } int DH_set_ex_data(DH *d, int idx, void *arg) { return (CRYPTO_set_ex_data(&d->ex_data, idx, arg)); } void *DH_get_ex_data(DH *d, int idx) { return (CRYPTO_get_ex_data(&d->ex_data, idx)); } int DH_bits(const DH *dh) { return BN_num_bits(dh->p); } int DH_size(const DH *dh) { return (BN_num_bytes(dh->p)); } int DH_security_bits(const DH *dh) { int N; if (dh->q) N = BN_num_bits(dh->q); else if (dh->length) N = dh->length; else N = -1; return BN_security_bits(BN_num_bits(dh->p), N); } void DH_get0_pqg(const DH *dh, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g) { if (p != NULL) *p = dh->p; if (q != NULL) *q = dh->q; if (g != NULL) *g = dh->g; } int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) { /* If the fields p and g in d are NULL, the corresponding input * parameters MUST be non-NULL. q may remain NULL. */ if ((dh->p == NULL && p == NULL) || (dh->g == NULL && g == NULL)) return 0; if (p != NULL) { BN_free(dh->p); dh->p = p; } if (q != NULL) { BN_free(dh->q); dh->q = q; } if (g != NULL) { BN_free(dh->g); dh->g = g; } if (q != NULL) { dh->length = BN_num_bits(q); } return 1; } long DH_get_length(const DH *dh) { return dh->length; } int DH_set_length(DH *dh, long length) { dh->length = length; return 1; } void DH_get0_key(const DH *dh, const BIGNUM **pub_key, const BIGNUM **priv_key) { if (pub_key != NULL) *pub_key = dh->pub_key; if (priv_key != NULL) *priv_key = dh->priv_key; } int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key) { /* If the field pub_key in dh is NULL, the corresponding input * parameters MUST be non-NULL. The priv_key field may * be left NULL. */ if (dh->pub_key == NULL && pub_key == NULL) return 0; if (pub_key != NULL) { BN_free(dh->pub_key); dh->pub_key = pub_key; } if (priv_key != NULL) { BN_free(dh->priv_key); dh->priv_key = priv_key; } return 1; } void DH_clear_flags(DH *dh, int flags) { dh->flags &= ~flags; } int DH_test_flags(const DH *dh, int flags) { return dh->flags & flags; } void DH_set_flags(DH *dh, int flags) { dh->flags |= flags; } ENGINE *DH_get0_engine(DH *dh) { return dh->engine; }
336140.c
/****************************************************************************** * * Copyright (C) 2011 - 2015 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. * * 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. * * * ******************************************************************************/ /****************************************************************************/ /** * * @file xiomodule_uart_intr.c * @addtogroup iomodule_v2_7 * @{ * * Contains required functions for the XIOModule UART driver interrupt mode. * See the xiomodule.h header file for more details on this driver. * * This file also contains interrupt-related functions for the UART. * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- ----------------------------------------------- * 1.03a sa 10/16/12 First release * 2.2 nsk 08/06/15 Updated XIOModule_Uart_InterruptHandler function * to read Status register instead of reading Interrupt * Pending register. * * </pre> * *****************************************************************************/ /***************************** Include Files ********************************/ #include "xil_assert.h" #include "xiomodule.h" #include "xiomodule_i.h" #include "xiomodule_l.h" /************************** Constant Definitions ****************************/ /**************************** Type Definitions ******************************/ /***************** Macros (Inline Functions) Definitions ********************/ /************************** Function Prototypes *****************************/ static void ReceiveDataHandler(XIOModule *InstancePtr); static void SendDataHandler(XIOModule *InstancePtr); /************************** Variable Definitions ****************************/ typedef void (*Handler)(XIOModule *InstancePtr); /****************************************************************************/ /** * * This functions sends the specified buffer of data using the UART in either * polled or interrupt driven modes. This function is non-blocking such that it * will return before the data has been sent by the UART. If the UART is busy * sending data, it will return and indicate zero bytes were sent. * * In a polled mode, this function will only send as much data as the UART can * buffer in the transmitter. The application may need to call it repeatedly to * send a buffer. * * In interrupt mode, this function will start sending the specified buffer and * then the interrupt handler of the driver will continue sending data until the * buffer has been sent. A callback function, as specified by the application, * will be called to indicate the completion of sending the buffer. * * @param InstancePtr is a pointer to the XIOModule instance. * @param DataBufferPtr is pointer to a buffer of data to be sent. * @param NumBytes contains the number of bytes to be sent. A value of * zero will stop a previous send operation that is in progress * in interrupt mode. Any data that was already put into the * transmit FIFO will be sent. * * @return The number of bytes actually sent. * * @note The number of bytes is not asserted so that this function may * be called with a value of zero to stop an operation that is * already in progress. * ******************************************************************************/ unsigned int XIOModule_Send(XIOModule *InstancePtr, u8 *DataBufferPtr, unsigned int NumBytes) { unsigned int BytesSent; u32 StatusRegister; /* * Assert validates the input arguments */ Xil_AssertNonvoid(InstancePtr != NULL); Xil_AssertNonvoid(DataBufferPtr != NULL); Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); Xil_AssertNonvoid(((signed)NumBytes) >= 0); /* * Enter a critical region by disabling the UART interrupts to allow * this call to stop a previous operation that may be interrupt driven. */ StatusRegister = InstancePtr->CurrentIER; XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, StatusRegister & 0xFFFFFFF8); /* * Setup the specified buffer to be sent by setting the instance * variables so it can be sent with polled or interrupt mode */ InstancePtr->SendBuffer.RequestedBytes = NumBytes; InstancePtr->SendBuffer.RemainingBytes = NumBytes; InstancePtr->SendBuffer.NextBytePtr = DataBufferPtr; /* * Restore the interrupt enable register to it's previous value such * that the critical region is exited. * This is done here to minimize the amount of time the interrupt is * disabled since there is only one interrupt and the receive could * be filling up while interrupts are blocked. */ XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, (InstancePtr->CurrentIER & 0xFFFFFFF8) | (StatusRegister & 0x7)); /* * Send the buffer using the UART and return the number of bytes sent */ BytesSent = XIOModule_SendBuffer(InstancePtr); return BytesSent; } /****************************************************************************/ /** * * This function will attempt to receive a specified number of bytes of data * from the UART and store it into the specified buffer. This function is * designed for either polled or interrupt driven modes. It is non-blocking * such that it will return if no data has already received by the UART. * * In a polled mode, this function will only receive as much data as the UART * can buffer in the receiver. The application may need to call it repeatedly to * receive a buffer. Polled mode is the default mode of operation for the driver. * * In interrupt mode, this function will start receiving and then the interrupt * handler of the driver will continue receiving data until the buffer has been * received. A callback function, as specified by the application, will be called * to indicate the completion of receiving the buffer or when any receive errors * or timeouts occur. * * @param InstancePtr is a pointer to the XIOModule instance. * @param DataBufferPtr is pointer to buffer for data to be received into. * @param NumBytes is the number of bytes to be received. A value of zero * will stop a previous receive operation that is in progress in * interrupt mode. * * @return The number of bytes received. * * @note The number of bytes is not asserted so that this function * may be called with a value of zero to stop an operation * that is already in progress. * *****************************************************************************/ unsigned int XIOModule_Recv(XIOModule *InstancePtr, u8 *DataBufferPtr, unsigned int NumBytes) { unsigned int ReceivedCount; u32 StatusRegister; /* * Assert validates the input arguments */ Xil_AssertNonvoid(InstancePtr != NULL); Xil_AssertNonvoid(DataBufferPtr != NULL); Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); Xil_AssertNonvoid(((signed)NumBytes) >= 0); /* * Enter a critical region by disabling all the UART interrupts to allow * this call to stop a previous operation that may be interrupt driven */ StatusRegister = InstancePtr->CurrentIER; XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, StatusRegister & 0xFFFFFFF8); /* * Setup the specified buffer to be received by setting the instance * variables so it can be received with polled or interrupt mode */ InstancePtr->ReceiveBuffer.RequestedBytes = NumBytes; InstancePtr->ReceiveBuffer.RemainingBytes = NumBytes; InstancePtr->ReceiveBuffer.NextBytePtr = DataBufferPtr; /* * Restore the interrupt enable register to it's previous value such * that the critical region is exited */ XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, (InstancePtr->CurrentIER & 0xFFFFFFF8) | (StatusRegister & 0x7)); /* * Receive the data from the UART and return the number of bytes * received. This is done here to minimize the amount of time the * interrupt is disabled. */ ReceivedCount = XIOModule_ReceiveBuffer(InstancePtr); return ReceivedCount; } /****************************************************************************/ /** * * This function does nothing, since the UART doesn't have any FIFOs. It is * included for compatibility with the UART Lite driver. * * @param InstancePtr is a pointer to the XIOModule instance . * * @return None. * * @note None. * *****************************************************************************/ void XIOModule_ResetFifos(XIOModule *InstancePtr) { Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); } /****************************************************************************/ /** * * This function determines if the specified UART is sending data. If the * transmitter register is not empty, it is sending data. * * @param InstancePtr is a pointer to the XIOModule instance. * * @return A value of TRUE if the UART is sending data, otherwise FALSE. * * @note None. * *****************************************************************************/ int XIOModule_IsSending(XIOModule *InstancePtr) { u32 StatusRegister; /* * Assert validates the input arguments */ Xil_AssertNonvoid(InstancePtr != NULL); /* * Read the status register to determine if the transmitter is empty */ StatusRegister = XIOModule_ReadReg(InstancePtr->BaseAddress, XUL_STATUS_REG_OFFSET); /* * If the transmitter is not empty then indicate that the UART is still * sending some data */ return ((StatusRegister & XUL_SR_TX_FIFO_FULL) == XUL_SR_TX_FIFO_FULL); } /****************************************************************************/ /** * * This function sends a buffer that has been previously specified by setting * up the instance variables of the instance. This function is designed to be * an internal function for the XIOModule component such that it may be called * from a shell function that sets up the buffer or from an interrupt handler. * * This function sends the specified buffer of data to the UART in either * polled or interrupt driven modes. This function is non-blocking such that * it will return before the data has been sent by the UART. * * In a polled mode, this function will only send as much data as the UART can * buffer in the transmitter. The application may need to call it repeatedly to * send a buffer. * * In interrupt mode, this function will start sending the specified buffer and * then the interrupt handler of the driver will continue until the buffer * has been sent. A callback function, as specified by the application, will * be called to indicate the completion of sending the buffer. * * @param InstancePtr is a pointer to the XIOModule instance. * * @return NumBytes is the number of bytes actually sent (put into the * UART transmitter and/or FIFO). * * @note None. * *****************************************************************************/ unsigned int XIOModule_SendBuffer(XIOModule *InstancePtr) { unsigned int SentCount = 0; u8 StatusRegister; u8 IntrEnableStatus; /* * Read the status register to determine if the transmitter is full */ StatusRegister = XIOModule_GetStatusReg(InstancePtr->BaseAddress); /* * Enter a critical region by disabling all the UART interrupts to allow * this call to stop a previous operation that may be interrupt driven */ XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, StatusRegister & 0xFFFFFFF8); /* * Save the status register contents to restore the interrupt enable * register to it's previous value when that the critical region is * exited */ IntrEnableStatus = StatusRegister; /* * Fill the FIFO from the the buffer that was specified */ while (((StatusRegister & XUL_SR_TX_FIFO_FULL) == 0) && (SentCount < InstancePtr->SendBuffer.RemainingBytes)) { XIOModule_WriteReg(InstancePtr->BaseAddress, XUL_TX_OFFSET, InstancePtr->SendBuffer.NextBytePtr[ SentCount]); SentCount++; StatusRegister = XIOModule_GetStatusReg(InstancePtr->BaseAddress); } /* * Update the buffer to reflect the bytes that were sent from it */ InstancePtr->SendBuffer.NextBytePtr += SentCount; InstancePtr->SendBuffer.RemainingBytes -= SentCount; /* * Increment associated counters */ InstancePtr->Uart_Stats.CharactersTransmitted += SentCount; /* * Restore the interrupt enable register to it's previous value such * that the critical region is exited */ XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, (InstancePtr->CurrentIER & 0xFFFFFFF8) | (IntrEnableStatus & 0x7)); /* * Return the number of bytes that were sent, although they really were * only put into the FIFO, not completely sent yet */ return SentCount; } /****************************************************************************/ /** * * This function receives a buffer that has been previously specified by setting * up the instance variables of the instance. This function is designed to be * an internal function for the XIOModule component such that it may be called * from a shell function that sets up the buffer or from an interrupt handler. * * This function will attempt to receive a specified number of bytes of data * from the UART and store it into the specified buffer. This function is * designed for either polled or interrupt driven modes. It is non-blocking * such that it will return if there is no data has already received by the * UART. * * In a polled mode, this function will only receive as much data as the UART * can buffer, either in the receiver or in the FIFO if present and enabled. * The application may need to call it repeatedly to receive a buffer. Polled * mode is the default mode of operation for the driver. * * In interrupt mode, this function will start receiving and then the interrupt * handler of the driver will continue until the buffer has been received. A * callback function, as specified by the application, will be called to indicate * the completion of receiving the buffer or when any receive errors or timeouts * occur. * * @param InstancePtr is a pointer to the XIOModule instance. * * @return The number of bytes received. * * @note None. * *****************************************************************************/ unsigned int XIOModule_ReceiveBuffer(XIOModule *InstancePtr) { u8 StatusRegister; unsigned int ReceivedCount = 0; /* * Loop until there is not more data buffered by the UART or the * specified number of bytes is received */ while (ReceivedCount < InstancePtr->ReceiveBuffer.RemainingBytes) { /* * Read the Status Register to determine if there is any data in * the receiver */ StatusRegister = XIOModule_GetStatusReg(InstancePtr->BaseAddress); /* * If there is data ready to be removed, then put the next byte * received into the specified buffer and update the stats to * reflect any receive errors for the byte */ if (StatusRegister & XUL_SR_RX_FIFO_VALID_DATA) { InstancePtr->ReceiveBuffer.NextBytePtr[ReceivedCount++]= XIOModule_ReadReg(InstancePtr->BaseAddress, XUL_RX_OFFSET); XIOModule_UpdateStats(InstancePtr, StatusRegister); } /* * There's no more data buffered, so exit such that this * function does not block waiting for data */ else { break; } } /* * Enter a critical region by disabling all the UART interrupts to allow * this call to stop a previous operation that may be interrupt driven */ StatusRegister = InstancePtr->CurrentIER; XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, StatusRegister & 0xFFFFFFF8); /* * Update the receive buffer to reflect the number of bytes that was * received */ InstancePtr->ReceiveBuffer.NextBytePtr += ReceivedCount; InstancePtr->ReceiveBuffer.RemainingBytes -= ReceivedCount; /* * Increment associated counters in the statistics */ InstancePtr->Uart_Stats.CharactersReceived += ReceivedCount; /* * Restore the interrupt enable register to it's previous value such * that the critical region is exited */ XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, (InstancePtr->CurrentIER & 0xFFFFFFF8) | (StatusRegister & 0x7)); return ReceivedCount; } /****************************************************************************/ /** * * This function sets the handler that will be called when an event (interrupt) * occurs in the driver for the UART. The purpose of the handler is to allow * application specific processing to be performed. * * @param InstancePtr is a pointer to the XIOModule instance. * @param FuncPtr is the pointer to the callback function. * @param CallBackRef is the upper layer callback reference passed back * when the callback function is invoked. * * @return None. * * @note There is no assert on the CallBackRef since the driver doesn't * know what it is (nor should it) * *****************************************************************************/ void XIOModule_SetRecvHandler(XIOModule *InstancePtr, XIOModule_Handler FuncPtr, void *CallBackRef) { /* * Assert validates the input arguments * CallBackRef not checked, no way to know what is valid */ Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(FuncPtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); InstancePtr->RecvHandler = FuncPtr; InstancePtr->RecvCallBackRef = CallBackRef; } /****************************************************************************/ /** * * This function sets the handler that will be called when an event (interrupt) * occurs in the driver for the UART. The purpose of the handler is to allow * application specific processing to be performed. * * @param InstancePtr is a pointer to the XIOModule instance . * @param FuncPtr is the pointer to the callback function. * @param CallBackRef is the upper layer callback reference passed back * when the callback function is invoked. * * @return None. * * @note There is no assert on the CallBackRef since the driver doesn't * know what it is (nor should it) * *****************************************************************************/ void XIOModule_SetSendHandler(XIOModule *InstancePtr, XIOModule_Handler FuncPtr, void *CallBackRef) { /* * Assert validates the input arguments * CallBackRef not checked, no way to know what is valid */ Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(FuncPtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); InstancePtr->SendHandler = FuncPtr; InstancePtr->SendCallBackRef = CallBackRef; } /****************************************************************************/ /** * * This function is the interrupt handler for the UART. * It must be connected to an interrupt system by the user such that it is * called when an interrupt for any UART lite occurs. This function * does not save or restore the processor context such that the user must * ensure this occurs. * * @param InstancePtr contains a pointer to the instance of the IOModule * that the interrupt is for. * * @return None. * * @note None. * ******************************************************************************/ void XIOModule_Uart_InterruptHandler(XIOModule *InstancePtr) { u32 IsrStatus; Xil_AssertVoid(InstancePtr != NULL); /* * Read the status register to determine which, could be both, * interrupt is active */ IsrStatus = XIOModule_GetStatusReg(InstancePtr->BaseAddress); if ((IsrStatus & XUL_SR_RX_FIFO_VALID_DATA) != 0) { ReceiveDataHandler(InstancePtr); } if (((IsrStatus & XUL_SR_TX_FIFO_FULL) == XUL_SR_TX_FIFO_FULL) && (InstancePtr->SendBuffer.RequestedBytes > 0)) { SendDataHandler(InstancePtr); } } /****************************************************************************/ /** * * This function handles the interrupt when data is received, either a single * byte when FIFOs are not enabled, or multiple bytes with the FIFO. * * @param InstancePtr is a pointer to the XIOModule instance. * * @return None. * * @note None. * *****************************************************************************/ static void ReceiveDataHandler(XIOModule *InstancePtr) { /* * If there are bytes still to be received in the specified buffer * go ahead and receive them */ if (InstancePtr->ReceiveBuffer.RemainingBytes != 0) { XIOModule_ReceiveBuffer(InstancePtr); } /* * If the last byte of a message was received then call the application * handler, this code should not use an else from the previous check of * the number of bytes to receive because the call to receive the buffer * updates the bytes to receive */ if (InstancePtr->ReceiveBuffer.RemainingBytes == 0) { InstancePtr->RecvHandler(InstancePtr->RecvCallBackRef, InstancePtr->ReceiveBuffer.RequestedBytes - InstancePtr->ReceiveBuffer.RemainingBytes); } /* * Update the receive stats to reflect the receive interrupt */ InstancePtr->Uart_Stats.ReceiveInterrupts++; } /****************************************************************************/ /** * * This function handles the interrupt when data has been sent, the transmit * FIFO is empty (transmitter holding register). * * @param InstancePtr is a pointer to the XIOModule instance . * * @return None. * * @note None. * *****************************************************************************/ static void SendDataHandler(XIOModule *InstancePtr) { /* * If there are not bytes to be sent from the specified buffer, * call the callback function */ if (InstancePtr->SendBuffer.RemainingBytes == 0) { int SaveReq; /* * Save and zero the requested bytes since transmission * is complete */ SaveReq = InstancePtr->SendBuffer.RequestedBytes; InstancePtr->SendBuffer.RequestedBytes = 0; /* * Call the application handler to indicate * the data has been sent */ InstancePtr->SendHandler(InstancePtr->SendCallBackRef, SaveReq); } /* * Otherwise there is still more data to send in the specified buffer * so go ahead and send it */ else { XIOModule_SendBuffer(InstancePtr); } /* * Update the transmit stats to reflect the transmit interrupt */ InstancePtr->Uart_Stats.TransmitInterrupts++; } /*****************************************************************************/ /** * * This function disables the UART interrupt. After calling this function, * data may still be received by the UART but no interrupt will be generated * since the hardware device has no way to disable the receiver. * * @param InstancePtr is a pointer to the XIOModule instance. * * @return None. * * @note None. * *****************************************************************************/ void XIOModule_Uart_DisableInterrupt(XIOModule *InstancePtr) { u32 NewIER; Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); /* * Write to the interrupt enable register to disable the UART * interrupts. */ NewIER = InstancePtr->CurrentIER & 0xFFFFFFF8; XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, NewIER); InstancePtr->CurrentIER = NewIER; } /*****************************************************************************/ /** * * This function enables the UART interrupts such that an interrupt will occur * when data is received or data has been transmitted. * * @param InstancePtr is a pointer to the XIOModule instance. * * @return None. * * @note None. * *****************************************************************************/ void XIOModule_Uart_EnableInterrupt(XIOModule *InstancePtr) { u32 NewIER; Xil_AssertVoid(InstancePtr != NULL); Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); /* * Write to the interrupt enable register to enable the interrupts. */ NewIER = InstancePtr->CurrentIER | 0x7; XIomodule_Out32(InstancePtr->BaseAddress + XIN_IER_OFFSET, NewIER); InstancePtr->CurrentIER = NewIER; } /** @} */
311606.c
#include "clar_libgit2.h" #include "posix.h" #include "path.h" #include "submodule_helpers.h" #include "fileops.h" #include "iterator.h" static git_repository *g_repo = NULL; void test_submodule_status__initialize(void) { g_repo = cl_git_sandbox_init("submod2"); cl_fixture_sandbox("submod2_target"); p_rename("submod2_target/.gitted", "submod2_target/.git"); /* must create submod2_target before rewrite so prettify will work */ rewrite_gitmodules(git_repository_workdir(g_repo)); p_rename("submod2/not-submodule/.gitted", "submod2/not-submodule/.git"); p_rename("submod2/not/.gitted", "submod2/not/.git"); } void test_submodule_status__cleanup(void) { cl_git_sandbox_cleanup(); cl_fixture_cleanup("submod2_target"); } void test_submodule_status__unchanged(void) { unsigned int status, expected; git_submodule *sm; cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); expected = GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD; cl_assert(status == expected); } /* 4 values of GIT_SUBMODULE_IGNORE to check */ void test_submodule_status__ignore_none(void) { unsigned int status; git_submodule *sm; git_buf path = GIT_BUF_INIT; cl_git_pass(git_buf_joinpath(&path, git_repository_workdir(g_repo), "sm_unchanged")); cl_git_pass(git_futils_rmdir_r(git_buf_cstr(&path), NULL, GIT_RMDIR_REMOVE_FILES)); cl_assert_equal_i(GIT_ENOTFOUND, git_submodule_lookup(&sm, g_repo, "just_a_dir")); cl_assert_equal_i(GIT_EEXISTS, git_submodule_lookup(&sm, g_repo, "not-submodule")); cl_assert_equal_i(GIT_EEXISTS, git_submodule_lookup(&sm, g_repo, "not")); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_index")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_file")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_WD_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_untracked_file")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_UNTRACKED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_missing_commits")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_added_and_uncommited")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_ADDED) != 0); /* removed sm_unchanged for deleted workdir */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_DELETED) != 0); /* now mkdir sm_unchanged to test uninitialized */ cl_git_pass(git_futils_mkdir(git_buf_cstr(&path), NULL, 0755, 0)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_reload(sm)); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_UNINITIALIZED) != 0); /* update sm_changed_head in index */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_add_to_index(sm, true)); /* reload is not needed because add_to_index updates the submodule data */ cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_MODIFIED) != 0); /* remove sm_changed_head from index */ { git_index *index; size_t pos; cl_git_pass(git_repository_index(&index, g_repo)); cl_assert(!git_index_find(&pos, index, "sm_changed_head")); cl_git_pass(git_index_remove(index, "sm_changed_head", 0)); cl_git_pass(git_index_write(index)); git_index_free(index); } cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_reload(sm)); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_DELETED) != 0); git_buf_free(&path); } static int set_sm_ignore(git_submodule *sm, const char *name, void *payload) { git_submodule_ignore_t ignore = *(git_submodule_ignore_t *)payload; GIT_UNUSED(name); git_submodule_set_ignore(sm, ignore); return 0; } void test_submodule_status__ignore_untracked(void) { unsigned int status; git_submodule *sm; git_buf path = GIT_BUF_INIT; git_submodule_ignore_t ign = GIT_SUBMODULE_IGNORE_UNTRACKED; cl_git_pass(git_buf_joinpath(&path, git_repository_workdir(g_repo), "sm_unchanged")); cl_git_pass(git_futils_rmdir_r(git_buf_cstr(&path), NULL, GIT_RMDIR_REMOVE_FILES)); cl_git_pass(git_submodule_foreach(g_repo, set_sm_ignore, &ign)); cl_git_fail(git_submodule_lookup(&sm, g_repo, "not-submodule")); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_index")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_INDEX_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_file")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_WD_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_untracked_file")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_missing_commits")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_added_and_uncommited")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_ADDED) != 0); /* removed sm_unchanged for deleted workdir */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_DELETED) != 0); /* now mkdir sm_unchanged to test uninitialized */ cl_git_pass(git_futils_mkdir(git_buf_cstr(&path), NULL, 0755, 0)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_reload(sm)); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_UNINITIALIZED) != 0); /* update sm_changed_head in index */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_add_to_index(sm, true)); /* reload is not needed because add_to_index updates the submodule data */ cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_MODIFIED) != 0); git_buf_free(&path); } void test_submodule_status__ignore_dirty(void) { unsigned int status; git_submodule *sm; git_buf path = GIT_BUF_INIT; git_submodule_ignore_t ign = GIT_SUBMODULE_IGNORE_DIRTY; cl_git_pass(git_buf_joinpath(&path, git_repository_workdir(g_repo), "sm_unchanged")); cl_git_pass(git_futils_rmdir_r(git_buf_cstr(&path), NULL, GIT_RMDIR_REMOVE_FILES)); cl_git_pass(git_submodule_foreach(g_repo, set_sm_ignore, &ign)); cl_assert_equal_i(GIT_ENOTFOUND, git_submodule_lookup(&sm, g_repo, "just_a_dir")); cl_assert_equal_i(GIT_EEXISTS, git_submodule_lookup(&sm, g_repo, "not-submodule")); cl_assert_equal_i(GIT_EEXISTS, git_submodule_lookup(&sm, g_repo, "not")); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_index")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_file")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_untracked_file")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_missing_commits")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_MODIFIED) != 0); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_added_and_uncommited")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_ADDED) != 0); /* removed sm_unchanged for deleted workdir */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_DELETED) != 0); /* now mkdir sm_unchanged to test uninitialized */ cl_git_pass(git_futils_mkdir(git_buf_cstr(&path), NULL, 0755, 0)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_reload(sm)); cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_WD_UNINITIALIZED) != 0); /* update sm_changed_head in index */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_add_to_index(sm, true)); /* reload is not needed because add_to_index updates the submodule data */ cl_git_pass(git_submodule_status(&status, sm)); cl_assert((status & GIT_SUBMODULE_STATUS_INDEX_MODIFIED) != 0); git_buf_free(&path); } void test_submodule_status__ignore_all(void) { unsigned int status; git_submodule *sm; git_buf path = GIT_BUF_INIT; git_submodule_ignore_t ign = GIT_SUBMODULE_IGNORE_ALL; cl_git_pass(git_buf_joinpath(&path, git_repository_workdir(g_repo), "sm_unchanged")); cl_git_pass(git_futils_rmdir_r(git_buf_cstr(&path), NULL, GIT_RMDIR_REMOVE_FILES)); cl_git_pass(git_submodule_foreach(g_repo, set_sm_ignore, &ign)); cl_assert_equal_i(GIT_ENOTFOUND, git_submodule_lookup(&sm, g_repo, "just_a_dir")); cl_assert_equal_i(GIT_EEXISTS, git_submodule_lookup(&sm, g_repo, "not-submodule")); cl_assert_equal_i(GIT_EEXISTS, git_submodule_lookup(&sm, g_repo, "not")); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_index")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_file")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_untracked_file")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_missing_commits")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_added_and_uncommited")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); /* removed sm_unchanged for deleted workdir */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); /* now mkdir sm_unchanged to test uninitialized */ cl_git_pass(git_futils_mkdir(git_buf_cstr(&path), NULL, 0755, 0)); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_reload(sm)); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); /* update sm_changed_head in index */ cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_changed_head")); cl_git_pass(git_submodule_add_to_index(sm, true)); /* reload is not needed because add_to_index updates the submodule data */ cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); git_buf_free(&path); } typedef struct { size_t counter; const char **paths; } submodule_expectations; static int confirm_submodule_status( const char *path, unsigned int status_flags, void *payload) { submodule_expectations *exp = payload; while (git__suffixcmp(exp->paths[exp->counter], "/") == 0) exp->counter++; cl_assert_equal_s(exp->paths[exp->counter++], path); GIT_UNUSED(status_flags); return 0; } void test_submodule_status__iterator(void) { git_iterator *iter; const git_index_entry *entry; size_t i; static const char *expected[] = { ".gitmodules", "just_a_dir/", "just_a_dir/contents", "just_a_file", "not", "not-submodule", "README.txt", "sm_added_and_uncommited", "sm_changed_file", "sm_changed_head", "sm_changed_index", "sm_changed_untracked_file", "sm_missing_commits", "sm_unchanged", NULL }; submodule_expectations exp = { 0, expected }; git_status_options opts = GIT_STATUS_OPTIONS_INIT; cl_git_pass(git_iterator_for_workdir(&iter, g_repo, GIT_ITERATOR_IGNORE_CASE | GIT_ITERATOR_INCLUDE_TREES, NULL, NULL)); for (i = 0; !git_iterator_advance(&entry, iter); ++i) cl_assert_equal_s(expected[i], entry->path); git_iterator_free(iter); opts.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_INCLUDE_UNMODIFIED | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS; cl_git_pass(git_status_foreach_ext( g_repo, &opts, confirm_submodule_status, &exp)); } void test_submodule_status__untracked_dirs_containing_ignored_files(void) { git_buf path = GIT_BUF_INIT; unsigned int status, expected; git_submodule *sm; cl_git_pass(git_buf_joinpath(&path, git_repository_path(g_repo), "modules/sm_unchanged/info/exclude")); cl_git_append2file(git_buf_cstr(&path), "\n*.ignored\n"); cl_git_pass(git_buf_joinpath(&path, git_repository_workdir(g_repo), "sm_unchanged/directory")); cl_git_pass(git_futils_mkdir(git_buf_cstr(&path), NULL, 0755, 0)); cl_git_pass(git_buf_joinpath(&path, git_buf_cstr(&path), "i_am.ignored")); cl_git_mkfile(git_buf_cstr(&path), "ignored this file, please\n"); cl_git_pass(git_submodule_lookup(&sm, g_repo, "sm_unchanged")); cl_git_pass(git_submodule_status(&status, sm)); cl_assert(GIT_SUBMODULE_STATUS_IS_UNMODIFIED(status)); expected = GIT_SUBMODULE_STATUS_IN_HEAD | GIT_SUBMODULE_STATUS_IN_INDEX | GIT_SUBMODULE_STATUS_IN_CONFIG | GIT_SUBMODULE_STATUS_IN_WD; cl_assert(status == expected); git_buf_free(&path); }
151454.c
/* * sequence_led.c * * Created on: 22 juin 2020 * Author: Th�o */ #include "../Inc/Sequence_led.h" //On initialise les paramètres void LED_SEQUENCE_init(sequence_led_t * seq_led, GPIO_TypeDef* gpio, uint16_t gpio_pin, int32_t init_seq, uint32_t periode, int8_t length_sequence, bool_e output_logic){ //Init des varaibles seq_led->compteur = 0; seq_led->gpio = gpio ; seq_led->gpio_pin = gpio_pin ; seq_led->length_sequence = length_sequence ; seq_led->periode = periode ; seq_led->output_logic = output_logic ; if(seq_led->output_logic == 1) //Si logique négative on inverse la séquence init_seq = ~init_seq ; seq_led->sequence = init_seq ; } //On change la séquence active void LED_SEQUENCE_set_sequence(sequence_led_t * seq_led, int32_t seq){ if(seq_led->output_logic == 1) //Si logique n�gative on inverse la s�quence seq = ~seq ; seq_led->compteur = 0 ; seq_led->sequence = seq ; } //On change la sortie de la led en fonction de la séquence active void LED_SEQUENCE_play(sequence_led_t * seq_led, uint32_t current_time_us){ if(current_time_us / 1000 > seq_led->previous_time + seq_led->periode){ seq_led->previous_time += seq_led->periode ; //on récupère le niveau logique de la sortie bool_e output = ((seq_led->sequence) >> ((seq_led->length_sequence - seq_led->compteur) - 1)) & 1 ; //On update la sortie if(output) seq_led->gpio->BSRR = seq_led->gpio_pin ; else seq_led->gpio->BSRR = (uint32_t)(seq_led->gpio_pin) << 16U ; //on update le compteur seq_led->compteur ++ ; //TODO : verif l'init si length > 0 if(seq_led->compteur == seq_led->length_sequence) seq_led->compteur = 0 ; } }
679419.c
/***************************************************************************/ /* */ /* t1gload.c */ /* */ /* Type 1 Glyph Loader (body). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <plugin/FT_fontsys/ft2build.h> #include "t1gload.h" #include FT_INTERNAL_CALC_H #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include FT_OUTLINE_H #include FT_INTERNAL_POSTSCRIPT_AUX_H #include "t1errors.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_t1gload /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********** *********/ /********** COMPUTE THE MAXIMUM ADVANCE WIDTH *********/ /********** *********/ /********** The following code is in charge of computing *********/ /********** the maximum advance width of the font. It *********/ /********** quickly processes each glyph charstring to *********/ /********** extract the value from either a `sbw' or `seac' *********/ /********** operator. *********/ /********** *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( FT_Error ) T1_Parse_Glyph_And_Get_Char_String( T1_Decoder decoder, FT_UInt glyph_index, FT_Data* char_string ) { T1_Face face = (T1_Face)decoder->builder.face; T1_Font type1 = &face->type1; FT_Error error = T1_Err_Ok; #ifdef FT_CONFIG_OPTION_INCREMENTAL FT_Incremental_InterfaceRec *inc = face->root.internal->incremental_interface; #endif decoder->font_matrix = type1->font_matrix; decoder->font_offset = type1->font_offset; #ifdef FT_CONFIG_OPTION_INCREMENTAL /* For incremental fonts get the character data using the */ /* callback function. */ if ( inc ) error = inc->funcs->get_glyph_data( inc->object, glyph_index, char_string ); else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ /* For ordinary fonts get the character data stored in the face record. */ { char_string->pointer = type1->charstrings[glyph_index]; char_string->length = (FT_Int)type1->charstrings_len[glyph_index]; } if ( !error ) error = decoder->funcs.parse_charstrings( decoder, (FT_Byte*)char_string->pointer, char_string->length ); #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Incremental fonts can optionally override the metrics. */ if ( !error && inc && inc->funcs->get_glyph_metrics ) { FT_Incremental_MetricsRec metrics; metrics.bearing_x = FIXED_TO_INT( decoder->builder.left_bearing.x ); metrics.bearing_y = 0; metrics.advance = FIXED_TO_INT( decoder->builder.advance.x ); metrics.advance_v = FIXED_TO_INT( decoder->builder.advance.y ); error = inc->funcs->get_glyph_metrics( inc->object, glyph_index, FALSE, &metrics ); decoder->builder.left_bearing.x = INT_TO_FIXED( metrics.bearing_x ); decoder->builder.advance.x = INT_TO_FIXED( metrics.advance ); decoder->builder.advance.y = INT_TO_FIXED( metrics.advance_v ); } #endif /* FT_CONFIG_OPTION_INCREMENTAL */ return error; } FT_CALLBACK_DEF( FT_Error ) T1_Parse_Glyph( T1_Decoder decoder, FT_UInt glyph_index ) { FT_Data glyph_data; FT_Error error = T1_Parse_Glyph_And_Get_Char_String( decoder, glyph_index, &glyph_data ); #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( !error ) { T1_Face face = (T1_Face)decoder->builder.face; if ( face->root.internal->incremental_interface ) face->root.internal->incremental_interface->funcs->free_glyph_data( face->root.internal->incremental_interface->object, &glyph_data ); } #endif /* FT_CONFIG_OPTION_INCREMENTAL */ return error; } FT_LOCAL_DEF( FT_Error ) T1_Compute_Max_Advance( T1_Face face, FT_Pos* max_advance ) { FT_Error error; T1_DecoderRec decoder; FT_Int glyph_index; T1_Font type1 = &face->type1; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) ); *max_advance = 0; /* initialize load decoder */ error = psaux->t1_decoder_funcs->init( &decoder, (FT_Face)face, 0, /* size */ 0, /* glyph slot */ (FT_Byte**)type1->glyph_names, face->blend, 0, FT_RENDER_MODE_NORMAL, T1_Parse_Glyph ); if ( error ) return error; decoder.builder.metrics_only = 1; decoder.builder.load_points = 0; decoder.num_subrs = type1->num_subrs; decoder.subrs = type1->subrs; decoder.subrs_len = type1->subrs_len; decoder.buildchar = face->buildchar; decoder.len_buildchar = face->len_buildchar; *max_advance = 0; /* for each glyph, parse the glyph charstring and extract */ /* the advance width */ for ( glyph_index = 0; glyph_index < type1->num_glyphs; glyph_index++ ) { /* now get load the unscaled outline */ error = T1_Parse_Glyph( &decoder, glyph_index ); if ( glyph_index == 0 || decoder.builder.advance.x > *max_advance ) *max_advance = decoder.builder.advance.x; /* ignore the error if one occurred - skip to next glyph */ } psaux->t1_decoder_funcs->done( &decoder ); return T1_Err_Ok; } FT_LOCAL_DEF( FT_Error ) T1_Get_Advances( T1_Face face, FT_UInt first, FT_UInt count, FT_ULong load_flags, FT_Fixed* advances ) { T1_DecoderRec decoder; T1_Font type1 = &face->type1; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_UInt nn; FT_Error error; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { for ( nn = 0; nn < count; nn++ ) advances[nn] = 0; return T1_Err_Ok; } error = psaux->t1_decoder_funcs->init( &decoder, (FT_Face)face, 0, /* size */ 0, /* glyph slot */ (FT_Byte**)type1->glyph_names, face->blend, 0, FT_RENDER_MODE_NORMAL, T1_Parse_Glyph ); if ( error ) return error; decoder.builder.metrics_only = 1; decoder.builder.load_points = 0; decoder.num_subrs = type1->num_subrs; decoder.subrs = type1->subrs; decoder.subrs_len = type1->subrs_len; decoder.buildchar = face->buildchar; decoder.len_buildchar = face->len_buildchar; for ( nn = 0; nn < count; nn++ ) { error = T1_Parse_Glyph( &decoder, first + nn ); if ( !error ) advances[nn] = FIXED_TO_INT( decoder.builder.advance.x ); else advances[nn] = 0; } return T1_Err_Ok; } FT_LOCAL_DEF( FT_Error ) T1_Load_Glyph( T1_GlyphSlot glyph, T1_Size size, FT_UInt glyph_index, FT_Int32 load_flags ) { FT_Error error; T1_DecoderRec decoder; T1_Face face = (T1_Face)glyph->root.face; FT_Bool hinting; T1_Font type1 = &face->type1; PSAux_Service psaux = (PSAux_Service)face->psaux; const T1_Decoder_Funcs decoder_funcs = psaux->t1_decoder_funcs; FT_Matrix font_matrix; FT_Vector font_offset; FT_Data glyph_data; FT_Bool must_finish_decoder = FALSE; #ifdef FT_CONFIG_OPTION_INCREMENTAL FT_Bool glyph_data_loaded = 0; #endif #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( glyph_index >= (FT_UInt)face->root.num_glyphs && !face->root.internal->incremental_interface ) #else if ( glyph_index >= (FT_UInt)face->root.num_glyphs ) #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { error = T1_Err_Invalid_Argument; goto Exit; } FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) ); if ( load_flags & FT_LOAD_NO_RECURSE ) load_flags |= FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING; if ( size ) { glyph->x_scale = size->root.metrics.x_scale; glyph->y_scale = size->root.metrics.y_scale; } else { glyph->x_scale = 0x10000L; glyph->y_scale = 0x10000L; } glyph->root.outline.n_points = 0; glyph->root.outline.n_contours = 0; hinting = FT_BOOL( ( load_flags & FT_LOAD_NO_SCALE ) == 0 && ( load_flags & FT_LOAD_NO_HINTING ) == 0 ); glyph->root.format = FT_GLYPH_FORMAT_OUTLINE; error = decoder_funcs->init( &decoder, (FT_Face)face, (FT_Size)size, (FT_GlyphSlot)glyph, (FT_Byte**)type1->glyph_names, face->blend, FT_BOOL( hinting ), FT_LOAD_TARGET_MODE( load_flags ), T1_Parse_Glyph ); if ( error ) goto Exit; must_finish_decoder = TRUE; decoder.builder.no_recurse = FT_BOOL( ( load_flags & FT_LOAD_NO_RECURSE ) != 0 ); decoder.num_subrs = type1->num_subrs; decoder.subrs = type1->subrs; decoder.subrs_len = type1->subrs_len; decoder.buildchar = face->buildchar; decoder.len_buildchar = face->len_buildchar; /* now load the unscaled outline */ error = T1_Parse_Glyph_And_Get_Char_String( &decoder, glyph_index, &glyph_data ); if ( error ) goto Exit; #ifdef FT_CONFIG_OPTION_INCREMENTAL glyph_data_loaded = 1; #endif font_matrix = decoder.font_matrix; font_offset = decoder.font_offset; /* save new glyph tables */ decoder_funcs->done( &decoder ); must_finish_decoder = FALSE; /* now, set the metrics -- this is rather simple, as */ /* the left side bearing is the xMin, and the top side */ /* bearing the yMax */ if ( !error ) { glyph->root.outline.flags &= FT_OUTLINE_OWNER; glyph->root.outline.flags |= FT_OUTLINE_REVERSE_FILL; /* for composite glyphs, return only left side bearing and */ /* advance width */ if ( load_flags & FT_LOAD_NO_RECURSE ) { FT_Slot_Internal internal = glyph->root.internal; glyph->root.metrics.horiBearingX = FIXED_TO_INT( decoder.builder.left_bearing.x ); glyph->root.metrics.horiAdvance = FIXED_TO_INT( decoder.builder.advance.x ); internal->glyph_matrix = font_matrix; internal->glyph_delta = font_offset; internal->glyph_transformed = 1; } else { FT_BBox cbox; FT_Glyph_Metrics* metrics = &glyph->root.metrics; FT_Vector advance; /* copy the _unscaled_ advance width */ metrics->horiAdvance = FIXED_TO_INT( decoder.builder.advance.x ); glyph->root.linearHoriAdvance = FIXED_TO_INT( decoder.builder.advance.x ); glyph->root.internal->glyph_transformed = 0; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { /* make up vertical ones */ metrics->vertAdvance = ( face->type1.font_bbox.yMax - face->type1.font_bbox.yMin ) >> 16; glyph->root.linearVertAdvance = metrics->vertAdvance; } else { metrics->vertAdvance = FIXED_TO_INT( decoder.builder.advance.y ); glyph->root.linearVertAdvance = FIXED_TO_INT( decoder.builder.advance.y ); } glyph->root.format = FT_GLYPH_FORMAT_OUTLINE; if ( size && size->root.metrics.y_ppem < 24 ) glyph->root.outline.flags |= FT_OUTLINE_HIGH_PRECISION; #if 1 /* apply the font matrix, if any */ if ( font_matrix.xx != 0x10000L || font_matrix.yy != font_matrix.xx || font_matrix.xy != 0 || font_matrix.yx != 0 ) FT_Outline_Transform( &glyph->root.outline, &font_matrix ); if ( font_offset.x || font_offset.y ) FT_Outline_Translate( &glyph->root.outline, font_offset.x, font_offset.y ); advance.x = metrics->horiAdvance; advance.y = 0; FT_Vector_Transform( &advance, &font_matrix ); metrics->horiAdvance = advance.x + font_offset.x; advance.x = 0; advance.y = metrics->vertAdvance; FT_Vector_Transform( &advance, &font_matrix ); metrics->vertAdvance = advance.y + font_offset.y; #endif if ( ( load_flags & FT_LOAD_NO_SCALE ) == 0 ) { /* scale the outline and the metrics */ FT_Int n; FT_Outline* cur = decoder.builder.base; FT_Vector* vec = cur->points; FT_Fixed x_scale = glyph->x_scale; FT_Fixed y_scale = glyph->y_scale; /* First of all, scale the points, if we are not hinting */ if ( !hinting || ! decoder.builder.hints_funcs ) for ( n = cur->n_points; n > 0; n--, vec++ ) { vec->x = FT_MulFix( vec->x, x_scale ); vec->y = FT_MulFix( vec->y, y_scale ); } /* Then scale the metrics */ metrics->horiAdvance = FT_MulFix( metrics->horiAdvance, x_scale ); metrics->vertAdvance = FT_MulFix( metrics->vertAdvance, y_scale ); } /* compute the other metrics */ FT_Outline_Get_CBox( &glyph->root.outline, &cbox ); metrics->width = cbox.xMax - cbox.xMin; metrics->height = cbox.yMax - cbox.yMin; metrics->horiBearingX = cbox.xMin; metrics->horiBearingY = cbox.yMax; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { /* make up vertical ones */ ft_synthesize_vertical_metrics( metrics, metrics->vertAdvance ); } } /* Set control data to the glyph charstrings. Note that this is */ /* _not_ zero-terminated. */ glyph->root.control_data = (FT_Byte*)glyph_data.pointer; glyph->root.control_len = glyph_data.length; } Exit: #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( glyph_data_loaded && face->root.internal->incremental_interface ) { face->root.internal->incremental_interface->funcs->free_glyph_data( face->root.internal->incremental_interface->object, &glyph_data ); /* Set the control data to null - it is no longer available if */ /* loaded incrementally. */ glyph->root.control_data = 0; glyph->root.control_len = 0; } #endif if ( must_finish_decoder ) decoder_funcs->done( &decoder ); return error; } /* END */
176312.c
// file: source/core/time.c #ifdef ZPL_EDITOR #include <zpl.h> #endif #if defined(ZPL_SYSTEM_MACOS) || ZPL_SYSTEM_UNIX #include <time.h> #endif #if defined(ZPL_SYSTEM_MACOS) #include <mach/mach.h> #include <mach/mach_time.h> #include <mach/clock.h> #endif ZPL_BEGIN_C_DECLS //! @} //$$ //////////////////////////////////////////////////////////////// // // Time // // #if defined(ZPL_COMPILER_MSVC) && !defined(__clang__) zpl_u64 zpl_rdtsc(void) { return __rdtsc( ); } #elif defined(__i386__) zpl_u64 zpl_rdtsc(void) { zpl_u64 x; __asm__ volatile(".byte 0x0f, 0x31" : "=A"(x)); return x; } #elif defined(__x86_64__) zpl_u64 zpl_rdtsc(void) { zpl_u32 hi, lo; __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi)); return (cast(zpl_u64) lo) | ((cast(zpl_u64) hi) << 32); } #elif defined(__powerpc__) zpl_u64 zpl_rdtsc(void) { zpl_u64 result = 0; zpl_u32 upper, lower, tmp; __asm__ volatile("0: \n" "\tmftbu %0 \n" "\tmftb %1 \n" "\tmftbu %2 \n" "\tcmpw %2,%0 \n" "\tbne 0b \n" : "=r"(upper), "=r"(lower), "=r"(tmp)); result = upper; result = result << 32; result = result | lower; return result; } #elif defined(ZPL_CPU_ARM) zpl_u64 zpl_rdtsc(void) { #if defined(__aarch64__) int64_t r = 0; asm volatile("mrs %0, cntvct_el0" : "=r"(r)); #elif defined(__ARM_ARCH_7A__) uint32_t r = 0; asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(r)); #elif (__ARM_ARCH >= 6) uint32_t pmccntr; uint32_t pmuseren; uint32_t pmcntenset; // Read the user mode perf monitor counter access permissions. asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren)); if (pmuseren & 1) { // Allows reading perfmon counters for user mode code. asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset)); if (pmcntenset & 0x80000000ul) { // Is it counting? asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr)); // The counter is set up to count every 64th cycle return ((int64_t)pmccntr) * 64; // Should optimize to << 6 } } #else #error "No suitable method for zpl_rdtsc for this cpu type" #endif return r; } #endif #if defined(ZPL_SYSTEM_WINDOWS) || defined(ZPL_SYSTEM_CYGWIN) zpl_f64 zpl_time_now(void) { zpl_local_persist LARGE_INTEGER win32_perf_count_freq = { 0 }; zpl_f64 result; LARGE_INTEGER counter; zpl_local_persist LARGE_INTEGER win32_perf_counter = { 0 }; if (!win32_perf_count_freq.QuadPart) { QueryPerformanceFrequency(&win32_perf_count_freq); ZPL_ASSERT(win32_perf_count_freq.QuadPart != 0); QueryPerformanceCounter(&win32_perf_counter); } QueryPerformanceCounter(&counter); result = (counter.QuadPart - win32_perf_counter.QuadPart) / cast(zpl_f64)(win32_perf_count_freq.QuadPart); return result; } zpl_f64 zpl_utc_time_now(void) { FILETIME ft; ULARGE_INTEGER li; GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; return li.QuadPart / 10 / 10e5; } void zpl_sleep_ms(zpl_u32 ms) { Sleep(ms); } #else #if defined(ZPL_SYSTEM_LINUX) || defined(ZPL_SYSTEM_FREEBSD) || defined(ZPL_SYSTEM_OPENBSD) || defined(ZPL_SYSTEM_EMSCRIPTEN) zpl_f64 zpl__unix_getime(void) { struct timespec t; zpl_f64 result; clock_gettime(1 /*CLOCK_MONOTONIC*/, &t); result = t.tv_sec + 1.0e-9 * t.tv_nsec; return result; } #endif zpl_f64 zpl_time_now(void) { #if defined(ZPL_SYSTEM_OSX) zpl_f64 result; zpl_local_persist zpl_f64 timebase = 0.0; zpl_local_persist zpl_u64 timestart = 0; if (!timestart) { mach_timebase_info_data_t tb = { 0 }; mach_timebase_info(&tb); timebase = tb.numer; timebase /= tb.denom; timestart = mach_absolute_time( ); } // NOTE: mach_absolute_time() returns things in nanoseconds result = 1.0e-9 * (mach_absolute_time( ) - timestart) * timebase; return result; #else zpl_local_persist zpl_f64 unix_timestart = 0.0; if (!unix_timestart) { unix_timestart = zpl__unix_getime( ); } zpl_f64 now = zpl__unix_getime( ); return (now - unix_timestart); #endif } zpl_f64 zpl_utc_time_now(void) { struct timespec t; #if defined(ZPL_SYSTEM_OSX) clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self( ), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self( ), cclock); t.tv_sec = mts.tv_sec; t.tv_nsec = mts.tv_nsec; #else clock_gettime(0 /*CLOCK_REALTIME*/, &t); #endif return (cast(zpl_u64) t.tv_sec * 1000000ull + t.tv_nsec / 1000 + 11644473600000000ull) / 10e5; } void zpl_sleep_ms(zpl_u32 ms) { struct timespec req = { cast(time_t) ms / 1000, cast(long)((ms % 1000) * 1000000) }; struct timespec rem = { 0, 0 }; nanosleep(&req, &rem); } #endif ZPL_END_C_DECLS
844488.c
/* Core extension modules are built-in on some platforms (e.g. Windows). */ #ifdef Py_BUILD_CORE #define Py_BUILD_CORE_BUILTIN #undef Py_BUILD_CORE #endif #include "Python.h" #include "structmember.h" PyDoc_STRVAR(pickle_module_doc, "Optimized C implementation for the Python pickle module."); /*[clinic input] module _pickle class _pickle.Pickler "PicklerObject *" "&Pickler_Type" class _pickle.PicklerMemoProxy "PicklerMemoProxyObject *" "&PicklerMemoProxyType" class _pickle.Unpickler "UnpicklerObject *" "&Unpickler_Type" class _pickle.UnpicklerMemoProxy "UnpicklerMemoProxyObject *" "&UnpicklerMemoProxyType" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=4b3e113468a58e6c]*/ /* Bump HIGHEST_PROTOCOL when new opcodes are added to the pickle protocol. Bump DEFAULT_PROTOCOL only when the oldest still supported version of Python already includes it. */ enum { HIGHEST_PROTOCOL = 4, DEFAULT_PROTOCOL = 4 }; /* Pickle opcodes. These must be kept updated with pickle.py. Extensive docs are in pickletools.py. */ enum opcode { MARK = '(', STOP = '.', POP = '0', POP_MARK = '1', DUP = '2', FLOAT = 'F', INT = 'I', BININT = 'J', BININT1 = 'K', LONG = 'L', BININT2 = 'M', NONE = 'N', PERSID = 'P', BINPERSID = 'Q', REDUCE = 'R', STRING = 'S', BINSTRING = 'T', SHORT_BINSTRING = 'U', UNICODE = 'V', BINUNICODE = 'X', APPEND = 'a', BUILD = 'b', GLOBAL = 'c', DICT = 'd', EMPTY_DICT = '}', APPENDS = 'e', GET = 'g', BINGET = 'h', INST = 'i', LONG_BINGET = 'j', LIST = 'l', EMPTY_LIST = ']', OBJ = 'o', PUT = 'p', BINPUT = 'q', LONG_BINPUT = 'r', SETITEM = 's', TUPLE = 't', EMPTY_TUPLE = ')', SETITEMS = 'u', BINFLOAT = 'G', /* Protocol 2. */ PROTO = '\x80', NEWOBJ = '\x81', EXT1 = '\x82', EXT2 = '\x83', EXT4 = '\x84', TUPLE1 = '\x85', TUPLE2 = '\x86', TUPLE3 = '\x87', NEWTRUE = '\x88', NEWFALSE = '\x89', LONG1 = '\x8a', LONG4 = '\x8b', /* Protocol 3 (Python 3.x) */ BINBYTES = 'B', SHORT_BINBYTES = 'C', /* Protocol 4 */ SHORT_BINUNICODE = '\x8c', BINUNICODE8 = '\x8d', BINBYTES8 = '\x8e', EMPTY_SET = '\x8f', ADDITEMS = '\x90', FROZENSET = '\x91', NEWOBJ_EX = '\x92', STACK_GLOBAL = '\x93', MEMOIZE = '\x94', FRAME = '\x95' }; enum { /* Keep in synch with pickle.Pickler._BATCHSIZE. This is how many elements batch_list/dict() pumps out before doing APPENDS/SETITEMS. Nothing will break if this gets out of synch with pickle.py, but it's unclear that would help anything either. */ BATCHSIZE = 1000, /* Nesting limit until Pickler, when running in "fast mode", starts checking for self-referential data-structures. */ FAST_NESTING_LIMIT = 50, /* Initial size of the write buffer of Pickler. */ WRITE_BUF_SIZE = 4096, /* Prefetch size when unpickling (disabled on unpeekable streams) */ PREFETCH = 8192 * 16, FRAME_SIZE_MIN = 4, FRAME_SIZE_TARGET = 64 * 1024, FRAME_HEADER_SIZE = 9 }; /*************************************************************************/ /* State of the pickle module, per PEP 3121. */ typedef struct { /* Exception classes for pickle. */ PyObject *PickleError; PyObject *PicklingError; PyObject *UnpicklingError; /* copyreg.dispatch_table, {type_object: pickling_function} */ PyObject *dispatch_table; /* For the extension opcodes EXT1, EXT2 and EXT4. */ /* copyreg._extension_registry, {(module_name, function_name): code} */ PyObject *extension_registry; /* copyreg._extension_cache, {code: object} */ PyObject *extension_cache; /* copyreg._inverted_registry, {code: (module_name, function_name)} */ PyObject *inverted_registry; /* Import mappings for compatibility with Python 2.x */ /* _compat_pickle.NAME_MAPPING, {(oldmodule, oldname): (newmodule, newname)} */ PyObject *name_mapping_2to3; /* _compat_pickle.IMPORT_MAPPING, {oldmodule: newmodule} */ PyObject *import_mapping_2to3; /* Same, but with REVERSE_NAME_MAPPING / REVERSE_IMPORT_MAPPING */ PyObject *name_mapping_3to2; PyObject *import_mapping_3to2; /* codecs.encode, used for saving bytes in older protocols */ PyObject *codecs_encode; /* builtins.getattr, used for saving nested names with protocol < 4 */ PyObject *getattr; /* functools.partial, used for implementing __newobj_ex__ with protocols 2 and 3 */ PyObject *partial; } PickleState; /* Forward declaration of the _pickle module definition. */ static struct PyModuleDef _picklemodule; /* Given a module object, get its per-module state. */ static PickleState * _Pickle_GetState(PyObject *module) { return (PickleState *)PyModule_GetState(module); } /* Find the module instance imported in the currently running sub-interpreter and get its state. */ static PickleState * _Pickle_GetGlobalState(void) { return _Pickle_GetState(PyState_FindModule(&_picklemodule)); } /* Clear the given pickle module state. */ static void _Pickle_ClearState(PickleState *st) { Py_CLEAR(st->PickleError); Py_CLEAR(st->PicklingError); Py_CLEAR(st->UnpicklingError); Py_CLEAR(st->dispatch_table); Py_CLEAR(st->extension_registry); Py_CLEAR(st->extension_cache); Py_CLEAR(st->inverted_registry); Py_CLEAR(st->name_mapping_2to3); Py_CLEAR(st->import_mapping_2to3); Py_CLEAR(st->name_mapping_3to2); Py_CLEAR(st->import_mapping_3to2); Py_CLEAR(st->codecs_encode); Py_CLEAR(st->getattr); Py_CLEAR(st->partial); } /* Initialize the given pickle module state. */ static int _Pickle_InitState(PickleState *st) { PyObject *builtins; PyObject *copyreg = NULL; PyObject *compat_pickle = NULL; PyObject *codecs = NULL; PyObject *functools = NULL; builtins = PyEval_GetBuiltins(); if (builtins == NULL) goto error; st->getattr = PyDict_GetItemString(builtins, "getattr"); if (st->getattr == NULL) goto error; Py_INCREF(st->getattr); copyreg = PyImport_ImportModule("copyreg"); if (!copyreg) goto error; st->dispatch_table = PyObject_GetAttrString(copyreg, "dispatch_table"); if (!st->dispatch_table) goto error; if (!PyDict_CheckExact(st->dispatch_table)) { PyErr_Format(PyExc_RuntimeError, "copyreg.dispatch_table should be a dict, not %.200s", Py_TYPE(st->dispatch_table)->tp_name); goto error; } st->extension_registry = \ PyObject_GetAttrString(copyreg, "_extension_registry"); if (!st->extension_registry) goto error; if (!PyDict_CheckExact(st->extension_registry)) { PyErr_Format(PyExc_RuntimeError, "copyreg._extension_registry should be a dict, " "not %.200s", Py_TYPE(st->extension_registry)->tp_name); goto error; } st->inverted_registry = \ PyObject_GetAttrString(copyreg, "_inverted_registry"); if (!st->inverted_registry) goto error; if (!PyDict_CheckExact(st->inverted_registry)) { PyErr_Format(PyExc_RuntimeError, "copyreg._inverted_registry should be a dict, " "not %.200s", Py_TYPE(st->inverted_registry)->tp_name); goto error; } st->extension_cache = PyObject_GetAttrString(copyreg, "_extension_cache"); if (!st->extension_cache) goto error; if (!PyDict_CheckExact(st->extension_cache)) { PyErr_Format(PyExc_RuntimeError, "copyreg._extension_cache should be a dict, " "not %.200s", Py_TYPE(st->extension_cache)->tp_name); goto error; } Py_CLEAR(copyreg); /* Load the 2.x -> 3.x stdlib module mapping tables */ compat_pickle = PyImport_ImportModule("_compat_pickle"); if (!compat_pickle) goto error; st->name_mapping_2to3 = \ PyObject_GetAttrString(compat_pickle, "NAME_MAPPING"); if (!st->name_mapping_2to3) goto error; if (!PyDict_CheckExact(st->name_mapping_2to3)) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.NAME_MAPPING should be a dict, not %.200s", Py_TYPE(st->name_mapping_2to3)->tp_name); goto error; } st->import_mapping_2to3 = \ PyObject_GetAttrString(compat_pickle, "IMPORT_MAPPING"); if (!st->import_mapping_2to3) goto error; if (!PyDict_CheckExact(st->import_mapping_2to3)) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.IMPORT_MAPPING should be a dict, " "not %.200s", Py_TYPE(st->import_mapping_2to3)->tp_name); goto error; } /* ... and the 3.x -> 2.x mapping tables */ st->name_mapping_3to2 = \ PyObject_GetAttrString(compat_pickle, "REVERSE_NAME_MAPPING"); if (!st->name_mapping_3to2) goto error; if (!PyDict_CheckExact(st->name_mapping_3to2)) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.REVERSE_NAME_MAPPING should be a dict, " "not %.200s", Py_TYPE(st->name_mapping_3to2)->tp_name); goto error; } st->import_mapping_3to2 = \ PyObject_GetAttrString(compat_pickle, "REVERSE_IMPORT_MAPPING"); if (!st->import_mapping_3to2) goto error; if (!PyDict_CheckExact(st->import_mapping_3to2)) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.REVERSE_IMPORT_MAPPING should be a dict, " "not %.200s", Py_TYPE(st->import_mapping_3to2)->tp_name); goto error; } Py_CLEAR(compat_pickle); codecs = PyImport_ImportModule("codecs"); if (codecs == NULL) goto error; st->codecs_encode = PyObject_GetAttrString(codecs, "encode"); if (st->codecs_encode == NULL) { goto error; } if (!PyCallable_Check(st->codecs_encode)) { PyErr_Format(PyExc_RuntimeError, "codecs.encode should be a callable, not %.200s", Py_TYPE(st->codecs_encode)->tp_name); goto error; } Py_CLEAR(codecs); functools = PyImport_ImportModule("functools"); if (!functools) goto error; st->partial = PyObject_GetAttrString(functools, "partial"); if (!st->partial) goto error; Py_CLEAR(functools); return 0; error: Py_CLEAR(copyreg); Py_CLEAR(compat_pickle); Py_CLEAR(codecs); Py_CLEAR(functools); _Pickle_ClearState(st); return -1; } /* Helper for calling a function with a single argument quickly. This function steals the reference of the given argument. */ static PyObject * _Pickle_FastCall(PyObject *func, PyObject *obj) { PyObject *result; result = PyObject_CallFunctionObjArgs(func, obj, NULL); Py_DECREF(obj); return result; } /*************************************************************************/ /* Retrieve and deconstruct a method for avoiding a reference cycle (pickler -> bound method of pickler -> pickler) */ static int init_method_ref(PyObject *self, _Py_Identifier *name, PyObject **method_func, PyObject **method_self) { PyObject *func, *func2; int ret; /* *method_func and *method_self should be consistent. All refcount decrements should be occurred after setting *method_self and *method_func. */ ret = _PyObject_LookupAttrId(self, name, &func); if (func == NULL) { *method_self = NULL; Py_CLEAR(*method_func); return ret; } if (PyMethod_Check(func) && PyMethod_GET_SELF(func) == self) { /* Deconstruct a bound Python method */ func2 = PyMethod_GET_FUNCTION(func); Py_INCREF(func2); *method_self = self; /* borrowed */ Py_XSETREF(*method_func, func2); Py_DECREF(func); return 0; } else { *method_self = NULL; Py_XSETREF(*method_func, func); return 0; } } /* Bind a method if it was deconstructed */ static PyObject * reconstruct_method(PyObject *func, PyObject *self) { if (self) { return PyMethod_New(func, self); } else { Py_INCREF(func); return func; } } static PyObject * call_method(PyObject *func, PyObject *self, PyObject *obj) { if (self) { return PyObject_CallFunctionObjArgs(func, self, obj, NULL); } else { return PyObject_CallFunctionObjArgs(func, obj, NULL); } } /*************************************************************************/ /* Internal data type used as the unpickling stack. */ typedef struct { PyObject_VAR_HEAD PyObject **data; int mark_set; /* is MARK set? */ Py_ssize_t fence; /* position of top MARK or 0 */ Py_ssize_t allocated; /* number of slots in data allocated */ } Pdata; static void Pdata_dealloc(Pdata *self) { Py_ssize_t i = Py_SIZE(self); while (--i >= 0) { Py_DECREF(self->data[i]); } PyMem_FREE(self->data); PyObject_Del(self); } static PyTypeObject Pdata_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_pickle.Pdata", /*tp_name*/ sizeof(Pdata), /*tp_basicsize*/ sizeof(PyObject *), /*tp_itemsize*/ (destructor)Pdata_dealloc, /*tp_dealloc*/ }; static PyObject * Pdata_New(void) { Pdata *self; if (!(self = PyObject_New(Pdata, &Pdata_Type))) return NULL; Py_SIZE(self) = 0; self->mark_set = 0; self->fence = 0; self->allocated = 8; self->data = PyMem_MALLOC(self->allocated * sizeof(PyObject *)); if (self->data) return (PyObject *)self; Py_DECREF(self); return PyErr_NoMemory(); } /* Retain only the initial clearto items. If clearto >= the current * number of items, this is a (non-erroneous) NOP. */ static int Pdata_clear(Pdata *self, Py_ssize_t clearto) { Py_ssize_t i = Py_SIZE(self); assert(clearto >= self->fence); if (clearto >= i) return 0; while (--i >= clearto) { Py_CLEAR(self->data[i]); } Py_SIZE(self) = clearto; return 0; } static int Pdata_grow(Pdata *self) { PyObject **data = self->data; size_t allocated = (size_t)self->allocated; size_t new_allocated; new_allocated = (allocated >> 3) + 6; /* check for integer overflow */ if (new_allocated > (size_t)PY_SSIZE_T_MAX - allocated) goto nomemory; new_allocated += allocated; PyMem_RESIZE(data, PyObject *, new_allocated); if (data == NULL) goto nomemory; self->data = data; self->allocated = (Py_ssize_t)new_allocated; return 0; nomemory: PyErr_NoMemory(); return -1; } static int Pdata_stack_underflow(Pdata *self) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, self->mark_set ? "unexpected MARK found" : "unpickling stack underflow"); return -1; } /* D is a Pdata*. Pop the topmost element and store it into V, which * must be an lvalue holding PyObject*. On stack underflow, UnpicklingError * is raised and V is set to NULL. */ static PyObject * Pdata_pop(Pdata *self) { if (Py_SIZE(self) <= self->fence) { Pdata_stack_underflow(self); return NULL; } return self->data[--Py_SIZE(self)]; } #define PDATA_POP(D, V) do { (V) = Pdata_pop((D)); } while (0) static int Pdata_push(Pdata *self, PyObject *obj) { if (Py_SIZE(self) == self->allocated && Pdata_grow(self) < 0) { return -1; } self->data[Py_SIZE(self)++] = obj; return 0; } /* Push an object on stack, transferring its ownership to the stack. */ #define PDATA_PUSH(D, O, ER) do { \ if (Pdata_push((D), (O)) < 0) return (ER); } while(0) /* Push an object on stack, adding a new reference to the object. */ #define PDATA_APPEND(D, O, ER) do { \ Py_INCREF((O)); \ if (Pdata_push((D), (O)) < 0) return (ER); } while(0) static PyObject * Pdata_poptuple(Pdata *self, Py_ssize_t start) { PyObject *tuple; Py_ssize_t len, i, j; if (start < self->fence) { Pdata_stack_underflow(self); return NULL; } len = Py_SIZE(self) - start; tuple = PyTuple_New(len); if (tuple == NULL) return NULL; for (i = start, j = 0; j < len; i++, j++) PyTuple_SET_ITEM(tuple, j, self->data[i]); Py_SIZE(self) = start; return tuple; } static PyObject * Pdata_poplist(Pdata *self, Py_ssize_t start) { PyObject *list; Py_ssize_t len, i, j; len = Py_SIZE(self) - start; list = PyList_New(len); if (list == NULL) return NULL; for (i = start, j = 0; j < len; i++, j++) PyList_SET_ITEM(list, j, self->data[i]); Py_SIZE(self) = start; return list; } typedef struct { PyObject *me_key; Py_ssize_t me_value; } PyMemoEntry; typedef struct { size_t mt_mask; size_t mt_used; size_t mt_allocated; PyMemoEntry *mt_table; } PyMemoTable; typedef struct PicklerObject { PyObject_HEAD PyMemoTable *memo; /* Memo table, keep track of the seen objects to support self-referential objects pickling. */ PyObject *pers_func; /* persistent_id() method, can be NULL */ PyObject *pers_func_self; /* borrowed reference to self if pers_func is an unbound method, NULL otherwise */ PyObject *dispatch_table; /* private dispatch_table, can be NULL */ PyObject *write; /* write() method of the output stream. */ PyObject *output_buffer; /* Write into a local bytearray buffer before flushing to the stream. */ Py_ssize_t output_len; /* Length of output_buffer. */ Py_ssize_t max_output_len; /* Allocation size of output_buffer. */ int proto; /* Pickle protocol number, >= 0 */ int bin; /* Boolean, true if proto > 0 */ int framing; /* True when framing is enabled, proto >= 4 */ Py_ssize_t frame_start; /* Position in output_buffer where the current frame begins. -1 if there is no frame currently open. */ Py_ssize_t buf_size; /* Size of the current buffered pickle data */ int fast; /* Enable fast mode if set to a true value. The fast mode disable the usage of memo, therefore speeding the pickling process by not generating superfluous PUT opcodes. It should not be used if with self-referential objects. */ int fast_nesting; int fix_imports; /* Indicate whether Pickler should fix the name of globals for Python 2.x. */ PyObject *fast_memo; } PicklerObject; typedef struct UnpicklerObject { PyObject_HEAD Pdata *stack; /* Pickle data stack, store unpickled objects. */ /* The unpickler memo is just an array of PyObject *s. Using a dict is unnecessary, since the keys are contiguous ints. */ PyObject **memo; size_t memo_size; /* Capacity of the memo array */ size_t memo_len; /* Number of objects in the memo */ PyObject *pers_func; /* persistent_load() method, can be NULL. */ PyObject *pers_func_self; /* borrowed reference to self if pers_func is an unbound method, NULL otherwise */ Py_buffer buffer; char *input_buffer; char *input_line; Py_ssize_t input_len; Py_ssize_t next_read_idx; Py_ssize_t prefetched_idx; /* index of first prefetched byte */ PyObject *read; /* read() method of the input stream. */ PyObject *readline; /* readline() method of the input stream. */ PyObject *peek; /* peek() method of the input stream, or NULL */ char *encoding; /* Name of the encoding to be used for decoding strings pickled using Python 2.x. The default value is "ASCII" */ char *errors; /* Name of errors handling scheme to used when decoding strings. The default value is "strict". */ Py_ssize_t *marks; /* Mark stack, used for unpickling container objects. */ Py_ssize_t num_marks; /* Number of marks in the mark stack. */ Py_ssize_t marks_size; /* Current allocated size of the mark stack. */ int proto; /* Protocol of the pickle loaded. */ int fix_imports; /* Indicate whether Unpickler should fix the name of globals pickled by Python 2.x. */ } UnpicklerObject; typedef struct { PyObject_HEAD PicklerObject *pickler; /* Pickler whose memo table we're proxying. */ } PicklerMemoProxyObject; typedef struct { PyObject_HEAD UnpicklerObject *unpickler; } UnpicklerMemoProxyObject; /* Forward declarations */ static int save(PicklerObject *, PyObject *, int); static int save_reduce(PicklerObject *, PyObject *, PyObject *); static PyTypeObject Pickler_Type; static PyTypeObject Unpickler_Type; #include "clinic/_pickle.c.h" /************************************************************************* A custom hashtable mapping void* to Python ints. This is used by the pickler for memoization. Using a custom hashtable rather than PyDict allows us to skip a bunch of unnecessary object creation. This makes a huge performance difference. */ #define MT_MINSIZE 8 #define PERTURB_SHIFT 5 static PyMemoTable * PyMemoTable_New(void) { PyMemoTable *memo = PyMem_MALLOC(sizeof(PyMemoTable)); if (memo == NULL) { PyErr_NoMemory(); return NULL; } memo->mt_used = 0; memo->mt_allocated = MT_MINSIZE; memo->mt_mask = MT_MINSIZE - 1; memo->mt_table = PyMem_MALLOC(MT_MINSIZE * sizeof(PyMemoEntry)); if (memo->mt_table == NULL) { PyMem_FREE(memo); PyErr_NoMemory(); return NULL; } memset(memo->mt_table, 0, MT_MINSIZE * sizeof(PyMemoEntry)); return memo; } static PyMemoTable * PyMemoTable_Copy(PyMemoTable *self) { PyMemoTable *new = PyMemoTable_New(); if (new == NULL) return NULL; new->mt_used = self->mt_used; new->mt_allocated = self->mt_allocated; new->mt_mask = self->mt_mask; /* The table we get from _New() is probably smaller than we wanted. Free it and allocate one that's the right size. */ PyMem_FREE(new->mt_table); new->mt_table = PyMem_NEW(PyMemoEntry, self->mt_allocated); if (new->mt_table == NULL) { PyMem_FREE(new); PyErr_NoMemory(); return NULL; } for (size_t i = 0; i < self->mt_allocated; i++) { Py_XINCREF(self->mt_table[i].me_key); } memcpy(new->mt_table, self->mt_table, sizeof(PyMemoEntry) * self->mt_allocated); return new; } static Py_ssize_t PyMemoTable_Size(PyMemoTable *self) { return self->mt_used; } static int PyMemoTable_Clear(PyMemoTable *self) { Py_ssize_t i = self->mt_allocated; while (--i >= 0) { Py_XDECREF(self->mt_table[i].me_key); } self->mt_used = 0; memset(self->mt_table, 0, self->mt_allocated * sizeof(PyMemoEntry)); return 0; } static void PyMemoTable_Del(PyMemoTable *self) { if (self == NULL) return; PyMemoTable_Clear(self); PyMem_FREE(self->mt_table); PyMem_FREE(self); } /* Since entries cannot be deleted from this hashtable, _PyMemoTable_Lookup() can be considerably simpler than dictobject.c's lookdict(). */ static PyMemoEntry * _PyMemoTable_Lookup(PyMemoTable *self, PyObject *key) { size_t i; size_t perturb; size_t mask = self->mt_mask; PyMemoEntry *table = self->mt_table; PyMemoEntry *entry; Py_hash_t hash = (Py_hash_t)key >> 3; i = hash & mask; entry = &table[i]; if (entry->me_key == NULL || entry->me_key == key) return entry; for (perturb = hash; ; perturb >>= PERTURB_SHIFT) { i = (i << 2) + i + perturb + 1; entry = &table[i & mask]; if (entry->me_key == NULL || entry->me_key == key) return entry; } Py_UNREACHABLE(); } /* Returns -1 on failure, 0 on success. */ static int _PyMemoTable_ResizeTable(PyMemoTable *self, size_t min_size) { PyMemoEntry *oldtable = NULL; PyMemoEntry *oldentry, *newentry; size_t new_size = MT_MINSIZE; size_t to_process; assert(min_size > 0); if (min_size > PY_SSIZE_T_MAX) { PyErr_NoMemory(); return -1; } /* Find the smallest valid table size >= min_size. */ while (new_size < min_size) { new_size <<= 1; } /* new_size needs to be a power of two. */ assert((new_size & (new_size - 1)) == 0); /* Allocate new table. */ oldtable = self->mt_table; self->mt_table = PyMem_NEW(PyMemoEntry, new_size); if (self->mt_table == NULL) { self->mt_table = oldtable; PyErr_NoMemory(); return -1; } self->mt_allocated = new_size; self->mt_mask = new_size - 1; memset(self->mt_table, 0, sizeof(PyMemoEntry) * new_size); /* Copy entries from the old table. */ to_process = self->mt_used; for (oldentry = oldtable; to_process > 0; oldentry++) { if (oldentry->me_key != NULL) { to_process--; /* newentry is a pointer to a chunk of the new mt_table, so we're setting the key:value pair in-place. */ newentry = _PyMemoTable_Lookup(self, oldentry->me_key); newentry->me_key = oldentry->me_key; newentry->me_value = oldentry->me_value; } } /* Deallocate the old table. */ PyMem_FREE(oldtable); return 0; } /* Returns NULL on failure, a pointer to the value otherwise. */ static Py_ssize_t * PyMemoTable_Get(PyMemoTable *self, PyObject *key) { PyMemoEntry *entry = _PyMemoTable_Lookup(self, key); if (entry->me_key == NULL) return NULL; return &entry->me_value; } /* Returns -1 on failure, 0 on success. */ static int PyMemoTable_Set(PyMemoTable *self, PyObject *key, Py_ssize_t value) { PyMemoEntry *entry; assert(key != NULL); entry = _PyMemoTable_Lookup(self, key); if (entry->me_key != NULL) { entry->me_value = value; return 0; } Py_INCREF(key); entry->me_key = key; entry->me_value = value; self->mt_used++; /* If we added a key, we can safely resize. Otherwise just return! * If used >= 2/3 size, adjust size. Normally, this quaduples the size. * * Quadrupling the size improves average table sparseness * (reducing collisions) at the cost of some memory. It also halves * the number of expensive resize operations in a growing memo table. * * Very large memo tables (over 50K items) use doubling instead. * This may help applications with severe memory constraints. */ if (SIZE_MAX / 3 >= self->mt_used && self->mt_used * 3 < self->mt_allocated * 2) { return 0; } // self->mt_used is always < PY_SSIZE_T_MAX, so this can't overflow. size_t desired_size = (self->mt_used > 50000 ? 2 : 4) * self->mt_used; return _PyMemoTable_ResizeTable(self, desired_size); } #undef MT_MINSIZE #undef PERTURB_SHIFT /*************************************************************************/ static int _Pickler_ClearBuffer(PicklerObject *self) { Py_XSETREF(self->output_buffer, PyBytes_FromStringAndSize(NULL, self->max_output_len)); if (self->output_buffer == NULL) return -1; self->output_len = 0; self->frame_start = -1; return 0; } static void _write_size64(char *out, size_t value) { size_t i; Py_BUILD_ASSERT(sizeof(size_t) <= 8); for (i = 0; i < sizeof(size_t); i++) { out[i] = (unsigned char)((value >> (8 * i)) & 0xff); } for (i = sizeof(size_t); i < 8; i++) { out[i] = 0; } } static int _Pickler_CommitFrame(PicklerObject *self) { size_t frame_len; char *qdata; if (!self->framing || self->frame_start == -1) return 0; frame_len = self->output_len - self->frame_start - FRAME_HEADER_SIZE; qdata = PyBytes_AS_STRING(self->output_buffer) + self->frame_start; if (frame_len >= FRAME_SIZE_MIN) { qdata[0] = FRAME; _write_size64(qdata + 1, frame_len); } else { memmove(qdata, qdata + FRAME_HEADER_SIZE, frame_len); self->output_len -= FRAME_HEADER_SIZE; } self->frame_start = -1; return 0; } static PyObject * _Pickler_GetString(PicklerObject *self) { PyObject *output_buffer = self->output_buffer; assert(self->output_buffer != NULL); if (_Pickler_CommitFrame(self)) return NULL; self->output_buffer = NULL; /* Resize down to exact size */ if (_PyBytes_Resize(&output_buffer, self->output_len) < 0) return NULL; return output_buffer; } static int _Pickler_FlushToFile(PicklerObject *self) { PyObject *output, *result; assert(self->write != NULL); /* This will commit the frame first */ output = _Pickler_GetString(self); if (output == NULL) return -1; result = _Pickle_FastCall(self->write, output); Py_XDECREF(result); return (result == NULL) ? -1 : 0; } static int _Pickler_OpcodeBoundary(PicklerObject *self) { Py_ssize_t frame_len; if (!self->framing || self->frame_start == -1) { return 0; } frame_len = self->output_len - self->frame_start - FRAME_HEADER_SIZE; if (frame_len >= FRAME_SIZE_TARGET) { if(_Pickler_CommitFrame(self)) { return -1; } /* Flush the content of the committed frame to the underlying * file and reuse the pickler buffer for the next frame so as * to limit memory usage when dumping large complex objects to * a file. * * self->write is NULL when called via dumps. */ if (self->write != NULL) { if (_Pickler_FlushToFile(self) < 0) { return -1; } if (_Pickler_ClearBuffer(self) < 0) { return -1; } } } return 0; } static Py_ssize_t _Pickler_Write(PicklerObject *self, const char *s, Py_ssize_t data_len) { Py_ssize_t i, n, required; char *buffer; int need_new_frame; assert(s != NULL); need_new_frame = (self->framing && self->frame_start == -1); if (need_new_frame) n = data_len + FRAME_HEADER_SIZE; else n = data_len; required = self->output_len + n; if (required > self->max_output_len) { /* Make place in buffer for the pickle chunk */ if (self->output_len >= PY_SSIZE_T_MAX / 2 - n) { PyErr_NoMemory(); return -1; } self->max_output_len = (self->output_len + n) / 2 * 3; if (_PyBytes_Resize(&self->output_buffer, self->max_output_len) < 0) return -1; } buffer = PyBytes_AS_STRING(self->output_buffer); if (need_new_frame) { /* Setup new frame */ Py_ssize_t frame_start = self->output_len; self->frame_start = frame_start; for (i = 0; i < FRAME_HEADER_SIZE; i++) { /* Write an invalid value, for debugging */ buffer[frame_start + i] = 0xFE; } self->output_len += FRAME_HEADER_SIZE; } if (data_len < 8) { /* This is faster than memcpy when the string is short. */ for (i = 0; i < data_len; i++) { buffer[self->output_len + i] = s[i]; } } else { memcpy(buffer + self->output_len, s, data_len); } self->output_len += data_len; return data_len; } static PicklerObject * _Pickler_New(void) { PicklerObject *self; self = PyObject_GC_New(PicklerObject, &Pickler_Type); if (self == NULL) return NULL; self->pers_func = NULL; self->dispatch_table = NULL; self->write = NULL; self->proto = 0; self->bin = 0; self->framing = 0; self->frame_start = -1; self->fast = 0; self->fast_nesting = 0; self->fix_imports = 0; self->fast_memo = NULL; self->max_output_len = WRITE_BUF_SIZE; self->output_len = 0; self->memo = PyMemoTable_New(); self->output_buffer = PyBytes_FromStringAndSize(NULL, self->max_output_len); if (self->memo == NULL || self->output_buffer == NULL) { Py_DECREF(self); return NULL; } return self; } static int _Pickler_SetProtocol(PicklerObject *self, PyObject *protocol, int fix_imports) { long proto; if (protocol == NULL || protocol == Py_None) { proto = DEFAULT_PROTOCOL; } else { proto = PyLong_AsLong(protocol); if (proto < 0) { if (proto == -1 && PyErr_Occurred()) return -1; proto = HIGHEST_PROTOCOL; } else if (proto > HIGHEST_PROTOCOL) { PyErr_Format(PyExc_ValueError, "pickle protocol must be <= %d", HIGHEST_PROTOCOL); return -1; } } self->proto = (int)proto; self->bin = proto > 0; self->fix_imports = fix_imports && proto < 3; return 0; } /* Returns -1 (with an exception set) on failure, 0 on success. This may be called once on a freshly created Pickler. */ static int _Pickler_SetOutputStream(PicklerObject *self, PyObject *file) { _Py_IDENTIFIER(write); assert(file != NULL); if (_PyObject_LookupAttrId(file, &PyId_write, &self->write) < 0) { return -1; } if (self->write == NULL) { PyErr_SetString(PyExc_TypeError, "file must have a 'write' attribute"); return -1; } return 0; } /* Returns the size of the input on success, -1 on failure. This takes its own reference to `input`. */ static Py_ssize_t _Unpickler_SetStringInput(UnpicklerObject *self, PyObject *input) { if (self->buffer.buf != NULL) PyBuffer_Release(&self->buffer); if (PyObject_GetBuffer(input, &self->buffer, PyBUF_CONTIG_RO) < 0) return -1; self->input_buffer = self->buffer.buf; self->input_len = self->buffer.len; self->next_read_idx = 0; self->prefetched_idx = self->input_len; return self->input_len; } static int bad_readline(void) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "pickle data was truncated"); return -1; } static int _Unpickler_SkipConsumed(UnpicklerObject *self) { Py_ssize_t consumed; PyObject *r; consumed = self->next_read_idx - self->prefetched_idx; if (consumed <= 0) return 0; assert(self->peek); /* otherwise we did something wrong */ /* This makes a useless copy... */ r = PyObject_CallFunction(self->read, "n", consumed); if (r == NULL) return -1; Py_DECREF(r); self->prefetched_idx = self->next_read_idx; return 0; } static const Py_ssize_t READ_WHOLE_LINE = -1; /* If reading from a file, we need to only pull the bytes we need, since there may be multiple pickle objects arranged contiguously in the same input buffer. If `n` is READ_WHOLE_LINE, read a whole line. Otherwise, read up to `n` bytes from the input stream/buffer. Update the unpickler's input buffer with the newly-read data. Returns -1 on failure; on success, returns the number of bytes read from the file. On success, self->input_len will be 0; this is intentional so that when unpickling from a file, the "we've run out of data" code paths will trigger, causing the Unpickler to go back to the file for more data. Use the returned size to tell you how much data you can process. */ static Py_ssize_t _Unpickler_ReadFromFile(UnpicklerObject *self, Py_ssize_t n) { PyObject *data; Py_ssize_t read_size; assert(self->read != NULL); if (_Unpickler_SkipConsumed(self) < 0) return -1; if (n == READ_WHOLE_LINE) { data = _PyObject_CallNoArg(self->readline); } else { PyObject *len; /* Prefetch some data without advancing the file pointer, if possible */ if (self->peek && n < PREFETCH) { len = PyLong_FromSsize_t(PREFETCH); if (len == NULL) return -1; data = _Pickle_FastCall(self->peek, len); if (data == NULL) { if (!PyErr_ExceptionMatches(PyExc_NotImplementedError)) return -1; /* peek() is probably not supported by the given file object */ PyErr_Clear(); Py_CLEAR(self->peek); } else { read_size = _Unpickler_SetStringInput(self, data); Py_DECREF(data); self->prefetched_idx = 0; if (n <= read_size) return n; } } len = PyLong_FromSsize_t(n); if (len == NULL) return -1; data = _Pickle_FastCall(self->read, len); } if (data == NULL) return -1; read_size = _Unpickler_SetStringInput(self, data); Py_DECREF(data); return read_size; } /* Don't call it directly: use _Unpickler_Read() */ static Py_ssize_t _Unpickler_ReadImpl(UnpicklerObject *self, char **s, Py_ssize_t n) { Py_ssize_t num_read; *s = NULL; if (self->next_read_idx > PY_SSIZE_T_MAX - n) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "read would overflow (invalid bytecode)"); return -1; } /* This case is handled by the _Unpickler_Read() macro for efficiency */ assert(self->next_read_idx + n > self->input_len); if (!self->read) return bad_readline(); num_read = _Unpickler_ReadFromFile(self, n); if (num_read < 0) return -1; if (num_read < n) return bad_readline(); *s = self->input_buffer; self->next_read_idx = n; return n; } /* Read `n` bytes from the unpickler's data source, storing the result in `*s`. This should be used for all data reads, rather than accessing the unpickler's input buffer directly. This method deals correctly with reading from input streams, which the input buffer doesn't deal with. Note that when reading from a file-like object, self->next_read_idx won't be updated (it should remain at 0 for the entire unpickling process). You should use this function's return value to know how many bytes you can consume. Returns -1 (with an exception set) on failure. On success, return the number of chars read. */ #define _Unpickler_Read(self, s, n) \ (((n) <= (self)->input_len - (self)->next_read_idx) \ ? (*(s) = (self)->input_buffer + (self)->next_read_idx, \ (self)->next_read_idx += (n), \ (n)) \ : _Unpickler_ReadImpl(self, (s), (n))) static Py_ssize_t _Unpickler_CopyLine(UnpicklerObject *self, char *line, Py_ssize_t len, char **result) { char *input_line = PyMem_Realloc(self->input_line, len + 1); if (input_line == NULL) { PyErr_NoMemory(); return -1; } memcpy(input_line, line, len); input_line[len] = '\0'; self->input_line = input_line; *result = self->input_line; return len; } /* Read a line from the input stream/buffer. If we run off the end of the input before hitting \n, raise an error. Returns the number of chars read, or -1 on failure. */ static Py_ssize_t _Unpickler_Readline(UnpicklerObject *self, char **result) { Py_ssize_t i, num_read; for (i = self->next_read_idx; i < self->input_len; i++) { if (self->input_buffer[i] == '\n') { char *line_start = self->input_buffer + self->next_read_idx; num_read = i - self->next_read_idx + 1; self->next_read_idx = i + 1; return _Unpickler_CopyLine(self, line_start, num_read, result); } } if (!self->read) return bad_readline(); num_read = _Unpickler_ReadFromFile(self, READ_WHOLE_LINE); if (num_read < 0) return -1; if (num_read == 0 || self->input_buffer[num_read - 1] != '\n') return bad_readline(); self->next_read_idx = num_read; return _Unpickler_CopyLine(self, self->input_buffer, num_read, result); } /* Returns -1 (with an exception set) on failure, 0 on success. The memo array will be modified in place. */ static int _Unpickler_ResizeMemoList(UnpicklerObject *self, size_t new_size) { size_t i; assert(new_size > self->memo_size); PyObject **memo_new = self->memo; PyMem_RESIZE(memo_new, PyObject *, new_size); if (memo_new == NULL) { PyErr_NoMemory(); return -1; } self->memo = memo_new; for (i = self->memo_size; i < new_size; i++) self->memo[i] = NULL; self->memo_size = new_size; return 0; } /* Returns NULL if idx is out of bounds. */ static PyObject * _Unpickler_MemoGet(UnpicklerObject *self, size_t idx) { if (idx >= self->memo_size) return NULL; return self->memo[idx]; } /* Returns -1 (with an exception set) on failure, 0 on success. This takes its own reference to `value`. */ static int _Unpickler_MemoPut(UnpicklerObject *self, size_t idx, PyObject *value) { PyObject *old_item; if (idx >= self->memo_size) { if (_Unpickler_ResizeMemoList(self, idx * 2) < 0) return -1; assert(idx < self->memo_size); } Py_INCREF(value); old_item = self->memo[idx]; self->memo[idx] = value; if (old_item != NULL) { Py_DECREF(old_item); } else { self->memo_len++; } return 0; } static PyObject ** _Unpickler_NewMemo(Py_ssize_t new_size) { PyObject **memo = PyMem_NEW(PyObject *, new_size); if (memo == NULL) { PyErr_NoMemory(); return NULL; } memset(memo, 0, new_size * sizeof(PyObject *)); return memo; } /* Free the unpickler's memo, taking care to decref any items left in it. */ static void _Unpickler_MemoCleanup(UnpicklerObject *self) { Py_ssize_t i; PyObject **memo = self->memo; if (self->memo == NULL) return; self->memo = NULL; i = self->memo_size; while (--i >= 0) { Py_XDECREF(memo[i]); } PyMem_FREE(memo); } static UnpicklerObject * _Unpickler_New(void) { UnpicklerObject *self; self = PyObject_GC_New(UnpicklerObject, &Unpickler_Type); if (self == NULL) return NULL; self->pers_func = NULL; self->input_buffer = NULL; self->input_line = NULL; self->input_len = 0; self->next_read_idx = 0; self->prefetched_idx = 0; self->read = NULL; self->readline = NULL; self->peek = NULL; self->encoding = NULL; self->errors = NULL; self->marks = NULL; self->num_marks = 0; self->marks_size = 0; self->proto = 0; self->fix_imports = 0; memset(&self->buffer, 0, sizeof(Py_buffer)); self->memo_size = 32; self->memo_len = 0; self->memo = _Unpickler_NewMemo(self->memo_size); self->stack = (Pdata *)Pdata_New(); if (self->memo == NULL || self->stack == NULL) { Py_DECREF(self); return NULL; } return self; } /* Returns -1 (with an exception set) on failure, 0 on success. This may be called once on a freshly created Pickler. */ static int _Unpickler_SetInputStream(UnpicklerObject *self, PyObject *file) { _Py_IDENTIFIER(peek); _Py_IDENTIFIER(read); _Py_IDENTIFIER(readline); if (_PyObject_LookupAttrId(file, &PyId_peek, &self->peek) < 0) { return -1; } (void)_PyObject_LookupAttrId(file, &PyId_read, &self->read); (void)_PyObject_LookupAttrId(file, &PyId_readline, &self->readline); if (self->readline == NULL || self->read == NULL) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "file must have 'read' and 'readline' attributes"); } Py_CLEAR(self->read); Py_CLEAR(self->readline); Py_CLEAR(self->peek); return -1; } return 0; } /* Returns -1 (with an exception set) on failure, 0 on success. This may be called once on a freshly created Pickler. */ static int _Unpickler_SetInputEncoding(UnpicklerObject *self, const char *encoding, const char *errors) { if (encoding == NULL) encoding = "ASCII"; if (errors == NULL) errors = "strict"; self->encoding = _PyMem_Strdup(encoding); self->errors = _PyMem_Strdup(errors); if (self->encoding == NULL || self->errors == NULL) { PyErr_NoMemory(); return -1; } return 0; } /* Generate a GET opcode for an object stored in the memo. */ static int memo_get(PicklerObject *self, PyObject *key) { Py_ssize_t *value; char pdata[30]; Py_ssize_t len; value = PyMemoTable_Get(self->memo, key); if (value == NULL) { PyErr_SetObject(PyExc_KeyError, key); return -1; } if (!self->bin) { pdata[0] = GET; PyOS_snprintf(pdata + 1, sizeof(pdata) - 1, "%" PY_FORMAT_SIZE_T "d\n", *value); len = strlen(pdata); } else { if (*value < 256) { pdata[0] = BINGET; pdata[1] = (unsigned char)(*value & 0xff); len = 2; } else if ((size_t)*value <= 0xffffffffUL) { pdata[0] = LONG_BINGET; pdata[1] = (unsigned char)(*value & 0xff); pdata[2] = (unsigned char)((*value >> 8) & 0xff); pdata[3] = (unsigned char)((*value >> 16) & 0xff); pdata[4] = (unsigned char)((*value >> 24) & 0xff); len = 5; } else { /* unlikely */ PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->PicklingError, "memo id too large for LONG_BINGET"); return -1; } } if (_Pickler_Write(self, pdata, len) < 0) return -1; return 0; } /* Store an object in the memo, assign it a new unique ID based on the number of objects currently stored in the memo and generate a PUT opcode. */ static int memo_put(PicklerObject *self, PyObject *obj) { char pdata[30]; Py_ssize_t len; Py_ssize_t idx; const char memoize_op = MEMOIZE; if (self->fast) return 0; idx = PyMemoTable_Size(self->memo); if (PyMemoTable_Set(self->memo, obj, idx) < 0) return -1; if (self->proto >= 4) { if (_Pickler_Write(self, &memoize_op, 1) < 0) return -1; return 0; } else if (!self->bin) { pdata[0] = PUT; PyOS_snprintf(pdata + 1, sizeof(pdata) - 1, "%" PY_FORMAT_SIZE_T "d\n", idx); len = strlen(pdata); } else { if (idx < 256) { pdata[0] = BINPUT; pdata[1] = (unsigned char)idx; len = 2; } else if ((size_t)idx <= 0xffffffffUL) { pdata[0] = LONG_BINPUT; pdata[1] = (unsigned char)(idx & 0xff); pdata[2] = (unsigned char)((idx >> 8) & 0xff); pdata[3] = (unsigned char)((idx >> 16) & 0xff); pdata[4] = (unsigned char)((idx >> 24) & 0xff); len = 5; } else { /* unlikely */ PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->PicklingError, "memo id too large for LONG_BINPUT"); return -1; } } if (_Pickler_Write(self, pdata, len) < 0) return -1; return 0; } static PyObject * get_dotted_path(PyObject *obj, PyObject *name) { _Py_static_string(PyId_dot, "."); PyObject *dotted_path; Py_ssize_t i, n; dotted_path = PyUnicode_Split(name, _PyUnicode_FromId(&PyId_dot), -1); if (dotted_path == NULL) return NULL; n = PyList_GET_SIZE(dotted_path); assert(n >= 1); for (i = 0; i < n; i++) { PyObject *subpath = PyList_GET_ITEM(dotted_path, i); if (_PyUnicode_EqualToASCIIString(subpath, "<locals>")) { if (obj == NULL) PyErr_Format(PyExc_AttributeError, "Can't pickle local object %R", name); else PyErr_Format(PyExc_AttributeError, "Can't pickle local attribute %R on %R", name, obj); Py_DECREF(dotted_path); return NULL; } } return dotted_path; } static PyObject * get_deep_attribute(PyObject *obj, PyObject *names, PyObject **pparent) { Py_ssize_t i, n; PyObject *parent = NULL; assert(PyList_CheckExact(names)); Py_INCREF(obj); n = PyList_GET_SIZE(names); for (i = 0; i < n; i++) { PyObject *name = PyList_GET_ITEM(names, i); Py_XDECREF(parent); parent = obj; (void)_PyObject_LookupAttr(parent, name, &obj); if (obj == NULL) { Py_DECREF(parent); return NULL; } } if (pparent != NULL) *pparent = parent; else Py_XDECREF(parent); return obj; } static PyObject * getattribute(PyObject *obj, PyObject *name, int allow_qualname) { PyObject *dotted_path, *attr; if (allow_qualname) { dotted_path = get_dotted_path(obj, name); if (dotted_path == NULL) return NULL; attr = get_deep_attribute(obj, dotted_path, NULL); Py_DECREF(dotted_path); } else { (void)_PyObject_LookupAttr(obj, name, &attr); } if (attr == NULL && !PyErr_Occurred()) { PyErr_Format(PyExc_AttributeError, "Can't get attribute %R on %R", name, obj); } return attr; } static int _checkmodule(PyObject *module_name, PyObject *module, PyObject *global, PyObject *dotted_path) { if (module == Py_None) { return -1; } if (PyUnicode_Check(module_name) && _PyUnicode_EqualToASCIIString(module_name, "__main__")) { return -1; } PyObject *candidate = get_deep_attribute(module, dotted_path, NULL); if (candidate == NULL) { return -1; } if (candidate != global) { Py_DECREF(candidate); return -1; } Py_DECREF(candidate); return 0; } static PyObject * whichmodule(PyObject *global, PyObject *dotted_path) { PyObject *module_name; PyObject *module = NULL; Py_ssize_t i; PyObject *modules; _Py_IDENTIFIER(__module__); _Py_IDENTIFIER(modules); _Py_IDENTIFIER(__main__); if (_PyObject_LookupAttrId(global, &PyId___module__, &module_name) < 0) { return NULL; } if (module_name) { /* In some rare cases (e.g., bound methods of extension types), __module__ can be None. If it is so, then search sys.modules for the module of global. */ if (module_name != Py_None) return module_name; Py_CLEAR(module_name); } assert(module_name == NULL); /* Fallback on walking sys.modules */ modules = _PySys_GetObjectId(&PyId_modules); if (modules == NULL) { PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules"); return NULL; } if (PyDict_CheckExact(modules)) { i = 0; while (PyDict_Next(modules, &i, &module_name, &module)) { if (_checkmodule(module_name, module, global, dotted_path) == 0) { Py_INCREF(module_name); return module_name; } if (PyErr_Occurred()) { return NULL; } } } else { PyObject *iterator = PyObject_GetIter(modules); if (iterator == NULL) { return NULL; } while ((module_name = PyIter_Next(iterator))) { module = PyObject_GetItem(modules, module_name); if (module == NULL) { Py_DECREF(module_name); Py_DECREF(iterator); return NULL; } if (_checkmodule(module_name, module, global, dotted_path) == 0) { Py_DECREF(module); Py_DECREF(iterator); return module_name; } Py_DECREF(module); Py_DECREF(module_name); if (PyErr_Occurred()) { Py_DECREF(iterator); return NULL; } } Py_DECREF(iterator); } /* If no module is found, use __main__. */ module_name = _PyUnicode_FromId(&PyId___main__); Py_XINCREF(module_name); return module_name; } /* fast_save_enter() and fast_save_leave() are guards against recursive objects when Pickler is used with the "fast mode" (i.e., with object memoization disabled). If the nesting of a list or dict object exceed FAST_NESTING_LIMIT, these guards will start keeping an internal reference to the seen list or dict objects and check whether these objects are recursive. These are not strictly necessary, since save() has a hard-coded recursion limit, but they give a nicer error message than the typical RuntimeError. */ static int fast_save_enter(PicklerObject *self, PyObject *obj) { /* if fast_nesting < 0, we're doing an error exit. */ if (++self->fast_nesting >= FAST_NESTING_LIMIT) { PyObject *key = NULL; if (self->fast_memo == NULL) { self->fast_memo = PyDict_New(); if (self->fast_memo == NULL) { self->fast_nesting = -1; return 0; } } key = PyLong_FromVoidPtr(obj); if (key == NULL) { self->fast_nesting = -1; return 0; } if (PyDict_GetItemWithError(self->fast_memo, key)) { Py_DECREF(key); PyErr_Format(PyExc_ValueError, "fast mode: can't pickle cyclic objects " "including object type %.200s at %p", obj->ob_type->tp_name, obj); self->fast_nesting = -1; return 0; } if (PyErr_Occurred()) { Py_DECREF(key); self->fast_nesting = -1; return 0; } if (PyDict_SetItem(self->fast_memo, key, Py_None) < 0) { Py_DECREF(key); self->fast_nesting = -1; return 0; } Py_DECREF(key); } return 1; } static int fast_save_leave(PicklerObject *self, PyObject *obj) { if (self->fast_nesting-- >= FAST_NESTING_LIMIT) { PyObject *key = PyLong_FromVoidPtr(obj); if (key == NULL) return 0; if (PyDict_DelItem(self->fast_memo, key) < 0) { Py_DECREF(key); return 0; } Py_DECREF(key); } return 1; } static int save_none(PicklerObject *self, PyObject *obj) { const char none_op = NONE; if (_Pickler_Write(self, &none_op, 1) < 0) return -1; return 0; } static int save_bool(PicklerObject *self, PyObject *obj) { if (self->proto >= 2) { const char bool_op = (obj == Py_True) ? NEWTRUE : NEWFALSE; if (_Pickler_Write(self, &bool_op, 1) < 0) return -1; } else { /* These aren't opcodes -- they're ways to pickle bools before protocol 2 * so that unpicklers written before bools were introduced unpickle them * as ints, but unpicklers after can recognize that bools were intended. * Note that protocol 2 added direct ways to pickle bools. */ const char *bool_str = (obj == Py_True) ? "I01\n" : "I00\n"; if (_Pickler_Write(self, bool_str, strlen(bool_str)) < 0) return -1; } return 0; } static int save_long(PicklerObject *self, PyObject *obj) { PyObject *repr = NULL; Py_ssize_t size; long val; int overflow; int status = 0; val= PyLong_AsLongAndOverflow(obj, &overflow); if (!overflow && (sizeof(long) <= 4 || (val <= 0x7fffffffL && val >= (-0x7fffffffL - 1)))) { /* result fits in a signed 4-byte integer. Note: we can't use -0x80000000L in the above condition because some compilers (e.g., MSVC) will promote 0x80000000L to an unsigned type before applying the unary minus when sizeof(long) <= 4. The resulting value stays unsigned which is commonly not what we want, so MSVC happily warns us about it. However, that result would have been fine because we guard for sizeof(long) <= 4 which turns the condition true in that particular case. */ char pdata[32]; Py_ssize_t len = 0; if (self->bin) { pdata[1] = (unsigned char)(val & 0xff); pdata[2] = (unsigned char)((val >> 8) & 0xff); pdata[3] = (unsigned char)((val >> 16) & 0xff); pdata[4] = (unsigned char)((val >> 24) & 0xff); if ((pdata[4] != 0) || (pdata[3] != 0)) { pdata[0] = BININT; len = 5; } else if (pdata[2] != 0) { pdata[0] = BININT2; len = 3; } else { pdata[0] = BININT1; len = 2; } } else { sprintf(pdata, "%c%ld\n", INT, val); len = strlen(pdata); } if (_Pickler_Write(self, pdata, len) < 0) return -1; return 0; } assert(!PyErr_Occurred()); if (self->proto >= 2) { /* Linear-time pickling. */ size_t nbits; size_t nbytes; unsigned char *pdata; char header[5]; int i; int sign = _PyLong_Sign(obj); if (sign == 0) { header[0] = LONG1; header[1] = 0; /* It's 0 -- an empty bytestring. */ if (_Pickler_Write(self, header, 2) < 0) goto error; return 0; } nbits = _PyLong_NumBits(obj); if (nbits == (size_t)-1 && PyErr_Occurred()) goto error; /* How many bytes do we need? There are nbits >> 3 full * bytes of data, and nbits & 7 leftover bits. If there * are any leftover bits, then we clearly need another * byte. Wnat's not so obvious is that we *probably* * need another byte even if there aren't any leftovers: * the most-significant bit of the most-significant byte * acts like a sign bit, and it's usually got a sense * opposite of the one we need. The exception is ints * of the form -(2**(8*j-1)) for j > 0. Such an int is * its own 256's-complement, so has the right sign bit * even without the extra byte. That's a pain to check * for in advance, though, so we always grab an extra * byte at the start, and cut it back later if possible. */ nbytes = (nbits >> 3) + 1; if (nbytes > 0x7fffffffL) { PyErr_SetString(PyExc_OverflowError, "int too large to pickle"); goto error; } repr = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)nbytes); if (repr == NULL) goto error; pdata = (unsigned char *)PyBytes_AS_STRING(repr); i = _PyLong_AsByteArray((PyLongObject *)obj, pdata, nbytes, 1 /* little endian */ , 1 /* signed */ ); if (i < 0) goto error; /* If the int is negative, this may be a byte more than * needed. This is so iff the MSB is all redundant sign * bits. */ if (sign < 0 && nbytes > 1 && pdata[nbytes - 1] == 0xff && (pdata[nbytes - 2] & 0x80) != 0) { nbytes--; } if (nbytes < 256) { header[0] = LONG1; header[1] = (unsigned char)nbytes; size = 2; } else { header[0] = LONG4; size = (Py_ssize_t) nbytes; for (i = 1; i < 5; i++) { header[i] = (unsigned char)(size & 0xff); size >>= 8; } size = 5; } if (_Pickler_Write(self, header, size) < 0 || _Pickler_Write(self, (char *)pdata, (int)nbytes) < 0) goto error; } else { const char long_op = LONG; const char *string; /* proto < 2: write the repr and newline. This is quadratic-time (in the number of digits), in both directions. We add a trailing 'L' to the repr, for compatibility with Python 2.x. */ repr = PyObject_Repr(obj); if (repr == NULL) goto error; string = PyUnicode_AsUTF8AndSize(repr, &size); if (string == NULL) goto error; if (_Pickler_Write(self, &long_op, 1) < 0 || _Pickler_Write(self, string, size) < 0 || _Pickler_Write(self, "L\n", 2) < 0) goto error; } if (0) { error: status = -1; } Py_XDECREF(repr); return status; } static int save_float(PicklerObject *self, PyObject *obj) { double x = PyFloat_AS_DOUBLE((PyFloatObject *)obj); if (self->bin) { char pdata[9]; pdata[0] = BINFLOAT; if (_PyFloat_Pack8(x, (unsigned char *)&pdata[1], 0) < 0) return -1; if (_Pickler_Write(self, pdata, 9) < 0) return -1; } else { int result = -1; char *buf = NULL; char op = FLOAT; if (_Pickler_Write(self, &op, 1) < 0) goto done; buf = PyOS_double_to_string(x, 'r', 0, Py_DTSF_ADD_DOT_0, NULL); if (!buf) { PyErr_NoMemory(); goto done; } if (_Pickler_Write(self, buf, strlen(buf)) < 0) goto done; if (_Pickler_Write(self, "\n", 1) < 0) goto done; result = 0; done: PyMem_Free(buf); return result; } return 0; } /* Perform direct write of the header and payload of the binary object. The large contiguous data is written directly into the underlying file object, bypassing the output_buffer of the Pickler. We intentionally do not insert a protocol 4 frame opcode to make it possible to optimize file.read calls in the loader. */ static int _Pickler_write_bytes(PicklerObject *self, const char *header, Py_ssize_t header_size, const char *data, Py_ssize_t data_size, PyObject *payload) { int bypass_buffer = (data_size >= FRAME_SIZE_TARGET); int framing = self->framing; if (bypass_buffer) { assert(self->output_buffer != NULL); /* Commit the previous frame. */ if (_Pickler_CommitFrame(self)) { return -1; } /* Disable framing temporarily */ self->framing = 0; } if (_Pickler_Write(self, header, header_size) < 0) { return -1; } if (bypass_buffer && self->write != NULL) { /* Bypass the in-memory buffer to directly stream large data into the underlying file object. */ PyObject *result, *mem = NULL; /* Dump the output buffer to the file. */ if (_Pickler_FlushToFile(self) < 0) { return -1; } /* Stream write the payload into the file without going through the output buffer. */ if (payload == NULL) { /* TODO: It would be better to use a memoryview with a linked original string if this is possible. */ payload = mem = PyBytes_FromStringAndSize(data, data_size); if (payload == NULL) { return -1; } } result = PyObject_CallFunctionObjArgs(self->write, payload, NULL); Py_XDECREF(mem); if (result == NULL) { return -1; } Py_DECREF(result); /* Reinitialize the buffer for subsequent calls to _Pickler_Write. */ if (_Pickler_ClearBuffer(self) < 0) { return -1; } } else { if (_Pickler_Write(self, data, data_size) < 0) { return -1; } } /* Re-enable framing for subsequent calls to _Pickler_Write. */ self->framing = framing; return 0; } static int save_bytes(PicklerObject *self, PyObject *obj) { if (self->proto < 3) { /* Older pickle protocols do not have an opcode for pickling bytes objects. Therefore, we need to fake the copy protocol (i.e., the __reduce__ method) to permit bytes object unpickling. Here we use a hack to be compatible with Python 2. Since in Python 2 'bytes' is just an alias for 'str' (which has different parameters than the actual bytes object), we use codecs.encode to create the appropriate 'str' object when unpickled using Python 2 *and* the appropriate 'bytes' object when unpickled using Python 3. Again this is a hack and we don't need to do this with newer protocols. */ PyObject *reduce_value = NULL; int status; if (PyBytes_GET_SIZE(obj) == 0) { reduce_value = Py_BuildValue("(O())", (PyObject*)&PyBytes_Type); } else { PickleState *st = _Pickle_GetGlobalState(); PyObject *unicode_str = PyUnicode_DecodeLatin1(PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj), "strict"); _Py_IDENTIFIER(latin1); if (unicode_str == NULL) return -1; reduce_value = Py_BuildValue("(O(OO))", st->codecs_encode, unicode_str, _PyUnicode_FromId(&PyId_latin1)); Py_DECREF(unicode_str); } if (reduce_value == NULL) return -1; /* save_reduce() will memoize the object automatically. */ status = save_reduce(self, reduce_value, obj); Py_DECREF(reduce_value); return status; } else { Py_ssize_t size; char header[9]; Py_ssize_t len; size = PyBytes_GET_SIZE(obj); if (size < 0) return -1; if (size <= 0xff) { header[0] = SHORT_BINBYTES; header[1] = (unsigned char)size; len = 2; } else if ((size_t)size <= 0xffffffffUL) { header[0] = BINBYTES; header[1] = (unsigned char)(size & 0xff); header[2] = (unsigned char)((size >> 8) & 0xff); header[3] = (unsigned char)((size >> 16) & 0xff); header[4] = (unsigned char)((size >> 24) & 0xff); len = 5; } else if (self->proto >= 4) { header[0] = BINBYTES8; _write_size64(header + 1, size); len = 9; } else { PyErr_SetString(PyExc_OverflowError, "cannot serialize a bytes object larger than 4 GiB"); return -1; /* string too large */ } if (_Pickler_write_bytes(self, header, len, PyBytes_AS_STRING(obj), size, obj) < 0) { return -1; } if (memo_put(self, obj) < 0) return -1; return 0; } } /* A copy of PyUnicode_EncodeRawUnicodeEscape() that also translates backslash and newline characters to \uXXXX escapes. */ static PyObject * raw_unicode_escape(PyObject *obj) { char *p; Py_ssize_t i, size; void *data; unsigned int kind; _PyBytesWriter writer; if (PyUnicode_READY(obj)) return NULL; _PyBytesWriter_Init(&writer); size = PyUnicode_GET_LENGTH(obj); data = PyUnicode_DATA(obj); kind = PyUnicode_KIND(obj); p = _PyBytesWriter_Alloc(&writer, size); if (p == NULL) goto error; writer.overallocate = 1; for (i=0; i < size; i++) { Py_UCS4 ch = PyUnicode_READ(kind, data, i); /* Map 32-bit characters to '\Uxxxxxxxx' */ if (ch >= 0x10000) { /* -1: subtract 1 preallocated byte */ p = _PyBytesWriter_Prepare(&writer, p, 10-1); if (p == NULL) goto error; *p++ = '\\'; *p++ = 'U'; *p++ = Py_hexdigits[(ch >> 28) & 0xf]; *p++ = Py_hexdigits[(ch >> 24) & 0xf]; *p++ = Py_hexdigits[(ch >> 20) & 0xf]; *p++ = Py_hexdigits[(ch >> 16) & 0xf]; *p++ = Py_hexdigits[(ch >> 12) & 0xf]; *p++ = Py_hexdigits[(ch >> 8) & 0xf]; *p++ = Py_hexdigits[(ch >> 4) & 0xf]; *p++ = Py_hexdigits[ch & 15]; } /* Map 16-bit characters, '\\' and '\n' to '\uxxxx' */ else if (ch >= 256 || ch == '\\' || ch == '\n') { /* -1: subtract 1 preallocated byte */ p = _PyBytesWriter_Prepare(&writer, p, 6-1); if (p == NULL) goto error; *p++ = '\\'; *p++ = 'u'; *p++ = Py_hexdigits[(ch >> 12) & 0xf]; *p++ = Py_hexdigits[(ch >> 8) & 0xf]; *p++ = Py_hexdigits[(ch >> 4) & 0xf]; *p++ = Py_hexdigits[ch & 15]; } /* Copy everything else as-is */ else *p++ = (char) ch; } return _PyBytesWriter_Finish(&writer, p); error: _PyBytesWriter_Dealloc(&writer); return NULL; } static int write_unicode_binary(PicklerObject *self, PyObject *obj) { char header[9]; Py_ssize_t len; PyObject *encoded = NULL; Py_ssize_t size; const char *data; if (PyUnicode_READY(obj)) return -1; data = PyUnicode_AsUTF8AndSize(obj, &size); if (data == NULL) { /* Issue #8383: for strings with lone surrogates, fallback on the "surrogatepass" error handler. */ PyErr_Clear(); encoded = PyUnicode_AsEncodedString(obj, "utf-8", "surrogatepass"); if (encoded == NULL) return -1; data = PyBytes_AS_STRING(encoded); size = PyBytes_GET_SIZE(encoded); } assert(size >= 0); if (size <= 0xff && self->proto >= 4) { header[0] = SHORT_BINUNICODE; header[1] = (unsigned char)(size & 0xff); len = 2; } else if ((size_t)size <= 0xffffffffUL) { header[0] = BINUNICODE; header[1] = (unsigned char)(size & 0xff); header[2] = (unsigned char)((size >> 8) & 0xff); header[3] = (unsigned char)((size >> 16) & 0xff); header[4] = (unsigned char)((size >> 24) & 0xff); len = 5; } else if (self->proto >= 4) { header[0] = BINUNICODE8; _write_size64(header + 1, size); len = 9; } else { PyErr_SetString(PyExc_OverflowError, "cannot serialize a string larger than 4GiB"); Py_XDECREF(encoded); return -1; } if (_Pickler_write_bytes(self, header, len, data, size, encoded) < 0) { Py_XDECREF(encoded); return -1; } Py_XDECREF(encoded); return 0; } static int save_unicode(PicklerObject *self, PyObject *obj) { if (self->bin) { if (write_unicode_binary(self, obj) < 0) return -1; } else { PyObject *encoded; Py_ssize_t size; const char unicode_op = UNICODE; encoded = raw_unicode_escape(obj); if (encoded == NULL) return -1; if (_Pickler_Write(self, &unicode_op, 1) < 0) { Py_DECREF(encoded); return -1; } size = PyBytes_GET_SIZE(encoded); if (_Pickler_Write(self, PyBytes_AS_STRING(encoded), size) < 0) { Py_DECREF(encoded); return -1; } Py_DECREF(encoded); if (_Pickler_Write(self, "\n", 1) < 0) return -1; } if (memo_put(self, obj) < 0) return -1; return 0; } /* A helper for save_tuple. Push the len elements in tuple t on the stack. */ static int store_tuple_elements(PicklerObject *self, PyObject *t, Py_ssize_t len) { Py_ssize_t i; assert(PyTuple_Size(t) == len); for (i = 0; i < len; i++) { PyObject *element = PyTuple_GET_ITEM(t, i); if (element == NULL) return -1; if (save(self, element, 0) < 0) return -1; } return 0; } /* Tuples are ubiquitous in the pickle protocols, so many techniques are * used across protocols to minimize the space needed to pickle them. * Tuples are also the only builtin immutable type that can be recursive * (a tuple can be reached from itself), and that requires some subtle * magic so that it works in all cases. IOW, this is a long routine. */ static int save_tuple(PicklerObject *self, PyObject *obj) { Py_ssize_t len, i; const char mark_op = MARK; const char tuple_op = TUPLE; const char pop_op = POP; const char pop_mark_op = POP_MARK; const char len2opcode[] = {EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3}; if ((len = PyTuple_Size(obj)) < 0) return -1; if (len == 0) { char pdata[2]; if (self->proto) { pdata[0] = EMPTY_TUPLE; len = 1; } else { pdata[0] = MARK; pdata[1] = TUPLE; len = 2; } if (_Pickler_Write(self, pdata, len) < 0) return -1; return 0; } /* The tuple isn't in the memo now. If it shows up there after * saving the tuple elements, the tuple must be recursive, in * which case we'll pop everything we put on the stack, and fetch * its value from the memo. */ if (len <= 3 && self->proto >= 2) { /* Use TUPLE{1,2,3} opcodes. */ if (store_tuple_elements(self, obj, len) < 0) return -1; if (PyMemoTable_Get(self->memo, obj)) { /* pop the len elements */ for (i = 0; i < len; i++) if (_Pickler_Write(self, &pop_op, 1) < 0) return -1; /* fetch from memo */ if (memo_get(self, obj) < 0) return -1; return 0; } else { /* Not recursive. */ if (_Pickler_Write(self, len2opcode + len, 1) < 0) return -1; } goto memoize; } /* proto < 2 and len > 0, or proto >= 2 and len > 3. * Generate MARK e1 e2 ... TUPLE */ if (_Pickler_Write(self, &mark_op, 1) < 0) return -1; if (store_tuple_elements(self, obj, len) < 0) return -1; if (PyMemoTable_Get(self->memo, obj)) { /* pop the stack stuff we pushed */ if (self->bin) { if (_Pickler_Write(self, &pop_mark_op, 1) < 0) return -1; } else { /* Note that we pop one more than len, to remove * the MARK too. */ for (i = 0; i <= len; i++) if (_Pickler_Write(self, &pop_op, 1) < 0) return -1; } /* fetch from memo */ if (memo_get(self, obj) < 0) return -1; return 0; } else { /* Not recursive. */ if (_Pickler_Write(self, &tuple_op, 1) < 0) return -1; } memoize: if (memo_put(self, obj) < 0) return -1; return 0; } /* iter is an iterator giving items, and we batch up chunks of * MARK item item ... item APPENDS * opcode sequences. Calling code should have arranged to first create an * empty list, or list-like object, for the APPENDS to operate on. * Returns 0 on success, <0 on error. */ static int batch_list(PicklerObject *self, PyObject *iter) { PyObject *obj = NULL; PyObject *firstitem = NULL; int i, n; const char mark_op = MARK; const char append_op = APPEND; const char appends_op = APPENDS; assert(iter != NULL); /* XXX: I think this function could be made faster by avoiding the iterator interface and fetching objects directly from list using PyList_GET_ITEM. */ if (self->proto == 0) { /* APPENDS isn't available; do one at a time. */ for (;;) { obj = PyIter_Next(iter); if (obj == NULL) { if (PyErr_Occurred()) return -1; break; } i = save(self, obj, 0); Py_DECREF(obj); if (i < 0) return -1; if (_Pickler_Write(self, &append_op, 1) < 0) return -1; } return 0; } /* proto > 0: write in batches of BATCHSIZE. */ do { /* Get first item */ firstitem = PyIter_Next(iter); if (firstitem == NULL) { if (PyErr_Occurred()) goto error; /* nothing more to add */ break; } /* Try to get a second item */ obj = PyIter_Next(iter); if (obj == NULL) { if (PyErr_Occurred()) goto error; /* Only one item to write */ if (save(self, firstitem, 0) < 0) goto error; if (_Pickler_Write(self, &append_op, 1) < 0) goto error; Py_CLEAR(firstitem); break; } /* More than one item to write */ /* Pump out MARK, items, APPENDS. */ if (_Pickler_Write(self, &mark_op, 1) < 0) goto error; if (save(self, firstitem, 0) < 0) goto error; Py_CLEAR(firstitem); n = 1; /* Fetch and save up to BATCHSIZE items */ while (obj) { if (save(self, obj, 0) < 0) goto error; Py_CLEAR(obj); n += 1; if (n == BATCHSIZE) break; obj = PyIter_Next(iter); if (obj == NULL) { if (PyErr_Occurred()) goto error; break; } } if (_Pickler_Write(self, &appends_op, 1) < 0) goto error; } while (n == BATCHSIZE); return 0; error: Py_XDECREF(firstitem); Py_XDECREF(obj); return -1; } /* This is a variant of batch_list() above, specialized for lists (with no * support for list subclasses). Like batch_list(), we batch up chunks of * MARK item item ... item APPENDS * opcode sequences. Calling code should have arranged to first create an * empty list, or list-like object, for the APPENDS to operate on. * Returns 0 on success, -1 on error. * * This version is considerably faster than batch_list(), if less general. * * Note that this only works for protocols > 0. */ static int batch_list_exact(PicklerObject *self, PyObject *obj) { PyObject *item = NULL; Py_ssize_t this_batch, total; const char append_op = APPEND; const char appends_op = APPENDS; const char mark_op = MARK; assert(obj != NULL); assert(self->proto > 0); assert(PyList_CheckExact(obj)); if (PyList_GET_SIZE(obj) == 1) { item = PyList_GET_ITEM(obj, 0); if (save(self, item, 0) < 0) return -1; if (_Pickler_Write(self, &append_op, 1) < 0) return -1; return 0; } /* Write in batches of BATCHSIZE. */ total = 0; do { this_batch = 0; if (_Pickler_Write(self, &mark_op, 1) < 0) return -1; while (total < PyList_GET_SIZE(obj)) { item = PyList_GET_ITEM(obj, total); if (save(self, item, 0) < 0) return -1; total++; if (++this_batch == BATCHSIZE) break; } if (_Pickler_Write(self, &appends_op, 1) < 0) return -1; } while (total < PyList_GET_SIZE(obj)); return 0; } static int save_list(PicklerObject *self, PyObject *obj) { char header[3]; Py_ssize_t len; int status = 0; if (self->fast && !fast_save_enter(self, obj)) goto error; /* Create an empty list. */ if (self->bin) { header[0] = EMPTY_LIST; len = 1; } else { header[0] = MARK; header[1] = LIST; len = 2; } if (_Pickler_Write(self, header, len) < 0) goto error; /* Get list length, and bow out early if empty. */ if ((len = PyList_Size(obj)) < 0) goto error; if (memo_put(self, obj) < 0) goto error; if (len != 0) { /* Materialize the list elements. */ if (PyList_CheckExact(obj) && self->proto > 0) { if (Py_EnterRecursiveCall(" while pickling an object")) goto error; status = batch_list_exact(self, obj); Py_LeaveRecursiveCall(); } else { PyObject *iter = PyObject_GetIter(obj); if (iter == NULL) goto error; if (Py_EnterRecursiveCall(" while pickling an object")) { Py_DECREF(iter); goto error; } status = batch_list(self, iter); Py_LeaveRecursiveCall(); Py_DECREF(iter); } } if (0) { error: status = -1; } if (self->fast && !fast_save_leave(self, obj)) status = -1; return status; } /* iter is an iterator giving (key, value) pairs, and we batch up chunks of * MARK key value ... key value SETITEMS * opcode sequences. Calling code should have arranged to first create an * empty dict, or dict-like object, for the SETITEMS to operate on. * Returns 0 on success, <0 on error. * * This is very much like batch_list(). The difference between saving * elements directly, and picking apart two-tuples, is so long-winded at * the C level, though, that attempts to combine these routines were too * ugly to bear. */ static int batch_dict(PicklerObject *self, PyObject *iter) { PyObject *obj = NULL; PyObject *firstitem = NULL; int i, n; const char mark_op = MARK; const char setitem_op = SETITEM; const char setitems_op = SETITEMS; assert(iter != NULL); if (self->proto == 0) { /* SETITEMS isn't available; do one at a time. */ for (;;) { obj = PyIter_Next(iter); if (obj == NULL) { if (PyErr_Occurred()) return -1; break; } if (!PyTuple_Check(obj) || PyTuple_Size(obj) != 2) { PyErr_SetString(PyExc_TypeError, "dict items " "iterator must return 2-tuples"); return -1; } i = save(self, PyTuple_GET_ITEM(obj, 0), 0); if (i >= 0) i = save(self, PyTuple_GET_ITEM(obj, 1), 0); Py_DECREF(obj); if (i < 0) return -1; if (_Pickler_Write(self, &setitem_op, 1) < 0) return -1; } return 0; } /* proto > 0: write in batches of BATCHSIZE. */ do { /* Get first item */ firstitem = PyIter_Next(iter); if (firstitem == NULL) { if (PyErr_Occurred()) goto error; /* nothing more to add */ break; } if (!PyTuple_Check(firstitem) || PyTuple_Size(firstitem) != 2) { PyErr_SetString(PyExc_TypeError, "dict items " "iterator must return 2-tuples"); goto error; } /* Try to get a second item */ obj = PyIter_Next(iter); if (obj == NULL) { if (PyErr_Occurred()) goto error; /* Only one item to write */ if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0) goto error; if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0) goto error; if (_Pickler_Write(self, &setitem_op, 1) < 0) goto error; Py_CLEAR(firstitem); break; } /* More than one item to write */ /* Pump out MARK, items, SETITEMS. */ if (_Pickler_Write(self, &mark_op, 1) < 0) goto error; if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0) goto error; if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0) goto error; Py_CLEAR(firstitem); n = 1; /* Fetch and save up to BATCHSIZE items */ while (obj) { if (!PyTuple_Check(obj) || PyTuple_Size(obj) != 2) { PyErr_SetString(PyExc_TypeError, "dict items " "iterator must return 2-tuples"); goto error; } if (save(self, PyTuple_GET_ITEM(obj, 0), 0) < 0 || save(self, PyTuple_GET_ITEM(obj, 1), 0) < 0) goto error; Py_CLEAR(obj); n += 1; if (n == BATCHSIZE) break; obj = PyIter_Next(iter); if (obj == NULL) { if (PyErr_Occurred()) goto error; break; } } if (_Pickler_Write(self, &setitems_op, 1) < 0) goto error; } while (n == BATCHSIZE); return 0; error: Py_XDECREF(firstitem); Py_XDECREF(obj); return -1; } /* This is a variant of batch_dict() above that specializes for dicts, with no * support for dict subclasses. Like batch_dict(), we batch up chunks of * MARK key value ... key value SETITEMS * opcode sequences. Calling code should have arranged to first create an * empty dict, or dict-like object, for the SETITEMS to operate on. * Returns 0 on success, -1 on error. * * Note that this currently doesn't work for protocol 0. */ static int batch_dict_exact(PicklerObject *self, PyObject *obj) { PyObject *key = NULL, *value = NULL; int i; Py_ssize_t dict_size, ppos = 0; const char mark_op = MARK; const char setitem_op = SETITEM; const char setitems_op = SETITEMS; assert(obj != NULL && PyDict_CheckExact(obj)); assert(self->proto > 0); dict_size = PyDict_GET_SIZE(obj); /* Special-case len(d) == 1 to save space. */ if (dict_size == 1) { PyDict_Next(obj, &ppos, &key, &value); if (save(self, key, 0) < 0) return -1; if (save(self, value, 0) < 0) return -1; if (_Pickler_Write(self, &setitem_op, 1) < 0) return -1; return 0; } /* Write in batches of BATCHSIZE. */ do { i = 0; if (_Pickler_Write(self, &mark_op, 1) < 0) return -1; while (PyDict_Next(obj, &ppos, &key, &value)) { if (save(self, key, 0) < 0) return -1; if (save(self, value, 0) < 0) return -1; if (++i == BATCHSIZE) break; } if (_Pickler_Write(self, &setitems_op, 1) < 0) return -1; if (PyDict_GET_SIZE(obj) != dict_size) { PyErr_Format( PyExc_RuntimeError, "dictionary changed size during iteration"); return -1; } } while (i == BATCHSIZE); return 0; } static int save_dict(PicklerObject *self, PyObject *obj) { PyObject *items, *iter; char header[3]; Py_ssize_t len; int status = 0; assert(PyDict_Check(obj)); if (self->fast && !fast_save_enter(self, obj)) goto error; /* Create an empty dict. */ if (self->bin) { header[0] = EMPTY_DICT; len = 1; } else { header[0] = MARK; header[1] = DICT; len = 2; } if (_Pickler_Write(self, header, len) < 0) goto error; if (memo_put(self, obj) < 0) goto error; if (PyDict_GET_SIZE(obj)) { /* Save the dict items. */ if (PyDict_CheckExact(obj) && self->proto > 0) { /* We can take certain shortcuts if we know this is a dict and not a dict subclass. */ if (Py_EnterRecursiveCall(" while pickling an object")) goto error; status = batch_dict_exact(self, obj); Py_LeaveRecursiveCall(); } else { _Py_IDENTIFIER(items); items = _PyObject_CallMethodId(obj, &PyId_items, NULL); if (items == NULL) goto error; iter = PyObject_GetIter(items); Py_DECREF(items); if (iter == NULL) goto error; if (Py_EnterRecursiveCall(" while pickling an object")) { Py_DECREF(iter); goto error; } status = batch_dict(self, iter); Py_LeaveRecursiveCall(); Py_DECREF(iter); } } if (0) { error: status = -1; } if (self->fast && !fast_save_leave(self, obj)) status = -1; return status; } static int save_set(PicklerObject *self, PyObject *obj) { PyObject *item; int i; Py_ssize_t set_size, ppos = 0; Py_hash_t hash; const char empty_set_op = EMPTY_SET; const char mark_op = MARK; const char additems_op = ADDITEMS; if (self->proto < 4) { PyObject *items; PyObject *reduce_value; int status; items = PySequence_List(obj); if (items == NULL) { return -1; } reduce_value = Py_BuildValue("(O(O))", (PyObject*)&PySet_Type, items); Py_DECREF(items); if (reduce_value == NULL) { return -1; } /* save_reduce() will memoize the object automatically. */ status = save_reduce(self, reduce_value, obj); Py_DECREF(reduce_value); return status; } if (_Pickler_Write(self, &empty_set_op, 1) < 0) return -1; if (memo_put(self, obj) < 0) return -1; set_size = PySet_GET_SIZE(obj); if (set_size == 0) return 0; /* nothing to do */ /* Write in batches of BATCHSIZE. */ do { i = 0; if (_Pickler_Write(self, &mark_op, 1) < 0) return -1; while (_PySet_NextEntry(obj, &ppos, &item, &hash)) { if (save(self, item, 0) < 0) return -1; if (++i == BATCHSIZE) break; } if (_Pickler_Write(self, &additems_op, 1) < 0) return -1; if (PySet_GET_SIZE(obj) != set_size) { PyErr_Format( PyExc_RuntimeError, "set changed size during iteration"); return -1; } } while (i == BATCHSIZE); return 0; } static int save_frozenset(PicklerObject *self, PyObject *obj) { PyObject *iter; const char mark_op = MARK; const char frozenset_op = FROZENSET; if (self->fast && !fast_save_enter(self, obj)) return -1; if (self->proto < 4) { PyObject *items; PyObject *reduce_value; int status; items = PySequence_List(obj); if (items == NULL) { return -1; } reduce_value = Py_BuildValue("(O(O))", (PyObject*)&PyFrozenSet_Type, items); Py_DECREF(items); if (reduce_value == NULL) { return -1; } /* save_reduce() will memoize the object automatically. */ status = save_reduce(self, reduce_value, obj); Py_DECREF(reduce_value); return status; } if (_Pickler_Write(self, &mark_op, 1) < 0) return -1; iter = PyObject_GetIter(obj); if (iter == NULL) { return -1; } for (;;) { PyObject *item; item = PyIter_Next(iter); if (item == NULL) { if (PyErr_Occurred()) { Py_DECREF(iter); return -1; } break; } if (save(self, item, 0) < 0) { Py_DECREF(item); Py_DECREF(iter); return -1; } Py_DECREF(item); } Py_DECREF(iter); /* If the object is already in the memo, this means it is recursive. In this case, throw away everything we put on the stack, and fetch the object back from the memo. */ if (PyMemoTable_Get(self->memo, obj)) { const char pop_mark_op = POP_MARK; if (_Pickler_Write(self, &pop_mark_op, 1) < 0) return -1; if (memo_get(self, obj) < 0) return -1; return 0; } if (_Pickler_Write(self, &frozenset_op, 1) < 0) return -1; if (memo_put(self, obj) < 0) return -1; return 0; } static int fix_imports(PyObject **module_name, PyObject **global_name) { PyObject *key; PyObject *item; PickleState *st = _Pickle_GetGlobalState(); key = PyTuple_Pack(2, *module_name, *global_name); if (key == NULL) return -1; item = PyDict_GetItemWithError(st->name_mapping_3to2, key); Py_DECREF(key); if (item) { PyObject *fixed_module_name; PyObject *fixed_global_name; if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.REVERSE_NAME_MAPPING values " "should be 2-tuples, not %.200s", Py_TYPE(item)->tp_name); return -1; } fixed_module_name = PyTuple_GET_ITEM(item, 0); fixed_global_name = PyTuple_GET_ITEM(item, 1); if (!PyUnicode_Check(fixed_module_name) || !PyUnicode_Check(fixed_global_name)) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.REVERSE_NAME_MAPPING values " "should be pairs of str, not (%.200s, %.200s)", Py_TYPE(fixed_module_name)->tp_name, Py_TYPE(fixed_global_name)->tp_name); return -1; } Py_CLEAR(*module_name); Py_CLEAR(*global_name); Py_INCREF(fixed_module_name); Py_INCREF(fixed_global_name); *module_name = fixed_module_name; *global_name = fixed_global_name; return 0; } else if (PyErr_Occurred()) { return -1; } item = PyDict_GetItemWithError(st->import_mapping_3to2, *module_name); if (item) { if (!PyUnicode_Check(item)) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.REVERSE_IMPORT_MAPPING values " "should be strings, not %.200s", Py_TYPE(item)->tp_name); return -1; } Py_INCREF(item); Py_XSETREF(*module_name, item); } else if (PyErr_Occurred()) { return -1; } return 0; } static int save_global(PicklerObject *self, PyObject *obj, PyObject *name) { PyObject *global_name = NULL; PyObject *module_name = NULL; PyObject *module = NULL; PyObject *parent = NULL; PyObject *dotted_path = NULL; PyObject *lastname = NULL; PyObject *cls; PickleState *st = _Pickle_GetGlobalState(); int status = 0; _Py_IDENTIFIER(__name__); _Py_IDENTIFIER(__qualname__); const char global_op = GLOBAL; if (name) { Py_INCREF(name); global_name = name; } else { if (_PyObject_LookupAttrId(obj, &PyId___qualname__, &global_name) < 0) goto error; if (global_name == NULL) { global_name = _PyObject_GetAttrId(obj, &PyId___name__); if (global_name == NULL) goto error; } } dotted_path = get_dotted_path(module, global_name); if (dotted_path == NULL) goto error; module_name = whichmodule(obj, dotted_path); if (module_name == NULL) goto error; /* XXX: Change to use the import C API directly with level=0 to disallow relative imports. XXX: PyImport_ImportModuleLevel could be used. However, this bypasses builtins.__import__. Therefore, _pickle, unlike pickle.py, will ignore custom import functions (IMHO, this would be a nice security feature). The import C API would need to be extended to support the extra parameters of __import__ to fix that. */ module = PyImport_Import(module_name); if (module == NULL) { PyErr_Format(st->PicklingError, "Can't pickle %R: import of module %R failed", obj, module_name); goto error; } lastname = PyList_GET_ITEM(dotted_path, PyList_GET_SIZE(dotted_path)-1); Py_INCREF(lastname); cls = get_deep_attribute(module, dotted_path, &parent); Py_CLEAR(dotted_path); if (cls == NULL) { PyErr_Format(st->PicklingError, "Can't pickle %R: attribute lookup %S on %S failed", obj, global_name, module_name); goto error; } if (cls != obj) { Py_DECREF(cls); PyErr_Format(st->PicklingError, "Can't pickle %R: it's not the same object as %S.%S", obj, module_name, global_name); goto error; } Py_DECREF(cls); if (self->proto >= 2) { /* See whether this is in the extension registry, and if * so generate an EXT opcode. */ PyObject *extension_key; PyObject *code_obj; /* extension code as Python object */ long code; /* extension code as C value */ char pdata[5]; Py_ssize_t n; extension_key = PyTuple_Pack(2, module_name, global_name); if (extension_key == NULL) { goto error; } code_obj = PyDict_GetItemWithError(st->extension_registry, extension_key); Py_DECREF(extension_key); /* The object is not registered in the extension registry. This is the most likely code path. */ if (code_obj == NULL) { if (PyErr_Occurred()) { goto error; } goto gen_global; } /* XXX: pickle.py doesn't check neither the type, nor the range of the value returned by the extension_registry. It should for consistency. */ /* Verify code_obj has the right type and value. */ if (!PyLong_Check(code_obj)) { PyErr_Format(st->PicklingError, "Can't pickle %R: extension code %R isn't an integer", obj, code_obj); goto error; } code = PyLong_AS_LONG(code_obj); if (code <= 0 || code > 0x7fffffffL) { if (!PyErr_Occurred()) PyErr_Format(st->PicklingError, "Can't pickle %R: extension " "code %ld is out of range", obj, code); goto error; } /* Generate an EXT opcode. */ if (code <= 0xff) { pdata[0] = EXT1; pdata[1] = (unsigned char)code; n = 2; } else if (code <= 0xffff) { pdata[0] = EXT2; pdata[1] = (unsigned char)(code & 0xff); pdata[2] = (unsigned char)((code >> 8) & 0xff); n = 3; } else { pdata[0] = EXT4; pdata[1] = (unsigned char)(code & 0xff); pdata[2] = (unsigned char)((code >> 8) & 0xff); pdata[3] = (unsigned char)((code >> 16) & 0xff); pdata[4] = (unsigned char)((code >> 24) & 0xff); n = 5; } if (_Pickler_Write(self, pdata, n) < 0) goto error; } else { gen_global: if (parent == module) { Py_INCREF(lastname); Py_DECREF(global_name); global_name = lastname; } if (self->proto >= 4) { const char stack_global_op = STACK_GLOBAL; if (save(self, module_name, 0) < 0) goto error; if (save(self, global_name, 0) < 0) goto error; if (_Pickler_Write(self, &stack_global_op, 1) < 0) goto error; } else if (parent != module) { PickleState *st = _Pickle_GetGlobalState(); PyObject *reduce_value = Py_BuildValue("(O(OO))", st->getattr, parent, lastname); if (reduce_value == NULL) goto error; status = save_reduce(self, reduce_value, NULL); Py_DECREF(reduce_value); if (status < 0) goto error; } else { /* Generate a normal global opcode if we are using a pickle protocol < 4, or if the object is not registered in the extension registry. */ PyObject *encoded; PyObject *(*unicode_encoder)(PyObject *); if (_Pickler_Write(self, &global_op, 1) < 0) goto error; /* For protocol < 3 and if the user didn't request against doing so, we convert module names to the old 2.x module names. */ if (self->proto < 3 && self->fix_imports) { if (fix_imports(&module_name, &global_name) < 0) { goto error; } } /* Since Python 3.0 now supports non-ASCII identifiers, we encode both the module name and the global name using UTF-8. We do so only when we are using the pickle protocol newer than version 3. This is to ensure compatibility with older Unpickler running on Python 2.x. */ if (self->proto == 3) { unicode_encoder = PyUnicode_AsUTF8String; } else { unicode_encoder = PyUnicode_AsASCIIString; } encoded = unicode_encoder(module_name); if (encoded == NULL) { if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) PyErr_Format(st->PicklingError, "can't pickle module identifier '%S' using " "pickle protocol %i", module_name, self->proto); goto error; } if (_Pickler_Write(self, PyBytes_AS_STRING(encoded), PyBytes_GET_SIZE(encoded)) < 0) { Py_DECREF(encoded); goto error; } Py_DECREF(encoded); if(_Pickler_Write(self, "\n", 1) < 0) goto error; /* Save the name of the module. */ encoded = unicode_encoder(global_name); if (encoded == NULL) { if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) PyErr_Format(st->PicklingError, "can't pickle global identifier '%S' using " "pickle protocol %i", global_name, self->proto); goto error; } if (_Pickler_Write(self, PyBytes_AS_STRING(encoded), PyBytes_GET_SIZE(encoded)) < 0) { Py_DECREF(encoded); goto error; } Py_DECREF(encoded); if (_Pickler_Write(self, "\n", 1) < 0) goto error; } /* Memoize the object. */ if (memo_put(self, obj) < 0) goto error; } if (0) { error: status = -1; } Py_XDECREF(module_name); Py_XDECREF(global_name); Py_XDECREF(module); Py_XDECREF(parent); Py_XDECREF(dotted_path); Py_XDECREF(lastname); return status; } static int save_singleton_type(PicklerObject *self, PyObject *obj, PyObject *singleton) { PyObject *reduce_value; int status; reduce_value = Py_BuildValue("O(O)", &PyType_Type, singleton); if (reduce_value == NULL) { return -1; } status = save_reduce(self, reduce_value, obj); Py_DECREF(reduce_value); return status; } static int save_type(PicklerObject *self, PyObject *obj) { if (obj == (PyObject *)&_PyNone_Type) { return save_singleton_type(self, obj, Py_None); } else if (obj == (PyObject *)&PyEllipsis_Type) { return save_singleton_type(self, obj, Py_Ellipsis); } else if (obj == (PyObject *)&_PyNotImplemented_Type) { return save_singleton_type(self, obj, Py_NotImplemented); } return save_global(self, obj, NULL); } static int save_pers(PicklerObject *self, PyObject *obj) { PyObject *pid = NULL; int status = 0; const char persid_op = PERSID; const char binpersid_op = BINPERSID; pid = call_method(self->pers_func, self->pers_func_self, obj); if (pid == NULL) return -1; if (pid != Py_None) { if (self->bin) { if (save(self, pid, 1) < 0 || _Pickler_Write(self, &binpersid_op, 1) < 0) goto error; } else { PyObject *pid_str; pid_str = PyObject_Str(pid); if (pid_str == NULL) goto error; /* XXX: Should it check whether the pid contains embedded newlines? */ if (!PyUnicode_IS_ASCII(pid_str)) { PyErr_SetString(_Pickle_GetGlobalState()->PicklingError, "persistent IDs in protocol 0 must be " "ASCII strings"); Py_DECREF(pid_str); goto error; } if (_Pickler_Write(self, &persid_op, 1) < 0 || _Pickler_Write(self, PyUnicode_DATA(pid_str), PyUnicode_GET_LENGTH(pid_str)) < 0 || _Pickler_Write(self, "\n", 1) < 0) { Py_DECREF(pid_str); goto error; } Py_DECREF(pid_str); } status = 1; } if (0) { error: status = -1; } Py_XDECREF(pid); return status; } static PyObject * get_class(PyObject *obj) { PyObject *cls; _Py_IDENTIFIER(__class__); if (_PyObject_LookupAttrId(obj, &PyId___class__, &cls) == 0) { cls = (PyObject *) Py_TYPE(obj); Py_INCREF(cls); } return cls; } /* We're saving obj, and args is the 2-thru-5 tuple returned by the * appropriate __reduce__ method for obj. */ static int save_reduce(PicklerObject *self, PyObject *args, PyObject *obj) { PyObject *callable; PyObject *argtup; PyObject *state = NULL; PyObject *listitems = Py_None; PyObject *dictitems = Py_None; PickleState *st = _Pickle_GetGlobalState(); Py_ssize_t size; int use_newobj = 0, use_newobj_ex = 0; const char reduce_op = REDUCE; const char build_op = BUILD; const char newobj_op = NEWOBJ; const char newobj_ex_op = NEWOBJ_EX; size = PyTuple_Size(args); if (size < 2 || size > 5) { PyErr_SetString(st->PicklingError, "tuple returned by " "__reduce__ must contain 2 through 5 elements"); return -1; } if (!PyArg_UnpackTuple(args, "save_reduce", 2, 5, &callable, &argtup, &state, &listitems, &dictitems)) return -1; if (!PyCallable_Check(callable)) { PyErr_SetString(st->PicklingError, "first item of the tuple " "returned by __reduce__ must be callable"); return -1; } if (!PyTuple_Check(argtup)) { PyErr_SetString(st->PicklingError, "second item of the tuple " "returned by __reduce__ must be a tuple"); return -1; } if (state == Py_None) state = NULL; if (listitems == Py_None) listitems = NULL; else if (!PyIter_Check(listitems)) { PyErr_Format(st->PicklingError, "fourth element of the tuple " "returned by __reduce__ must be an iterator, not %s", Py_TYPE(listitems)->tp_name); return -1; } if (dictitems == Py_None) dictitems = NULL; else if (!PyIter_Check(dictitems)) { PyErr_Format(st->PicklingError, "fifth element of the tuple " "returned by __reduce__ must be an iterator, not %s", Py_TYPE(dictitems)->tp_name); return -1; } if (self->proto >= 2) { PyObject *name; _Py_IDENTIFIER(__name__); if (_PyObject_LookupAttrId(callable, &PyId___name__, &name) < 0) { return -1; } if (name != NULL && PyUnicode_Check(name)) { _Py_IDENTIFIER(__newobj_ex__); use_newobj_ex = _PyUnicode_EqualToASCIIId( name, &PyId___newobj_ex__); if (!use_newobj_ex) { _Py_IDENTIFIER(__newobj__); use_newobj = _PyUnicode_EqualToASCIIId(name, &PyId___newobj__); } } Py_XDECREF(name); } if (use_newobj_ex) { PyObject *cls; PyObject *args; PyObject *kwargs; if (PyTuple_GET_SIZE(argtup) != 3) { PyErr_Format(st->PicklingError, "length of the NEWOBJ_EX argument tuple must be " "exactly 3, not %zd", PyTuple_GET_SIZE(argtup)); return -1; } cls = PyTuple_GET_ITEM(argtup, 0); if (!PyType_Check(cls)) { PyErr_Format(st->PicklingError, "first item from NEWOBJ_EX argument tuple must " "be a class, not %.200s", Py_TYPE(cls)->tp_name); return -1; } args = PyTuple_GET_ITEM(argtup, 1); if (!PyTuple_Check(args)) { PyErr_Format(st->PicklingError, "second item from NEWOBJ_EX argument tuple must " "be a tuple, not %.200s", Py_TYPE(args)->tp_name); return -1; } kwargs = PyTuple_GET_ITEM(argtup, 2); if (!PyDict_Check(kwargs)) { PyErr_Format(st->PicklingError, "third item from NEWOBJ_EX argument tuple must " "be a dict, not %.200s", Py_TYPE(kwargs)->tp_name); return -1; } if (self->proto >= 4) { if (save(self, cls, 0) < 0 || save(self, args, 0) < 0 || save(self, kwargs, 0) < 0 || _Pickler_Write(self, &newobj_ex_op, 1) < 0) { return -1; } } else { PyObject *newargs; PyObject *cls_new; Py_ssize_t i; _Py_IDENTIFIER(__new__); newargs = PyTuple_New(PyTuple_GET_SIZE(args) + 2); if (newargs == NULL) return -1; cls_new = _PyObject_GetAttrId(cls, &PyId___new__); if (cls_new == NULL) { Py_DECREF(newargs); return -1; } PyTuple_SET_ITEM(newargs, 0, cls_new); Py_INCREF(cls); PyTuple_SET_ITEM(newargs, 1, cls); for (i = 0; i < PyTuple_GET_SIZE(args); i++) { PyObject *item = PyTuple_GET_ITEM(args, i); Py_INCREF(item); PyTuple_SET_ITEM(newargs, i + 2, item); } callable = PyObject_Call(st->partial, newargs, kwargs); Py_DECREF(newargs); if (callable == NULL) return -1; newargs = PyTuple_New(0); if (newargs == NULL) { Py_DECREF(callable); return -1; } if (save(self, callable, 0) < 0 || save(self, newargs, 0) < 0 || _Pickler_Write(self, &reduce_op, 1) < 0) { Py_DECREF(newargs); Py_DECREF(callable); return -1; } Py_DECREF(newargs); Py_DECREF(callable); } } else if (use_newobj) { PyObject *cls; PyObject *newargtup; PyObject *obj_class; int p; /* Sanity checks. */ if (PyTuple_GET_SIZE(argtup) < 1) { PyErr_SetString(st->PicklingError, "__newobj__ arglist is empty"); return -1; } cls = PyTuple_GET_ITEM(argtup, 0); if (!PyType_Check(cls)) { PyErr_SetString(st->PicklingError, "args[0] from " "__newobj__ args is not a type"); return -1; } if (obj != NULL) { obj_class = get_class(obj); if (obj_class == NULL) { return -1; } p = obj_class != cls; Py_DECREF(obj_class); if (p) { PyErr_SetString(st->PicklingError, "args[0] from " "__newobj__ args has the wrong class"); return -1; } } /* XXX: These calls save() are prone to infinite recursion. Imagine what happen if the value returned by the __reduce__() method of some extension type contains another object of the same type. Ouch! Here is a quick example, that I ran into, to illustrate what I mean: >>> import pickle, copyreg >>> copyreg.dispatch_table.pop(complex) >>> pickle.dumps(1+2j) Traceback (most recent call last): ... RecursionError: maximum recursion depth exceeded Removing the complex class from copyreg.dispatch_table made the __reduce_ex__() method emit another complex object: >>> (1+1j).__reduce_ex__(2) (<function __newobj__ at 0xb7b71c3c>, (<class 'complex'>, (1+1j)), None, None, None) Thus when save() was called on newargstup (the 2nd item) recursion ensued. Of course, the bug was in the complex class which had a broken __getnewargs__() that emitted another complex object. But, the point, here, is it is quite easy to end up with a broken reduce function. */ /* Save the class and its __new__ arguments. */ if (save(self, cls, 0) < 0) return -1; newargtup = PyTuple_GetSlice(argtup, 1, PyTuple_GET_SIZE(argtup)); if (newargtup == NULL) return -1; p = save(self, newargtup, 0); Py_DECREF(newargtup); if (p < 0) return -1; /* Add NEWOBJ opcode. */ if (_Pickler_Write(self, &newobj_op, 1) < 0) return -1; } else { /* Not using NEWOBJ. */ if (save(self, callable, 0) < 0 || save(self, argtup, 0) < 0 || _Pickler_Write(self, &reduce_op, 1) < 0) return -1; } /* obj can be NULL when save_reduce() is used directly. A NULL obj means the caller do not want to memoize the object. Not particularly useful, but that is to mimic the behavior save_reduce() in pickle.py when obj is None. */ if (obj != NULL) { /* If the object is already in the memo, this means it is recursive. In this case, throw away everything we put on the stack, and fetch the object back from the memo. */ if (PyMemoTable_Get(self->memo, obj)) { const char pop_op = POP; if (_Pickler_Write(self, &pop_op, 1) < 0) return -1; if (memo_get(self, obj) < 0) return -1; return 0; } else if (memo_put(self, obj) < 0) return -1; } if (listitems && batch_list(self, listitems) < 0) return -1; if (dictitems && batch_dict(self, dictitems) < 0) return -1; if (state) { if (save(self, state, 0) < 0 || _Pickler_Write(self, &build_op, 1) < 0) return -1; } return 0; } static int save(PicklerObject *self, PyObject *obj, int pers_save) { PyTypeObject *type; PyObject *reduce_func = NULL; PyObject *reduce_value = NULL; int status = 0; if (_Pickler_OpcodeBoundary(self) < 0) return -1; /* The extra pers_save argument is necessary to avoid calling save_pers() on its returned object. */ if (!pers_save && self->pers_func) { /* save_pers() returns: -1 to signal an error; 0 if it did nothing successfully; 1 if a persistent id was saved. */ if ((status = save_pers(self, obj)) != 0) return status; } type = Py_TYPE(obj); /* The old cPickle had an optimization that used switch-case statement dispatching on the first letter of the type name. This has was removed since benchmarks shown that this optimization was actually slowing things down. */ /* Atom types; these aren't memoized, so don't check the memo. */ if (obj == Py_None) { return save_none(self, obj); } else if (obj == Py_False || obj == Py_True) { return save_bool(self, obj); } else if (type == &PyLong_Type) { return save_long(self, obj); } else if (type == &PyFloat_Type) { return save_float(self, obj); } /* Check the memo to see if it has the object. If so, generate a GET (or BINGET) opcode, instead of pickling the object once again. */ if (PyMemoTable_Get(self->memo, obj)) { return memo_get(self, obj); } if (type == &PyBytes_Type) { return save_bytes(self, obj); } else if (type == &PyUnicode_Type) { return save_unicode(self, obj); } /* We're only calling Py_EnterRecursiveCall here so that atomic types above are pickled faster. */ if (Py_EnterRecursiveCall(" while pickling an object")) { return -1; } if (type == &PyDict_Type) { status = save_dict(self, obj); goto done; } else if (type == &PySet_Type) { status = save_set(self, obj); goto done; } else if (type == &PyFrozenSet_Type) { status = save_frozenset(self, obj); goto done; } else if (type == &PyList_Type) { status = save_list(self, obj); goto done; } else if (type == &PyTuple_Type) { status = save_tuple(self, obj); goto done; } else if (type == &PyType_Type) { status = save_type(self, obj); goto done; } else if (type == &PyFunction_Type) { status = save_global(self, obj, NULL); goto done; } /* XXX: This part needs some unit tests. */ /* Get a reduction callable, and call it. This may come from * self.dispatch_table, copyreg.dispatch_table, the object's * __reduce_ex__ method, or the object's __reduce__ method. */ if (self->dispatch_table == NULL) { PickleState *st = _Pickle_GetGlobalState(); reduce_func = PyDict_GetItemWithError(st->dispatch_table, (PyObject *)type); if (reduce_func == NULL) { if (PyErr_Occurred()) { goto error; } } else { /* PyDict_GetItemWithError() returns a borrowed reference. Increase the reference count to be consistent with PyObject_GetItem and _PyObject_GetAttrId used below. */ Py_INCREF(reduce_func); } } else { reduce_func = PyObject_GetItem(self->dispatch_table, (PyObject *)type); if (reduce_func == NULL) { if (PyErr_ExceptionMatches(PyExc_KeyError)) PyErr_Clear(); else goto error; } } if (reduce_func != NULL) { Py_INCREF(obj); reduce_value = _Pickle_FastCall(reduce_func, obj); } else if (PyType_IsSubtype(type, &PyType_Type)) { status = save_global(self, obj, NULL); goto done; } else { _Py_IDENTIFIER(__reduce__); _Py_IDENTIFIER(__reduce_ex__); /* XXX: If the __reduce__ method is defined, __reduce_ex__ is automatically defined as __reduce__. While this is convenient, this make it impossible to know which method was actually called. Of course, this is not a big deal. But still, it would be nice to let the user know which method was called when something go wrong. Incidentally, this means if __reduce_ex__ is not defined, we don't actually have to check for a __reduce__ method. */ /* Check for a __reduce_ex__ method. */ if (_PyObject_LookupAttrId(obj, &PyId___reduce_ex__, &reduce_func) < 0) { goto error; } if (reduce_func != NULL) { PyObject *proto; proto = PyLong_FromLong(self->proto); if (proto != NULL) { reduce_value = _Pickle_FastCall(reduce_func, proto); } } else { PickleState *st = _Pickle_GetGlobalState(); /* Check for a __reduce__ method. */ reduce_func = _PyObject_GetAttrId(obj, &PyId___reduce__); if (reduce_func != NULL) { reduce_value = _PyObject_CallNoArg(reduce_func); } else { PyErr_Format(st->PicklingError, "can't pickle '%.200s' object: %R", type->tp_name, obj); goto error; } } } if (reduce_value == NULL) goto error; if (PyUnicode_Check(reduce_value)) { status = save_global(self, obj, reduce_value); goto done; } if (!PyTuple_Check(reduce_value)) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->PicklingError, "__reduce__ must return a string or tuple"); goto error; } status = save_reduce(self, reduce_value, obj); if (0) { error: status = -1; } done: Py_LeaveRecursiveCall(); Py_XDECREF(reduce_func); Py_XDECREF(reduce_value); return status; } static int dump(PicklerObject *self, PyObject *obj) { const char stop_op = STOP; if (self->proto >= 2) { char header[2]; header[0] = PROTO; assert(self->proto >= 0 && self->proto < 256); header[1] = (unsigned char)self->proto; if (_Pickler_Write(self, header, 2) < 0) return -1; if (self->proto >= 4) self->framing = 1; } if (save(self, obj, 0) < 0 || _Pickler_Write(self, &stop_op, 1) < 0 || _Pickler_CommitFrame(self) < 0) return -1; self->framing = 0; return 0; } /*[clinic input] _pickle.Pickler.clear_memo Clears the pickler's "memo". The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects are pickled by reference and not by value. This method is useful when re-using picklers. [clinic start generated code]*/ static PyObject * _pickle_Pickler_clear_memo_impl(PicklerObject *self) /*[clinic end generated code: output=8665c8658aaa094b input=01bdad52f3d93e56]*/ { if (self->memo) PyMemoTable_Clear(self->memo); Py_RETURN_NONE; } /*[clinic input] _pickle.Pickler.dump obj: object / Write a pickled representation of the given object to the open file. [clinic start generated code]*/ static PyObject * _pickle_Pickler_dump(PicklerObject *self, PyObject *obj) /*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/ { /* Check whether the Pickler was initialized correctly (issue3664). Developers often forget to call __init__() in their subclasses, which would trigger a segfault without this check. */ if (self->write == NULL) { PickleState *st = _Pickle_GetGlobalState(); PyErr_Format(st->PicklingError, "Pickler.__init__() was not called by %s.__init__()", Py_TYPE(self)->tp_name); return NULL; } if (_Pickler_ClearBuffer(self) < 0) return NULL; if (dump(self, obj) < 0) return NULL; if (_Pickler_FlushToFile(self) < 0) return NULL; Py_RETURN_NONE; } /*[clinic input] _pickle.Pickler.__sizeof__ -> Py_ssize_t Returns size in memory, in bytes. [clinic start generated code]*/ static Py_ssize_t _pickle_Pickler___sizeof___impl(PicklerObject *self) /*[clinic end generated code: output=106edb3123f332e1 input=8cbbec9bd5540d42]*/ { Py_ssize_t res, s; res = _PyObject_SIZE(Py_TYPE(self)); if (self->memo != NULL) { res += sizeof(PyMemoTable); res += self->memo->mt_allocated * sizeof(PyMemoEntry); } if (self->output_buffer != NULL) { s = _PySys_GetSizeOf(self->output_buffer); if (s == -1) return -1; res += s; } return res; } static struct PyMethodDef Pickler_methods[] = { _PICKLE_PICKLER_DUMP_METHODDEF _PICKLE_PICKLER_CLEAR_MEMO_METHODDEF _PICKLE_PICKLER___SIZEOF___METHODDEF {NULL, NULL} /* sentinel */ }; static void Pickler_dealloc(PicklerObject *self) { PyObject_GC_UnTrack(self); Py_XDECREF(self->output_buffer); Py_XDECREF(self->write); Py_XDECREF(self->pers_func); Py_XDECREF(self->dispatch_table); Py_XDECREF(self->fast_memo); PyMemoTable_Del(self->memo); Py_TYPE(self)->tp_free((PyObject *)self); } static int Pickler_traverse(PicklerObject *self, visitproc visit, void *arg) { Py_VISIT(self->write); Py_VISIT(self->pers_func); Py_VISIT(self->dispatch_table); Py_VISIT(self->fast_memo); return 0; } static int Pickler_clear(PicklerObject *self) { Py_CLEAR(self->output_buffer); Py_CLEAR(self->write); Py_CLEAR(self->pers_func); Py_CLEAR(self->dispatch_table); Py_CLEAR(self->fast_memo); if (self->memo != NULL) { PyMemoTable *memo = self->memo; self->memo = NULL; PyMemoTable_Del(memo); } return 0; } /*[clinic input] _pickle.Pickler.__init__ file: object protocol: object = NULL fix_imports: bool = True This takes a binary file for writing a pickle data stream. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3 and 4. The default protocol is 3; a backward-incompatible protocol designed for Python 3. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The *file* argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface. If *fix_imports* is True and protocol is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2. [clinic start generated code]*/ static int _pickle_Pickler___init___impl(PicklerObject *self, PyObject *file, PyObject *protocol, int fix_imports) /*[clinic end generated code: output=b5f31078dab17fb0 input=4faabdbc763c2389]*/ { _Py_IDENTIFIER(persistent_id); _Py_IDENTIFIER(dispatch_table); /* In case of multiple __init__() calls, clear previous content. */ if (self->write != NULL) (void)Pickler_clear(self); if (_Pickler_SetProtocol(self, protocol, fix_imports) < 0) return -1; if (_Pickler_SetOutputStream(self, file) < 0) return -1; /* memo and output_buffer may have already been created in _Pickler_New */ if (self->memo == NULL) { self->memo = PyMemoTable_New(); if (self->memo == NULL) return -1; } self->output_len = 0; if (self->output_buffer == NULL) { self->max_output_len = WRITE_BUF_SIZE; self->output_buffer = PyBytes_FromStringAndSize(NULL, self->max_output_len); if (self->output_buffer == NULL) return -1; } self->fast = 0; self->fast_nesting = 0; self->fast_memo = NULL; if (init_method_ref((PyObject *)self, &PyId_persistent_id, &self->pers_func, &self->pers_func_self) < 0) { return -1; } if (_PyObject_LookupAttrId((PyObject *)self, &PyId_dispatch_table, &self->dispatch_table) < 0) { return -1; } return 0; } /* Define a proxy object for the Pickler's internal memo object. This is to * avoid breaking code like: * pickler.memo.clear() * and * pickler.memo = saved_memo * Is this a good idea? Not really, but we don't want to break code that uses * it. Note that we don't implement the entire mapping API here. This is * intentional, as these should be treated as black-box implementation details. */ /*[clinic input] _pickle.PicklerMemoProxy.clear Remove all items from memo. [clinic start generated code]*/ static PyObject * _pickle_PicklerMemoProxy_clear_impl(PicklerMemoProxyObject *self) /*[clinic end generated code: output=5fb9370d48ae8b05 input=ccc186dacd0f1405]*/ { if (self->pickler->memo) PyMemoTable_Clear(self->pickler->memo); Py_RETURN_NONE; } /*[clinic input] _pickle.PicklerMemoProxy.copy Copy the memo to a new object. [clinic start generated code]*/ static PyObject * _pickle_PicklerMemoProxy_copy_impl(PicklerMemoProxyObject *self) /*[clinic end generated code: output=bb83a919d29225ef input=b73043485ac30b36]*/ { PyMemoTable *memo; PyObject *new_memo = PyDict_New(); if (new_memo == NULL) return NULL; memo = self->pickler->memo; for (size_t i = 0; i < memo->mt_allocated; ++i) { PyMemoEntry entry = memo->mt_table[i]; if (entry.me_key != NULL) { int status; PyObject *key, *value; key = PyLong_FromVoidPtr(entry.me_key); value = Py_BuildValue("nO", entry.me_value, entry.me_key); if (key == NULL || value == NULL) { Py_XDECREF(key); Py_XDECREF(value); goto error; } status = PyDict_SetItem(new_memo, key, value); Py_DECREF(key); Py_DECREF(value); if (status < 0) goto error; } } return new_memo; error: Py_XDECREF(new_memo); return NULL; } /*[clinic input] _pickle.PicklerMemoProxy.__reduce__ Implement pickle support. [clinic start generated code]*/ static PyObject * _pickle_PicklerMemoProxy___reduce___impl(PicklerMemoProxyObject *self) /*[clinic end generated code: output=bebba1168863ab1d input=2f7c540e24b7aae4]*/ { PyObject *reduce_value, *dict_args; PyObject *contents = _pickle_PicklerMemoProxy_copy_impl(self); if (contents == NULL) return NULL; reduce_value = PyTuple_New(2); if (reduce_value == NULL) { Py_DECREF(contents); return NULL; } dict_args = PyTuple_New(1); if (dict_args == NULL) { Py_DECREF(contents); Py_DECREF(reduce_value); return NULL; } PyTuple_SET_ITEM(dict_args, 0, contents); Py_INCREF((PyObject *)&PyDict_Type); PyTuple_SET_ITEM(reduce_value, 0, (PyObject *)&PyDict_Type); PyTuple_SET_ITEM(reduce_value, 1, dict_args); return reduce_value; } static PyMethodDef picklerproxy_methods[] = { _PICKLE_PICKLERMEMOPROXY_CLEAR_METHODDEF _PICKLE_PICKLERMEMOPROXY_COPY_METHODDEF _PICKLE_PICKLERMEMOPROXY___REDUCE___METHODDEF {NULL, NULL} /* sentinel */ }; static void PicklerMemoProxy_dealloc(PicklerMemoProxyObject *self) { PyObject_GC_UnTrack(self); Py_XDECREF(self->pickler); PyObject_GC_Del((PyObject *)self); } static int PicklerMemoProxy_traverse(PicklerMemoProxyObject *self, visitproc visit, void *arg) { Py_VISIT(self->pickler); return 0; } static int PicklerMemoProxy_clear(PicklerMemoProxyObject *self) { Py_CLEAR(self->pickler); return 0; } static PyTypeObject PicklerMemoProxyType = { PyVarObject_HEAD_INIT(NULL, 0) "_pickle.PicklerMemoProxy", /*tp_name*/ sizeof(PicklerMemoProxyObject), /*tp_basicsize*/ 0, (destructor)PicklerMemoProxy_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ PyObject_HashNotImplemented, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, 0, /* tp_doc */ (traverseproc)PicklerMemoProxy_traverse, /* tp_traverse */ (inquiry)PicklerMemoProxy_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ picklerproxy_methods, /* tp_methods */ }; static PyObject * PicklerMemoProxy_New(PicklerObject *pickler) { PicklerMemoProxyObject *self; self = PyObject_GC_New(PicklerMemoProxyObject, &PicklerMemoProxyType); if (self == NULL) return NULL; Py_INCREF(pickler); self->pickler = pickler; PyObject_GC_Track(self); return (PyObject *)self; } /*****************************************************************************/ static PyObject * Pickler_get_memo(PicklerObject *self, void *Py_UNUSED(ignored)) { return PicklerMemoProxy_New(self); } static int Pickler_set_memo(PicklerObject *self, PyObject *obj, void *Py_UNUSED(ignored)) { PyMemoTable *new_memo = NULL; if (obj == NULL) { PyErr_SetString(PyExc_TypeError, "attribute deletion is not supported"); return -1; } if (Py_TYPE(obj) == &PicklerMemoProxyType) { PicklerObject *pickler = ((PicklerMemoProxyObject *)obj)->pickler; new_memo = PyMemoTable_Copy(pickler->memo); if (new_memo == NULL) return -1; } else if (PyDict_Check(obj)) { Py_ssize_t i = 0; PyObject *key, *value; new_memo = PyMemoTable_New(); if (new_memo == NULL) return -1; while (PyDict_Next(obj, &i, &key, &value)) { Py_ssize_t memo_id; PyObject *memo_obj; if (!PyTuple_Check(value) || PyTuple_GET_SIZE(value) != 2) { PyErr_SetString(PyExc_TypeError, "'memo' values must be 2-item tuples"); goto error; } memo_id = PyLong_AsSsize_t(PyTuple_GET_ITEM(value, 0)); if (memo_id == -1 && PyErr_Occurred()) goto error; memo_obj = PyTuple_GET_ITEM(value, 1); if (PyMemoTable_Set(new_memo, memo_obj, memo_id) < 0) goto error; } } else { PyErr_Format(PyExc_TypeError, "'memo' attribute must be a PicklerMemoProxy object " "or dict, not %.200s", Py_TYPE(obj)->tp_name); return -1; } PyMemoTable_Del(self->memo); self->memo = new_memo; return 0; error: if (new_memo) PyMemoTable_Del(new_memo); return -1; } static PyObject * Pickler_get_persid(PicklerObject *self, void *Py_UNUSED(ignored)) { if (self->pers_func == NULL) { PyErr_SetString(PyExc_AttributeError, "persistent_id"); return NULL; } return reconstruct_method(self->pers_func, self->pers_func_self); } static int Pickler_set_persid(PicklerObject *self, PyObject *value, void *Py_UNUSED(ignored)) { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "attribute deletion is not supported"); return -1; } if (!PyCallable_Check(value)) { PyErr_SetString(PyExc_TypeError, "persistent_id must be a callable taking one argument"); return -1; } self->pers_func_self = NULL; Py_INCREF(value); Py_XSETREF(self->pers_func, value); return 0; } static PyMemberDef Pickler_members[] = { {"bin", T_INT, offsetof(PicklerObject, bin)}, {"fast", T_INT, offsetof(PicklerObject, fast)}, {"dispatch_table", T_OBJECT_EX, offsetof(PicklerObject, dispatch_table)}, {NULL} }; static PyGetSetDef Pickler_getsets[] = { {"memo", (getter)Pickler_get_memo, (setter)Pickler_set_memo}, {"persistent_id", (getter)Pickler_get_persid, (setter)Pickler_set_persid}, {NULL} }; static PyTypeObject Pickler_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_pickle.Pickler" , /*tp_name*/ sizeof(PicklerObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Pickler_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, _pickle_Pickler___init____doc__, /*tp_doc*/ (traverseproc)Pickler_traverse, /*tp_traverse*/ (inquiry)Pickler_clear, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ Pickler_methods, /*tp_methods*/ Pickler_members, /*tp_members*/ Pickler_getsets, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ _pickle_Pickler___init__, /*tp_init*/ PyType_GenericAlloc, /*tp_alloc*/ PyType_GenericNew, /*tp_new*/ PyObject_GC_Del, /*tp_free*/ 0, /*tp_is_gc*/ }; /* Temporary helper for calling self.find_class(). XXX: It would be nice to able to avoid Python function call overhead, by using directly the C version of find_class(), when find_class() is not overridden by a subclass. Although, this could become rather hackish. A simpler optimization would be to call the C function when self is not a subclass instance. */ static PyObject * find_class(UnpicklerObject *self, PyObject *module_name, PyObject *global_name) { _Py_IDENTIFIER(find_class); return _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_find_class, module_name, global_name, NULL); } static Py_ssize_t marker(UnpicklerObject *self) { Py_ssize_t mark; if (self->num_marks < 1) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "could not find MARK"); return -1; } mark = self->marks[--self->num_marks]; self->stack->mark_set = self->num_marks != 0; self->stack->fence = self->num_marks ? self->marks[self->num_marks - 1] : 0; return mark; } static int load_none(UnpicklerObject *self) { PDATA_APPEND(self->stack, Py_None, -1); return 0; } static int load_int(UnpicklerObject *self) { PyObject *value; char *endptr, *s; Py_ssize_t len; long x; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); errno = 0; /* XXX: Should the base argument of strtol() be explicitly set to 10? XXX(avassalotti): Should this uses PyOS_strtol()? */ x = strtol(s, &endptr, 0); if (errno || (*endptr != '\n' && *endptr != '\0')) { /* Hm, maybe we've got something long. Let's try reading * it as a Python int object. */ errno = 0; /* XXX: Same thing about the base here. */ value = PyLong_FromString(s, NULL, 0); if (value == NULL) { PyErr_SetString(PyExc_ValueError, "could not convert string to int"); return -1; } } else { if (len == 3 && (x == 0 || x == 1)) { if ((value = PyBool_FromLong(x)) == NULL) return -1; } else { if ((value = PyLong_FromLong(x)) == NULL) return -1; } } PDATA_PUSH(self->stack, value, -1); return 0; } static int load_bool(UnpicklerObject *self, PyObject *boolean) { assert(boolean == Py_True || boolean == Py_False); PDATA_APPEND(self->stack, boolean, -1); return 0; } /* s contains x bytes of an unsigned little-endian integer. Return its value * as a C Py_ssize_t, or -1 if it's higher than PY_SSIZE_T_MAX. */ static Py_ssize_t calc_binsize(char *bytes, int nbytes) { unsigned char *s = (unsigned char *)bytes; int i; size_t x = 0; if (nbytes > (int)sizeof(size_t)) { /* Check for integer overflow. BINBYTES8 and BINUNICODE8 opcodes * have 64-bit size that can't be represented on 32-bit platform. */ for (i = (int)sizeof(size_t); i < nbytes; i++) { if (s[i]) return -1; } nbytes = (int)sizeof(size_t); } for (i = 0; i < nbytes; i++) { x |= (size_t) s[i] << (8 * i); } if (x > PY_SSIZE_T_MAX) return -1; else return (Py_ssize_t) x; } /* s contains x bytes of a little-endian integer. Return its value as a * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian * int, but when x is 4 it's a signed one. This is a historical source * of x-platform bugs. */ static long calc_binint(char *bytes, int nbytes) { unsigned char *s = (unsigned char *)bytes; Py_ssize_t i; long x = 0; for (i = 0; i < nbytes; i++) { x |= (long)s[i] << (8 * i); } /* Unlike BININT1 and BININT2, BININT (more accurately BININT4) * is signed, so on a box with longs bigger than 4 bytes we need * to extend a BININT's sign bit to the full width. */ if (SIZEOF_LONG > 4 && nbytes == 4) { x |= -(x & (1L << 31)); } return x; } static int load_binintx(UnpicklerObject *self, char *s, int size) { PyObject *value; long x; x = calc_binint(s, size); if ((value = PyLong_FromLong(x)) == NULL) return -1; PDATA_PUSH(self->stack, value, -1); return 0; } static int load_binint(UnpicklerObject *self) { char *s; if (_Unpickler_Read(self, &s, 4) < 0) return -1; return load_binintx(self, s, 4); } static int load_binint1(UnpicklerObject *self) { char *s; if (_Unpickler_Read(self, &s, 1) < 0) return -1; return load_binintx(self, s, 1); } static int load_binint2(UnpicklerObject *self) { char *s; if (_Unpickler_Read(self, &s, 2) < 0) return -1; return load_binintx(self, s, 2); } static int load_long(UnpicklerObject *self) { PyObject *value; char *s = NULL; Py_ssize_t len; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); /* s[len-2] will usually be 'L' (and s[len-1] is '\n'); we need to remove the 'L' before calling PyLong_FromString. In order to maintain compatibility with Python 3.0.0, we don't actually *require* the 'L' to be present. */ if (s[len-2] == 'L') s[len-2] = '\0'; /* XXX: Should the base argument explicitly set to 10? */ value = PyLong_FromString(s, NULL, 0); if (value == NULL) return -1; PDATA_PUSH(self->stack, value, -1); return 0; } /* 'size' bytes contain the # of bytes of little-endian 256's-complement * data following. */ static int load_counted_long(UnpicklerObject *self, int size) { PyObject *value; char *nbytes; char *pdata; assert(size == 1 || size == 4); if (_Unpickler_Read(self, &nbytes, size) < 0) return -1; size = calc_binint(nbytes, size); if (size < 0) { PickleState *st = _Pickle_GetGlobalState(); /* Corrupt or hostile pickle -- we never write one like this */ PyErr_SetString(st->UnpicklingError, "LONG pickle has negative byte count"); return -1; } if (size == 0) value = PyLong_FromLong(0L); else { /* Read the raw little-endian bytes and convert. */ if (_Unpickler_Read(self, &pdata, size) < 0) return -1; value = _PyLong_FromByteArray((unsigned char *)pdata, (size_t)size, 1 /* little endian */ , 1 /* signed */ ); } if (value == NULL) return -1; PDATA_PUSH(self->stack, value, -1); return 0; } static int load_float(UnpicklerObject *self) { PyObject *value; char *endptr, *s; Py_ssize_t len; double d; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); errno = 0; d = PyOS_string_to_double(s, &endptr, PyExc_OverflowError); if (d == -1.0 && PyErr_Occurred()) return -1; if ((endptr[0] != '\n') && (endptr[0] != '\0')) { PyErr_SetString(PyExc_ValueError, "could not convert string to float"); return -1; } value = PyFloat_FromDouble(d); if (value == NULL) return -1; PDATA_PUSH(self->stack, value, -1); return 0; } static int load_binfloat(UnpicklerObject *self) { PyObject *value; double x; char *s; if (_Unpickler_Read(self, &s, 8) < 0) return -1; x = _PyFloat_Unpack8((unsigned char *)s, 0); if (x == -1.0 && PyErr_Occurred()) return -1; if ((value = PyFloat_FromDouble(x)) == NULL) return -1; PDATA_PUSH(self->stack, value, -1); return 0; } static int load_string(UnpicklerObject *self) { PyObject *bytes; PyObject *obj; Py_ssize_t len; char *s, *p; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; /* Strip the newline */ len--; /* Strip outermost quotes */ if (len >= 2 && s[0] == s[len - 1] && (s[0] == '\'' || s[0] == '"')) { p = s + 1; len -= 2; } else { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "the STRING opcode argument must be quoted"); return -1; } assert(len >= 0); /* Use the PyBytes API to decode the string, since that is what is used to encode, and then coerce the result to Unicode. */ bytes = PyBytes_DecodeEscape(p, len, NULL, 0, NULL); if (bytes == NULL) return -1; /* Leave the Python 2.x strings as bytes if the *encoding* given to the Unpickler was 'bytes'. Otherwise, convert them to unicode. */ if (strcmp(self->encoding, "bytes") == 0) { obj = bytes; } else { obj = PyUnicode_FromEncodedObject(bytes, self->encoding, self->errors); Py_DECREF(bytes); if (obj == NULL) { return -1; } } PDATA_PUSH(self->stack, obj, -1); return 0; } static int load_counted_binstring(UnpicklerObject *self, int nbytes) { PyObject *obj; Py_ssize_t size; char *s; if (_Unpickler_Read(self, &s, nbytes) < 0) return -1; size = calc_binsize(s, nbytes); if (size < 0) { PickleState *st = _Pickle_GetGlobalState(); PyErr_Format(st->UnpicklingError, "BINSTRING exceeds system's maximum size of %zd bytes", PY_SSIZE_T_MAX); return -1; } if (_Unpickler_Read(self, &s, size) < 0) return -1; /* Convert Python 2.x strings to bytes if the *encoding* given to the Unpickler was 'bytes'. Otherwise, convert them to unicode. */ if (strcmp(self->encoding, "bytes") == 0) { obj = PyBytes_FromStringAndSize(s, size); } else { obj = PyUnicode_Decode(s, size, self->encoding, self->errors); } if (obj == NULL) { return -1; } PDATA_PUSH(self->stack, obj, -1); return 0; } static int load_counted_binbytes(UnpicklerObject *self, int nbytes) { PyObject *bytes; Py_ssize_t size; char *s; if (_Unpickler_Read(self, &s, nbytes) < 0) return -1; size = calc_binsize(s, nbytes); if (size < 0) { PyErr_Format(PyExc_OverflowError, "BINBYTES exceeds system's maximum size of %zd bytes", PY_SSIZE_T_MAX); return -1; } if (_Unpickler_Read(self, &s, size) < 0) return -1; bytes = PyBytes_FromStringAndSize(s, size); if (bytes == NULL) return -1; PDATA_PUSH(self->stack, bytes, -1); return 0; } static int load_unicode(UnpicklerObject *self) { PyObject *str; Py_ssize_t len; char *s = NULL; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 1) return bad_readline(); str = PyUnicode_DecodeRawUnicodeEscape(s, len - 1, NULL); if (str == NULL) return -1; PDATA_PUSH(self->stack, str, -1); return 0; } static int load_counted_binunicode(UnpicklerObject *self, int nbytes) { PyObject *str; Py_ssize_t size; char *s; if (_Unpickler_Read(self, &s, nbytes) < 0) return -1; size = calc_binsize(s, nbytes); if (size < 0) { PyErr_Format(PyExc_OverflowError, "BINUNICODE exceeds system's maximum size of %zd bytes", PY_SSIZE_T_MAX); return -1; } if (_Unpickler_Read(self, &s, size) < 0) return -1; str = PyUnicode_DecodeUTF8(s, size, "surrogatepass"); if (str == NULL) return -1; PDATA_PUSH(self->stack, str, -1); return 0; } static int load_counted_tuple(UnpicklerObject *self, Py_ssize_t len) { PyObject *tuple; if (Py_SIZE(self->stack) < len) return Pdata_stack_underflow(self->stack); tuple = Pdata_poptuple(self->stack, Py_SIZE(self->stack) - len); if (tuple == NULL) return -1; PDATA_PUSH(self->stack, tuple, -1); return 0; } static int load_tuple(UnpicklerObject *self) { Py_ssize_t i; if ((i = marker(self)) < 0) return -1; return load_counted_tuple(self, Py_SIZE(self->stack) - i); } static int load_empty_list(UnpicklerObject *self) { PyObject *list; if ((list = PyList_New(0)) == NULL) return -1; PDATA_PUSH(self->stack, list, -1); return 0; } static int load_empty_dict(UnpicklerObject *self) { PyObject *dict; if ((dict = PyDict_New()) == NULL) return -1; PDATA_PUSH(self->stack, dict, -1); return 0; } static int load_empty_set(UnpicklerObject *self) { PyObject *set; if ((set = PySet_New(NULL)) == NULL) return -1; PDATA_PUSH(self->stack, set, -1); return 0; } static int load_list(UnpicklerObject *self) { PyObject *list; Py_ssize_t i; if ((i = marker(self)) < 0) return -1; list = Pdata_poplist(self->stack, i); if (list == NULL) return -1; PDATA_PUSH(self->stack, list, -1); return 0; } static int load_dict(UnpicklerObject *self) { PyObject *dict, *key, *value; Py_ssize_t i, j, k; if ((i = marker(self)) < 0) return -1; j = Py_SIZE(self->stack); if ((dict = PyDict_New()) == NULL) return -1; if ((j - i) % 2 != 0) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "odd number of items for DICT"); Py_DECREF(dict); return -1; } for (k = i + 1; k < j; k += 2) { key = self->stack->data[k - 1]; value = self->stack->data[k]; if (PyDict_SetItem(dict, key, value) < 0) { Py_DECREF(dict); return -1; } } Pdata_clear(self->stack, i); PDATA_PUSH(self->stack, dict, -1); return 0; } static int load_frozenset(UnpicklerObject *self) { PyObject *items; PyObject *frozenset; Py_ssize_t i; if ((i = marker(self)) < 0) return -1; items = Pdata_poptuple(self->stack, i); if (items == NULL) return -1; frozenset = PyFrozenSet_New(items); Py_DECREF(items); if (frozenset == NULL) return -1; PDATA_PUSH(self->stack, frozenset, -1); return 0; } static PyObject * instantiate(PyObject *cls, PyObject *args) { /* Caller must assure args are a tuple. Normally, args come from Pdata_poptuple which packs objects from the top of the stack into a newly created tuple. */ assert(PyTuple_Check(args)); if (!PyTuple_GET_SIZE(args) && PyType_Check(cls)) { _Py_IDENTIFIER(__getinitargs__); _Py_IDENTIFIER(__new__); PyObject *func; if (_PyObject_LookupAttrId(cls, &PyId___getinitargs__, &func) < 0) { return NULL; } if (func == NULL) { return _PyObject_CallMethodIdObjArgs(cls, &PyId___new__, cls, NULL); } Py_DECREF(func); } return PyObject_CallObject(cls, args); } static int load_obj(UnpicklerObject *self) { PyObject *cls, *args, *obj = NULL; Py_ssize_t i; if ((i = marker(self)) < 0) return -1; if (Py_SIZE(self->stack) - i < 1) return Pdata_stack_underflow(self->stack); args = Pdata_poptuple(self->stack, i + 1); if (args == NULL) return -1; PDATA_POP(self->stack, cls); if (cls) { obj = instantiate(cls, args); Py_DECREF(cls); } Py_DECREF(args); if (obj == NULL) return -1; PDATA_PUSH(self->stack, obj, -1); return 0; } static int load_inst(UnpicklerObject *self) { PyObject *cls = NULL; PyObject *args = NULL; PyObject *obj = NULL; PyObject *module_name; PyObject *class_name; Py_ssize_t len; Py_ssize_t i; char *s; if ((i = marker(self)) < 0) return -1; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); /* Here it is safe to use PyUnicode_DecodeASCII(), even though non-ASCII identifiers are permitted in Python 3.0, since the INST opcode is only supported by older protocols on Python 2.x. */ module_name = PyUnicode_DecodeASCII(s, len - 1, "strict"); if (module_name == NULL) return -1; if ((len = _Unpickler_Readline(self, &s)) >= 0) { if (len < 2) { Py_DECREF(module_name); return bad_readline(); } class_name = PyUnicode_DecodeASCII(s, len - 1, "strict"); if (class_name != NULL) { cls = find_class(self, module_name, class_name); Py_DECREF(class_name); } } Py_DECREF(module_name); if (cls == NULL) return -1; if ((args = Pdata_poptuple(self->stack, i)) != NULL) { obj = instantiate(cls, args); Py_DECREF(args); } Py_DECREF(cls); if (obj == NULL) return -1; PDATA_PUSH(self->stack, obj, -1); return 0; } static int load_newobj(UnpicklerObject *self) { PyObject *args = NULL; PyObject *clsraw = NULL; PyTypeObject *cls; /* clsraw cast to its true type */ PyObject *obj; PickleState *st = _Pickle_GetGlobalState(); /* Stack is ... cls argtuple, and we want to call * cls.__new__(cls, *argtuple). */ PDATA_POP(self->stack, args); if (args == NULL) goto error; if (!PyTuple_Check(args)) { PyErr_SetString(st->UnpicklingError, "NEWOBJ expected an arg " "tuple."); goto error; } PDATA_POP(self->stack, clsraw); cls = (PyTypeObject *)clsraw; if (cls == NULL) goto error; if (!PyType_Check(cls)) { PyErr_SetString(st->UnpicklingError, "NEWOBJ class argument " "isn't a type object"); goto error; } if (cls->tp_new == NULL) { PyErr_SetString(st->UnpicklingError, "NEWOBJ class argument " "has NULL tp_new"); goto error; } /* Call __new__. */ obj = cls->tp_new(cls, args, NULL); if (obj == NULL) goto error; Py_DECREF(args); Py_DECREF(clsraw); PDATA_PUSH(self->stack, obj, -1); return 0; error: Py_XDECREF(args); Py_XDECREF(clsraw); return -1; } static int load_newobj_ex(UnpicklerObject *self) { PyObject *cls, *args, *kwargs; PyObject *obj; PickleState *st = _Pickle_GetGlobalState(); PDATA_POP(self->stack, kwargs); if (kwargs == NULL) { return -1; } PDATA_POP(self->stack, args); if (args == NULL) { Py_DECREF(kwargs); return -1; } PDATA_POP(self->stack, cls); if (cls == NULL) { Py_DECREF(kwargs); Py_DECREF(args); return -1; } if (!PyType_Check(cls)) { Py_DECREF(kwargs); Py_DECREF(args); PyErr_Format(st->UnpicklingError, "NEWOBJ_EX class argument must be a type, not %.200s", Py_TYPE(cls)->tp_name); Py_DECREF(cls); return -1; } if (((PyTypeObject *)cls)->tp_new == NULL) { Py_DECREF(kwargs); Py_DECREF(args); Py_DECREF(cls); PyErr_SetString(st->UnpicklingError, "NEWOBJ_EX class argument doesn't have __new__"); return -1; } obj = ((PyTypeObject *)cls)->tp_new((PyTypeObject *)cls, args, kwargs); Py_DECREF(kwargs); Py_DECREF(args); Py_DECREF(cls); if (obj == NULL) { return -1; } PDATA_PUSH(self->stack, obj, -1); return 0; } static int load_global(UnpicklerObject *self) { PyObject *global = NULL; PyObject *module_name; PyObject *global_name; Py_ssize_t len; char *s; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); module_name = PyUnicode_DecodeUTF8(s, len - 1, "strict"); if (!module_name) return -1; if ((len = _Unpickler_Readline(self, &s)) >= 0) { if (len < 2) { Py_DECREF(module_name); return bad_readline(); } global_name = PyUnicode_DecodeUTF8(s, len - 1, "strict"); if (global_name) { global = find_class(self, module_name, global_name); Py_DECREF(global_name); } } Py_DECREF(module_name); if (global == NULL) return -1; PDATA_PUSH(self->stack, global, -1); return 0; } static int load_stack_global(UnpicklerObject *self) { PyObject *global; PyObject *module_name; PyObject *global_name; PDATA_POP(self->stack, global_name); PDATA_POP(self->stack, module_name); if (module_name == NULL || !PyUnicode_CheckExact(module_name) || global_name == NULL || !PyUnicode_CheckExact(global_name)) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "STACK_GLOBAL requires str"); Py_XDECREF(global_name); Py_XDECREF(module_name); return -1; } global = find_class(self, module_name, global_name); Py_DECREF(global_name); Py_DECREF(module_name); if (global == NULL) return -1; PDATA_PUSH(self->stack, global, -1); return 0; } static int load_persid(UnpicklerObject *self) { PyObject *pid, *obj; Py_ssize_t len; char *s; if (self->pers_func) { if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 1) return bad_readline(); pid = PyUnicode_DecodeASCII(s, len - 1, "strict"); if (pid == NULL) { if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { PyErr_SetString(_Pickle_GetGlobalState()->UnpicklingError, "persistent IDs in protocol 0 must be " "ASCII strings"); } return -1; } obj = call_method(self->pers_func, self->pers_func_self, pid); Py_DECREF(pid); if (obj == NULL) return -1; PDATA_PUSH(self->stack, obj, -1); return 0; } else { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "A load persistent id instruction was encountered,\n" "but no persistent_load function was specified."); return -1; } } static int load_binpersid(UnpicklerObject *self) { PyObject *pid, *obj; if (self->pers_func) { PDATA_POP(self->stack, pid); if (pid == NULL) return -1; obj = call_method(self->pers_func, self->pers_func_self, pid); Py_DECREF(pid); if (obj == NULL) return -1; PDATA_PUSH(self->stack, obj, -1); return 0; } else { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "A load persistent id instruction was encountered,\n" "but no persistent_load function was specified."); return -1; } } static int load_pop(UnpicklerObject *self) { Py_ssize_t len = Py_SIZE(self->stack); /* Note that we split the (pickle.py) stack into two stacks, * an object stack and a mark stack. We have to be clever and * pop the right one. We do this by looking at the top of the * mark stack first, and only signalling a stack underflow if * the object stack is empty and the mark stack doesn't match * our expectations. */ if (self->num_marks > 0 && self->marks[self->num_marks - 1] == len) { self->num_marks--; self->stack->mark_set = self->num_marks != 0; self->stack->fence = self->num_marks ? self->marks[self->num_marks - 1] : 0; } else if (len <= self->stack->fence) return Pdata_stack_underflow(self->stack); else { len--; Py_DECREF(self->stack->data[len]); Py_SIZE(self->stack) = len; } return 0; } static int load_pop_mark(UnpicklerObject *self) { Py_ssize_t i; if ((i = marker(self)) < 0) return -1; Pdata_clear(self->stack, i); return 0; } static int load_dup(UnpicklerObject *self) { PyObject *last; Py_ssize_t len = Py_SIZE(self->stack); if (len <= self->stack->fence) return Pdata_stack_underflow(self->stack); last = self->stack->data[len - 1]; PDATA_APPEND(self->stack, last, -1); return 0; } static int load_get(UnpicklerObject *self) { PyObject *key, *value; Py_ssize_t idx; Py_ssize_t len; char *s; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); key = PyLong_FromString(s, NULL, 10); if (key == NULL) return -1; idx = PyLong_AsSsize_t(key); if (idx == -1 && PyErr_Occurred()) { Py_DECREF(key); return -1; } value = _Unpickler_MemoGet(self, idx); if (value == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); return -1; } Py_DECREF(key); PDATA_APPEND(self->stack, value, -1); return 0; } static int load_binget(UnpicklerObject *self) { PyObject *value; Py_ssize_t idx; char *s; if (_Unpickler_Read(self, &s, 1) < 0) return -1; idx = Py_CHARMASK(s[0]); value = _Unpickler_MemoGet(self, idx); if (value == NULL) { PyObject *key = PyLong_FromSsize_t(idx); if (key != NULL) { PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); } return -1; } PDATA_APPEND(self->stack, value, -1); return 0; } static int load_long_binget(UnpicklerObject *self) { PyObject *value; Py_ssize_t idx; char *s; if (_Unpickler_Read(self, &s, 4) < 0) return -1; idx = calc_binsize(s, 4); value = _Unpickler_MemoGet(self, idx); if (value == NULL) { PyObject *key = PyLong_FromSsize_t(idx); if (key != NULL) { PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); } return -1; } PDATA_APPEND(self->stack, value, -1); return 0; } /* Push an object from the extension registry (EXT[124]). nbytes is * the number of bytes following the opcode, holding the index (code) value. */ static int load_extension(UnpicklerObject *self, int nbytes) { char *codebytes; /* the nbytes bytes after the opcode */ long code; /* calc_binint returns long */ PyObject *py_code; /* code as a Python int */ PyObject *obj; /* the object to push */ PyObject *pair; /* (module_name, class_name) */ PyObject *module_name, *class_name; PickleState *st = _Pickle_GetGlobalState(); assert(nbytes == 1 || nbytes == 2 || nbytes == 4); if (_Unpickler_Read(self, &codebytes, nbytes) < 0) return -1; code = calc_binint(codebytes, nbytes); if (code <= 0) { /* note that 0 is forbidden */ /* Corrupt or hostile pickle. */ PyErr_SetString(st->UnpicklingError, "EXT specifies code <= 0"); return -1; } /* Look for the code in the cache. */ py_code = PyLong_FromLong(code); if (py_code == NULL) return -1; obj = PyDict_GetItemWithError(st->extension_cache, py_code); if (obj != NULL) { /* Bingo. */ Py_DECREF(py_code); PDATA_APPEND(self->stack, obj, -1); return 0; } if (PyErr_Occurred()) { Py_DECREF(py_code); return -1; } /* Look up the (module_name, class_name) pair. */ pair = PyDict_GetItemWithError(st->inverted_registry, py_code); if (pair == NULL) { Py_DECREF(py_code); if (!PyErr_Occurred()) { PyErr_Format(PyExc_ValueError, "unregistered extension " "code %ld", code); } return -1; } /* Since the extension registry is manipulable via Python code, * confirm that pair is really a 2-tuple of strings. */ if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2) { goto error; } module_name = PyTuple_GET_ITEM(pair, 0); if (!PyUnicode_Check(module_name)) { goto error; } class_name = PyTuple_GET_ITEM(pair, 1); if (!PyUnicode_Check(class_name)) { goto error; } /* Load the object. */ obj = find_class(self, module_name, class_name); if (obj == NULL) { Py_DECREF(py_code); return -1; } /* Cache code -> obj. */ code = PyDict_SetItem(st->extension_cache, py_code, obj); Py_DECREF(py_code); if (code < 0) { Py_DECREF(obj); return -1; } PDATA_PUSH(self->stack, obj, -1); return 0; error: Py_DECREF(py_code); PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] " "isn't a 2-tuple of strings", code); return -1; } static int load_put(UnpicklerObject *self) { PyObject *key, *value; Py_ssize_t idx; Py_ssize_t len; char *s = NULL; if ((len = _Unpickler_Readline(self, &s)) < 0) return -1; if (len < 2) return bad_readline(); if (Py_SIZE(self->stack) <= self->stack->fence) return Pdata_stack_underflow(self->stack); value = self->stack->data[Py_SIZE(self->stack) - 1]; key = PyLong_FromString(s, NULL, 10); if (key == NULL) return -1; idx = PyLong_AsSsize_t(key); Py_DECREF(key); if (idx < 0) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "negative PUT argument"); return -1; } return _Unpickler_MemoPut(self, idx, value); } static int load_binput(UnpicklerObject *self) { PyObject *value; Py_ssize_t idx; char *s; if (_Unpickler_Read(self, &s, 1) < 0) return -1; if (Py_SIZE(self->stack) <= self->stack->fence) return Pdata_stack_underflow(self->stack); value = self->stack->data[Py_SIZE(self->stack) - 1]; idx = Py_CHARMASK(s[0]); return _Unpickler_MemoPut(self, idx, value); } static int load_long_binput(UnpicklerObject *self) { PyObject *value; Py_ssize_t idx; char *s; if (_Unpickler_Read(self, &s, 4) < 0) return -1; if (Py_SIZE(self->stack) <= self->stack->fence) return Pdata_stack_underflow(self->stack); value = self->stack->data[Py_SIZE(self->stack) - 1]; idx = calc_binsize(s, 4); if (idx < 0) { PyErr_SetString(PyExc_ValueError, "negative LONG_BINPUT argument"); return -1; } return _Unpickler_MemoPut(self, idx, value); } static int load_memoize(UnpicklerObject *self) { PyObject *value; if (Py_SIZE(self->stack) <= self->stack->fence) return Pdata_stack_underflow(self->stack); value = self->stack->data[Py_SIZE(self->stack) - 1]; return _Unpickler_MemoPut(self, self->memo_len, value); } static int do_append(UnpicklerObject *self, Py_ssize_t x) { PyObject *value; PyObject *slice; PyObject *list; PyObject *result; Py_ssize_t len, i; len = Py_SIZE(self->stack); if (x > len || x <= self->stack->fence) return Pdata_stack_underflow(self->stack); if (len == x) /* nothing to do */ return 0; list = self->stack->data[x - 1]; if (PyList_CheckExact(list)) { Py_ssize_t list_len; int ret; slice = Pdata_poplist(self->stack, x); if (!slice) return -1; list_len = PyList_GET_SIZE(list); ret = PyList_SetSlice(list, list_len, list_len, slice); Py_DECREF(slice); return ret; } else { PyObject *extend_func; _Py_IDENTIFIER(extend); extend_func = _PyObject_GetAttrId(list, &PyId_extend); if (extend_func != NULL) { slice = Pdata_poplist(self->stack, x); if (!slice) { Py_DECREF(extend_func); return -1; } result = _Pickle_FastCall(extend_func, slice); Py_DECREF(extend_func); if (result == NULL) return -1; Py_DECREF(result); } else { PyObject *append_func; _Py_IDENTIFIER(append); /* Even if the PEP 307 requires extend() and append() methods, fall back on append() if the object has no extend() method for backward compatibility. */ PyErr_Clear(); append_func = _PyObject_GetAttrId(list, &PyId_append); if (append_func == NULL) return -1; for (i = x; i < len; i++) { value = self->stack->data[i]; result = _Pickle_FastCall(append_func, value); if (result == NULL) { Pdata_clear(self->stack, i + 1); Py_SIZE(self->stack) = x; Py_DECREF(append_func); return -1; } Py_DECREF(result); } Py_SIZE(self->stack) = x; Py_DECREF(append_func); } } return 0; } static int load_append(UnpicklerObject *self) { if (Py_SIZE(self->stack) - 1 <= self->stack->fence) return Pdata_stack_underflow(self->stack); return do_append(self, Py_SIZE(self->stack) - 1); } static int load_appends(UnpicklerObject *self) { Py_ssize_t i = marker(self); if (i < 0) return -1; return do_append(self, i); } static int do_setitems(UnpicklerObject *self, Py_ssize_t x) { PyObject *value, *key; PyObject *dict; Py_ssize_t len, i; int status = 0; len = Py_SIZE(self->stack); if (x > len || x <= self->stack->fence) return Pdata_stack_underflow(self->stack); if (len == x) /* nothing to do */ return 0; if ((len - x) % 2 != 0) { PickleState *st = _Pickle_GetGlobalState(); /* Currupt or hostile pickle -- we never write one like this. */ PyErr_SetString(st->UnpicklingError, "odd number of items for SETITEMS"); return -1; } /* Here, dict does not actually need to be a PyDict; it could be anything that supports the __setitem__ attribute. */ dict = self->stack->data[x - 1]; for (i = x + 1; i < len; i += 2) { key = self->stack->data[i - 1]; value = self->stack->data[i]; if (PyObject_SetItem(dict, key, value) < 0) { status = -1; break; } } Pdata_clear(self->stack, x); return status; } static int load_setitem(UnpicklerObject *self) { return do_setitems(self, Py_SIZE(self->stack) - 2); } static int load_setitems(UnpicklerObject *self) { Py_ssize_t i = marker(self); if (i < 0) return -1; return do_setitems(self, i); } static int load_additems(UnpicklerObject *self) { PyObject *set; Py_ssize_t mark, len, i; mark = marker(self); if (mark < 0) return -1; len = Py_SIZE(self->stack); if (mark > len || mark <= self->stack->fence) return Pdata_stack_underflow(self->stack); if (len == mark) /* nothing to do */ return 0; set = self->stack->data[mark - 1]; if (PySet_Check(set)) { PyObject *items; int status; items = Pdata_poptuple(self->stack, mark); if (items == NULL) return -1; status = _PySet_Update(set, items); Py_DECREF(items); return status; } else { PyObject *add_func; _Py_IDENTIFIER(add); add_func = _PyObject_GetAttrId(set, &PyId_add); if (add_func == NULL) return -1; for (i = mark; i < len; i++) { PyObject *result; PyObject *item; item = self->stack->data[i]; result = _Pickle_FastCall(add_func, item); if (result == NULL) { Pdata_clear(self->stack, i + 1); Py_SIZE(self->stack) = mark; return -1; } Py_DECREF(result); } Py_SIZE(self->stack) = mark; } return 0; } static int load_build(UnpicklerObject *self) { PyObject *state, *inst, *slotstate; PyObject *setstate; int status = 0; _Py_IDENTIFIER(__setstate__); /* Stack is ... instance, state. We want to leave instance at * the stack top, possibly mutated via instance.__setstate__(state). */ if (Py_SIZE(self->stack) - 2 < self->stack->fence) return Pdata_stack_underflow(self->stack); PDATA_POP(self->stack, state); if (state == NULL) return -1; inst = self->stack->data[Py_SIZE(self->stack) - 1]; if (_PyObject_LookupAttrId(inst, &PyId___setstate__, &setstate) < 0) { Py_DECREF(state); return -1; } if (setstate != NULL) { PyObject *result; /* The explicit __setstate__ is responsible for everything. */ result = _Pickle_FastCall(setstate, state); Py_DECREF(setstate); if (result == NULL) return -1; Py_DECREF(result); return 0; } /* A default __setstate__. First see whether state embeds a * slot state dict too (a proto 2 addition). */ if (PyTuple_Check(state) && PyTuple_GET_SIZE(state) == 2) { PyObject *tmp = state; state = PyTuple_GET_ITEM(tmp, 0); slotstate = PyTuple_GET_ITEM(tmp, 1); Py_INCREF(state); Py_INCREF(slotstate); Py_DECREF(tmp); } else slotstate = NULL; /* Set inst.__dict__ from the state dict (if any). */ if (state != Py_None) { PyObject *dict; PyObject *d_key, *d_value; Py_ssize_t i; _Py_IDENTIFIER(__dict__); if (!PyDict_Check(state)) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "state is not a dictionary"); goto error; } dict = _PyObject_GetAttrId(inst, &PyId___dict__); if (dict == NULL) goto error; i = 0; while (PyDict_Next(state, &i, &d_key, &d_value)) { /* normally the keys for instance attributes are interned. we should try to do that here. */ Py_INCREF(d_key); if (PyUnicode_CheckExact(d_key)) PyUnicode_InternInPlace(&d_key); if (PyObject_SetItem(dict, d_key, d_value) < 0) { Py_DECREF(d_key); goto error; } Py_DECREF(d_key); } Py_DECREF(dict); } /* Also set instance attributes from the slotstate dict (if any). */ if (slotstate != NULL) { PyObject *d_key, *d_value; Py_ssize_t i; if (!PyDict_Check(slotstate)) { PickleState *st = _Pickle_GetGlobalState(); PyErr_SetString(st->UnpicklingError, "slot state is not a dictionary"); goto error; } i = 0; while (PyDict_Next(slotstate, &i, &d_key, &d_value)) { if (PyObject_SetAttr(inst, d_key, d_value) < 0) goto error; } } if (0) { error: status = -1; } Py_DECREF(state); Py_XDECREF(slotstate); return status; } static int load_mark(UnpicklerObject *self) { /* Note that we split the (pickle.py) stack into two stacks, an * object stack and a mark stack. Here we push a mark onto the * mark stack. */ if (self->num_marks >= self->marks_size) { size_t alloc = ((size_t)self->num_marks << 1) + 20; Py_ssize_t *marks_new = self->marks; PyMem_RESIZE(marks_new, Py_ssize_t, alloc); if (marks_new == NULL) { PyErr_NoMemory(); return -1; } self->marks = marks_new; self->marks_size = (Py_ssize_t)alloc; } self->stack->mark_set = 1; self->marks[self->num_marks++] = self->stack->fence = Py_SIZE(self->stack); return 0; } static int load_reduce(UnpicklerObject *self) { PyObject *callable = NULL; PyObject *argtup = NULL; PyObject *obj = NULL; PDATA_POP(self->stack, argtup); if (argtup == NULL) return -1; PDATA_POP(self->stack, callable); if (callable) { obj = PyObject_CallObject(callable, argtup); Py_DECREF(callable); } Py_DECREF(argtup); if (obj == NULL) return -1; PDATA_PUSH(self->stack, obj, -1); return 0; } /* Just raises an error if we don't know the protocol specified. PROTO * is the first opcode for protocols >= 2. */ static int load_proto(UnpicklerObject *self) { char *s; int i; if (_Unpickler_Read(self, &s, 1) < 0) return -1; i = (unsigned char)s[0]; if (i <= HIGHEST_PROTOCOL) { self->proto = i; return 0; } PyErr_Format(PyExc_ValueError, "unsupported pickle protocol: %d", i); return -1; } static int load_frame(UnpicklerObject *self) { char *s; Py_ssize_t frame_len; if (_Unpickler_Read(self, &s, 8) < 0) return -1; frame_len = calc_binsize(s, 8); if (frame_len < 0) { PyErr_Format(PyExc_OverflowError, "FRAME length exceeds system's maximum of %zd bytes", PY_SSIZE_T_MAX); return -1; } if (_Unpickler_Read(self, &s, frame_len) < 0) return -1; /* Rewind to start of frame */ self->next_read_idx -= frame_len; return 0; } static PyObject * load(UnpicklerObject *self) { PyObject *value = NULL; char *s = NULL; self->num_marks = 0; self->stack->mark_set = 0; self->stack->fence = 0; self->proto = 0; if (Py_SIZE(self->stack)) Pdata_clear(self->stack, 0); /* Convenient macros for the dispatch while-switch loop just below. */ #define OP(opcode, load_func) \ case opcode: if (load_func(self) < 0) break; continue; #define OP_ARG(opcode, load_func, arg) \ case opcode: if (load_func(self, (arg)) < 0) break; continue; while (1) { if (_Unpickler_Read(self, &s, 1) < 0) { PickleState *st = _Pickle_GetGlobalState(); if (PyErr_ExceptionMatches(st->UnpicklingError)) { PyErr_Format(PyExc_EOFError, "Ran out of input"); } return NULL; } switch ((enum opcode)s[0]) { OP(NONE, load_none) OP(BININT, load_binint) OP(BININT1, load_binint1) OP(BININT2, load_binint2) OP(INT, load_int) OP(LONG, load_long) OP_ARG(LONG1, load_counted_long, 1) OP_ARG(LONG4, load_counted_long, 4) OP(FLOAT, load_float) OP(BINFLOAT, load_binfloat) OP_ARG(SHORT_BINBYTES, load_counted_binbytes, 1) OP_ARG(BINBYTES, load_counted_binbytes, 4) OP_ARG(BINBYTES8, load_counted_binbytes, 8) OP_ARG(SHORT_BINSTRING, load_counted_binstring, 1) OP_ARG(BINSTRING, load_counted_binstring, 4) OP(STRING, load_string) OP(UNICODE, load_unicode) OP_ARG(SHORT_BINUNICODE, load_counted_binunicode, 1) OP_ARG(BINUNICODE, load_counted_binunicode, 4) OP_ARG(BINUNICODE8, load_counted_binunicode, 8) OP_ARG(EMPTY_TUPLE, load_counted_tuple, 0) OP_ARG(TUPLE1, load_counted_tuple, 1) OP_ARG(TUPLE2, load_counted_tuple, 2) OP_ARG(TUPLE3, load_counted_tuple, 3) OP(TUPLE, load_tuple) OP(EMPTY_LIST, load_empty_list) OP(LIST, load_list) OP(EMPTY_DICT, load_empty_dict) OP(DICT, load_dict) OP(EMPTY_SET, load_empty_set) OP(ADDITEMS, load_additems) OP(FROZENSET, load_frozenset) OP(OBJ, load_obj) OP(INST, load_inst) OP(NEWOBJ, load_newobj) OP(NEWOBJ_EX, load_newobj_ex) OP(GLOBAL, load_global) OP(STACK_GLOBAL, load_stack_global) OP(APPEND, load_append) OP(APPENDS, load_appends) OP(BUILD, load_build) OP(DUP, load_dup) OP(BINGET, load_binget) OP(LONG_BINGET, load_long_binget) OP(GET, load_get) OP(MARK, load_mark) OP(BINPUT, load_binput) OP(LONG_BINPUT, load_long_binput) OP(PUT, load_put) OP(MEMOIZE, load_memoize) OP(POP, load_pop) OP(POP_MARK, load_pop_mark) OP(SETITEM, load_setitem) OP(SETITEMS, load_setitems) OP(PERSID, load_persid) OP(BINPERSID, load_binpersid) OP(REDUCE, load_reduce) OP(PROTO, load_proto) OP(FRAME, load_frame) OP_ARG(EXT1, load_extension, 1) OP_ARG(EXT2, load_extension, 2) OP_ARG(EXT4, load_extension, 4) OP_ARG(NEWTRUE, load_bool, Py_True) OP_ARG(NEWFALSE, load_bool, Py_False) case STOP: break; default: { PickleState *st = _Pickle_GetGlobalState(); unsigned char c = (unsigned char) *s; if (0x20 <= c && c <= 0x7e && c != '\'' && c != '\\') { PyErr_Format(st->UnpicklingError, "invalid load key, '%c'.", c); } else { PyErr_Format(st->UnpicklingError, "invalid load key, '\\x%02x'.", c); } return NULL; } } break; /* and we are done! */ } if (PyErr_Occurred()) { return NULL; } if (_Unpickler_SkipConsumed(self) < 0) return NULL; PDATA_POP(self->stack, value); return value; } /*[clinic input] _pickle.Unpickler.load Load a pickle. Read a pickled object representation from the open file object given in the constructor, and return the reconstituted object hierarchy specified therein. [clinic start generated code]*/ static PyObject * _pickle_Unpickler_load_impl(UnpicklerObject *self) /*[clinic end generated code: output=fdcc488aad675b14 input=acbb91a42fa9b7b9]*/ { UnpicklerObject *unpickler = (UnpicklerObject*)self; /* Check whether the Unpickler was initialized correctly. This prevents segfaulting if a subclass overridden __init__ with a function that does not call Unpickler.__init__(). Here, we simply ensure that self->read is not NULL. */ if (unpickler->read == NULL) { PickleState *st = _Pickle_GetGlobalState(); PyErr_Format(st->UnpicklingError, "Unpickler.__init__() was not called by %s.__init__()", Py_TYPE(unpickler)->tp_name); return NULL; } return load(unpickler); } /* The name of find_class() is misleading. In newer pickle protocols, this function is used for loading any global (i.e., functions), not just classes. The name is kept only for backward compatibility. */ /*[clinic input] _pickle.Unpickler.find_class module_name: object global_name: object / Return an object from a specified module. If necessary, the module will be imported. Subclasses may override this method (e.g. to restrict unpickling of arbitrary classes and functions). This method is called whenever a class or a function object is needed. Both arguments passed are str objects. [clinic start generated code]*/ static PyObject * _pickle_Unpickler_find_class_impl(UnpicklerObject *self, PyObject *module_name, PyObject *global_name) /*[clinic end generated code: output=becc08d7f9ed41e3 input=e2e6a865de093ef4]*/ { PyObject *global; PyObject *module; /* Try to map the old names used in Python 2.x to the new ones used in Python 3.x. We do this only with old pickle protocols and when the user has not disabled the feature. */ if (self->proto < 3 && self->fix_imports) { PyObject *key; PyObject *item; PickleState *st = _Pickle_GetGlobalState(); /* Check if the global (i.e., a function or a class) was renamed or moved to another module. */ key = PyTuple_Pack(2, module_name, global_name); if (key == NULL) return NULL; item = PyDict_GetItemWithError(st->name_mapping_2to3, key); Py_DECREF(key); if (item) { if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.NAME_MAPPING values should be " "2-tuples, not %.200s", Py_TYPE(item)->tp_name); return NULL; } module_name = PyTuple_GET_ITEM(item, 0); global_name = PyTuple_GET_ITEM(item, 1); if (!PyUnicode_Check(module_name) || !PyUnicode_Check(global_name)) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.NAME_MAPPING values should be " "pairs of str, not (%.200s, %.200s)", Py_TYPE(module_name)->tp_name, Py_TYPE(global_name)->tp_name); return NULL; } } else if (PyErr_Occurred()) { return NULL; } else { /* Check if the module was renamed. */ item = PyDict_GetItemWithError(st->import_mapping_2to3, module_name); if (item) { if (!PyUnicode_Check(item)) { PyErr_Format(PyExc_RuntimeError, "_compat_pickle.IMPORT_MAPPING values should be " "strings, not %.200s", Py_TYPE(item)->tp_name); return NULL; } module_name = item; } else if (PyErr_Occurred()) { return NULL; } } } module = PyImport_GetModule(module_name); if (module == NULL) { if (PyErr_Occurred()) return NULL; module = PyImport_Import(module_name); if (module == NULL) return NULL; } global = getattribute(module, global_name, self->proto >= 4); Py_DECREF(module); return global; } /*[clinic input] _pickle.Unpickler.__sizeof__ -> Py_ssize_t Returns size in memory, in bytes. [clinic start generated code]*/ static Py_ssize_t _pickle_Unpickler___sizeof___impl(UnpicklerObject *self) /*[clinic end generated code: output=119d9d03ad4c7651 input=13333471fdeedf5e]*/ { Py_ssize_t res; res = _PyObject_SIZE(Py_TYPE(self)); if (self->memo != NULL) res += self->memo_size * sizeof(PyObject *); if (self->marks != NULL) res += self->marks_size * sizeof(Py_ssize_t); if (self->input_line != NULL) res += strlen(self->input_line) + 1; if (self->encoding != NULL) res += strlen(self->encoding) + 1; if (self->errors != NULL) res += strlen(self->errors) + 1; return res; } static struct PyMethodDef Unpickler_methods[] = { _PICKLE_UNPICKLER_LOAD_METHODDEF _PICKLE_UNPICKLER_FIND_CLASS_METHODDEF _PICKLE_UNPICKLER___SIZEOF___METHODDEF {NULL, NULL} /* sentinel */ }; static void Unpickler_dealloc(UnpicklerObject *self) { PyObject_GC_UnTrack((PyObject *)self); Py_XDECREF(self->readline); Py_XDECREF(self->read); Py_XDECREF(self->peek); Py_XDECREF(self->stack); Py_XDECREF(self->pers_func); if (self->buffer.buf != NULL) { PyBuffer_Release(&self->buffer); self->buffer.buf = NULL; } _Unpickler_MemoCleanup(self); PyMem_Free(self->marks); PyMem_Free(self->input_line); PyMem_Free(self->encoding); PyMem_Free(self->errors); Py_TYPE(self)->tp_free((PyObject *)self); } static int Unpickler_traverse(UnpicklerObject *self, visitproc visit, void *arg) { Py_VISIT(self->readline); Py_VISIT(self->read); Py_VISIT(self->peek); Py_VISIT(self->stack); Py_VISIT(self->pers_func); return 0; } static int Unpickler_clear(UnpicklerObject *self) { Py_CLEAR(self->readline); Py_CLEAR(self->read); Py_CLEAR(self->peek); Py_CLEAR(self->stack); Py_CLEAR(self->pers_func); if (self->buffer.buf != NULL) { PyBuffer_Release(&self->buffer); self->buffer.buf = NULL; } _Unpickler_MemoCleanup(self); PyMem_Free(self->marks); self->marks = NULL; PyMem_Free(self->input_line); self->input_line = NULL; PyMem_Free(self->encoding); self->encoding = NULL; PyMem_Free(self->errors); self->errors = NULL; return 0; } /*[clinic input] _pickle.Unpickler.__init__ file: object * fix_imports: bool = True encoding: str = 'ASCII' errors: str = 'strict' This takes a binary file for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled object's representation are ignored. The argument *file* must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus *file* can be a binary file object opened for reading, an io.BytesIO object, or any other custom object that meets this interface. Optional keyword arguments are *fix_imports*, *encoding* and *errors*, which are used to control compatibility support for pickle stream generated by Python 2. If *fix_imports* is True, pickle will try to map the old Python 2 names to the new names used in Python 3. The *encoding* and *errors* tell pickle how to decode 8-bit string instances pickled by Python 2; these default to 'ASCII' and 'strict', respectively. The *encoding* can be 'bytes' to read these 8-bit string instances as bytes objects. [clinic start generated code]*/ static int _pickle_Unpickler___init___impl(UnpicklerObject *self, PyObject *file, int fix_imports, const char *encoding, const char *errors) /*[clinic end generated code: output=e2c8ce748edc57b0 input=f9b7da04f5f4f335]*/ { _Py_IDENTIFIER(persistent_load); /* In case of multiple __init__() calls, clear previous content. */ if (self->read != NULL) (void)Unpickler_clear(self); if (_Unpickler_SetInputStream(self, file) < 0) return -1; if (_Unpickler_SetInputEncoding(self, encoding, errors) < 0) return -1; self->fix_imports = fix_imports; if (init_method_ref((PyObject *)self, &PyId_persistent_load, &self->pers_func, &self->pers_func_self) < 0) { return -1; } self->stack = (Pdata *)Pdata_New(); if (self->stack == NULL) return -1; self->memo_size = 32; self->memo = _Unpickler_NewMemo(self->memo_size); if (self->memo == NULL) return -1; self->proto = 0; return 0; } /* Define a proxy object for the Unpickler's internal memo object. This is to * avoid breaking code like: * unpickler.memo.clear() * and * unpickler.memo = saved_memo * Is this a good idea? Not really, but we don't want to break code that uses * it. Note that we don't implement the entire mapping API here. This is * intentional, as these should be treated as black-box implementation details. * * We do, however, have to implement pickling/unpickling support because of * real-world code like cvs2svn. */ /*[clinic input] _pickle.UnpicklerMemoProxy.clear Remove all items from memo. [clinic start generated code]*/ static PyObject * _pickle_UnpicklerMemoProxy_clear_impl(UnpicklerMemoProxyObject *self) /*[clinic end generated code: output=d20cd43f4ba1fb1f input=b1df7c52e7afd9bd]*/ { _Unpickler_MemoCleanup(self->unpickler); self->unpickler->memo = _Unpickler_NewMemo(self->unpickler->memo_size); if (self->unpickler->memo == NULL) return NULL; Py_RETURN_NONE; } /*[clinic input] _pickle.UnpicklerMemoProxy.copy Copy the memo to a new object. [clinic start generated code]*/ static PyObject * _pickle_UnpicklerMemoProxy_copy_impl(UnpicklerMemoProxyObject *self) /*[clinic end generated code: output=e12af7e9bc1e4c77 input=97769247ce032c1d]*/ { size_t i; PyObject *new_memo = PyDict_New(); if (new_memo == NULL) return NULL; for (i = 0; i < self->unpickler->memo_size; i++) { int status; PyObject *key, *value; value = self->unpickler->memo[i]; if (value == NULL) continue; key = PyLong_FromSsize_t(i); if (key == NULL) goto error; status = PyDict_SetItem(new_memo, key, value); Py_DECREF(key); if (status < 0) goto error; } return new_memo; error: Py_DECREF(new_memo); return NULL; } /*[clinic input] _pickle.UnpicklerMemoProxy.__reduce__ Implement pickling support. [clinic start generated code]*/ static PyObject * _pickle_UnpicklerMemoProxy___reduce___impl(UnpicklerMemoProxyObject *self) /*[clinic end generated code: output=6da34ac048d94cca input=6920862413407199]*/ { PyObject *reduce_value; PyObject *constructor_args; PyObject *contents = _pickle_UnpicklerMemoProxy_copy_impl(self); if (contents == NULL) return NULL; reduce_value = PyTuple_New(2); if (reduce_value == NULL) { Py_DECREF(contents); return NULL; } constructor_args = PyTuple_New(1); if (constructor_args == NULL) { Py_DECREF(contents); Py_DECREF(reduce_value); return NULL; } PyTuple_SET_ITEM(constructor_args, 0, contents); Py_INCREF((PyObject *)&PyDict_Type); PyTuple_SET_ITEM(reduce_value, 0, (PyObject *)&PyDict_Type); PyTuple_SET_ITEM(reduce_value, 1, constructor_args); return reduce_value; } static PyMethodDef unpicklerproxy_methods[] = { _PICKLE_UNPICKLERMEMOPROXY_CLEAR_METHODDEF _PICKLE_UNPICKLERMEMOPROXY_COPY_METHODDEF _PICKLE_UNPICKLERMEMOPROXY___REDUCE___METHODDEF {NULL, NULL} /* sentinel */ }; static void UnpicklerMemoProxy_dealloc(UnpicklerMemoProxyObject *self) { PyObject_GC_UnTrack(self); Py_XDECREF(self->unpickler); PyObject_GC_Del((PyObject *)self); } static int UnpicklerMemoProxy_traverse(UnpicklerMemoProxyObject *self, visitproc visit, void *arg) { Py_VISIT(self->unpickler); return 0; } static int UnpicklerMemoProxy_clear(UnpicklerMemoProxyObject *self) { Py_CLEAR(self->unpickler); return 0; } static PyTypeObject UnpicklerMemoProxyType = { PyVarObject_HEAD_INIT(NULL, 0) "_pickle.UnpicklerMemoProxy", /*tp_name*/ sizeof(UnpicklerMemoProxyObject), /*tp_basicsize*/ 0, (destructor)UnpicklerMemoProxy_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ PyObject_HashNotImplemented, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, 0, /* tp_doc */ (traverseproc)UnpicklerMemoProxy_traverse, /* tp_traverse */ (inquiry)UnpicklerMemoProxy_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ unpicklerproxy_methods, /* tp_methods */ }; static PyObject * UnpicklerMemoProxy_New(UnpicklerObject *unpickler) { UnpicklerMemoProxyObject *self; self = PyObject_GC_New(UnpicklerMemoProxyObject, &UnpicklerMemoProxyType); if (self == NULL) return NULL; Py_INCREF(unpickler); self->unpickler = unpickler; PyObject_GC_Track(self); return (PyObject *)self; } /*****************************************************************************/ static PyObject * Unpickler_get_memo(UnpicklerObject *self, void *Py_UNUSED(ignored)) { return UnpicklerMemoProxy_New(self); } static int Unpickler_set_memo(UnpicklerObject *self, PyObject *obj, void *Py_UNUSED(ignored)) { PyObject **new_memo; size_t new_memo_size = 0; if (obj == NULL) { PyErr_SetString(PyExc_TypeError, "attribute deletion is not supported"); return -1; } if (Py_TYPE(obj) == &UnpicklerMemoProxyType) { UnpicklerObject *unpickler = ((UnpicklerMemoProxyObject *)obj)->unpickler; new_memo_size = unpickler->memo_size; new_memo = _Unpickler_NewMemo(new_memo_size); if (new_memo == NULL) return -1; for (size_t i = 0; i < new_memo_size; i++) { Py_XINCREF(unpickler->memo[i]); new_memo[i] = unpickler->memo[i]; } } else if (PyDict_Check(obj)) { Py_ssize_t i = 0; PyObject *key, *value; new_memo_size = PyDict_GET_SIZE(obj); new_memo = _Unpickler_NewMemo(new_memo_size); if (new_memo == NULL) return -1; while (PyDict_Next(obj, &i, &key, &value)) { Py_ssize_t idx; if (!PyLong_Check(key)) { PyErr_SetString(PyExc_TypeError, "memo key must be integers"); goto error; } idx = PyLong_AsSsize_t(key); if (idx == -1 && PyErr_Occurred()) goto error; if (idx < 0) { PyErr_SetString(PyExc_ValueError, "memo key must be positive integers."); goto error; } if (_Unpickler_MemoPut(self, idx, value) < 0) goto error; } } else { PyErr_Format(PyExc_TypeError, "'memo' attribute must be an UnpicklerMemoProxy object " "or dict, not %.200s", Py_TYPE(obj)->tp_name); return -1; } _Unpickler_MemoCleanup(self); self->memo_size = new_memo_size; self->memo = new_memo; return 0; error: if (new_memo_size) { for (size_t i = new_memo_size - 1; i != SIZE_MAX; i--) { Py_XDECREF(new_memo[i]); } PyMem_FREE(new_memo); } return -1; } static PyObject * Unpickler_get_persload(UnpicklerObject *self, void *Py_UNUSED(ignored)) { if (self->pers_func == NULL) { PyErr_SetString(PyExc_AttributeError, "persistent_load"); return NULL; } return reconstruct_method(self->pers_func, self->pers_func_self); } static int Unpickler_set_persload(UnpicklerObject *self, PyObject *value, void *Py_UNUSED(ignored)) { if (value == NULL) { PyErr_SetString(PyExc_TypeError, "attribute deletion is not supported"); return -1; } if (!PyCallable_Check(value)) { PyErr_SetString(PyExc_TypeError, "persistent_load must be a callable taking " "one argument"); return -1; } self->pers_func_self = NULL; Py_INCREF(value); Py_XSETREF(self->pers_func, value); return 0; } static PyGetSetDef Unpickler_getsets[] = { {"memo", (getter)Unpickler_get_memo, (setter)Unpickler_set_memo}, {"persistent_load", (getter)Unpickler_get_persload, (setter)Unpickler_set_persload}, {NULL} }; static PyTypeObject Unpickler_Type = { PyVarObject_HEAD_INIT(NULL, 0) "_pickle.Unpickler", /*tp_name*/ sizeof(UnpicklerObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Unpickler_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, _pickle_Unpickler___init____doc__, /*tp_doc*/ (traverseproc)Unpickler_traverse, /*tp_traverse*/ (inquiry)Unpickler_clear, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ Unpickler_methods, /*tp_methods*/ 0, /*tp_members*/ Unpickler_getsets, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ _pickle_Unpickler___init__, /*tp_init*/ PyType_GenericAlloc, /*tp_alloc*/ PyType_GenericNew, /*tp_new*/ PyObject_GC_Del, /*tp_free*/ 0, /*tp_is_gc*/ }; /*[clinic input] _pickle.dump obj: object file: object protocol: object = NULL * fix_imports: bool = True Write a pickled representation of obj to the open file object file. This is equivalent to ``Pickler(file, protocol).dump(obj)``, but may be more efficient. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3 and 4. The default protocol is 4. It was introduced in Python 3.4, it is incompatible with previous versions. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The *file* argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface. If *fix_imports* is True and protocol is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2. [clinic start generated code]*/ static PyObject * _pickle_dump_impl(PyObject *module, PyObject *obj, PyObject *file, PyObject *protocol, int fix_imports) /*[clinic end generated code: output=a4774d5fde7d34de input=93f1408489a87472]*/ { PicklerObject *pickler = _Pickler_New(); if (pickler == NULL) return NULL; if (_Pickler_SetProtocol(pickler, protocol, fix_imports) < 0) goto error; if (_Pickler_SetOutputStream(pickler, file) < 0) goto error; if (dump(pickler, obj) < 0) goto error; if (_Pickler_FlushToFile(pickler) < 0) goto error; Py_DECREF(pickler); Py_RETURN_NONE; error: Py_XDECREF(pickler); return NULL; } /*[clinic input] _pickle.dumps obj: object protocol: object = NULL * fix_imports: bool = True Return the pickled representation of the object as a bytes object. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3 and 4. The default protocol is 4. It was introduced in Python 3.4, it is incompatible with previous versions. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. If *fix_imports* is True and *protocol* is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2. [clinic start generated code]*/ static PyObject * _pickle_dumps_impl(PyObject *module, PyObject *obj, PyObject *protocol, int fix_imports) /*[clinic end generated code: output=d75d5cda456fd261 input=b6efb45a7d19b5ab]*/ { PyObject *result; PicklerObject *pickler = _Pickler_New(); if (pickler == NULL) return NULL; if (_Pickler_SetProtocol(pickler, protocol, fix_imports) < 0) goto error; if (dump(pickler, obj) < 0) goto error; result = _Pickler_GetString(pickler); Py_DECREF(pickler); return result; error: Py_XDECREF(pickler); return NULL; } /*[clinic input] _pickle.load file: object * fix_imports: bool = True encoding: str = 'ASCII' errors: str = 'strict' Read and return an object from the pickle data stored in a file. This is equivalent to ``Unpickler(file).load()``, but may be more efficient. The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled object's representation are ignored. The argument *file* must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus *file* can be a binary file object opened for reading, an io.BytesIO object, or any other custom object that meets this interface. Optional keyword arguments are *fix_imports*, *encoding* and *errors*, which are used to control compatibility support for pickle stream generated by Python 2. If *fix_imports* is True, pickle will try to map the old Python 2 names to the new names used in Python 3. The *encoding* and *errors* tell pickle how to decode 8-bit string instances pickled by Python 2; these default to 'ASCII' and 'strict', respectively. The *encoding* can be 'bytes' to read these 8-bit string instances as bytes objects. [clinic start generated code]*/ static PyObject * _pickle_load_impl(PyObject *module, PyObject *file, int fix_imports, const char *encoding, const char *errors) /*[clinic end generated code: output=69e298160285199e input=01b44dd3fc07afa7]*/ { PyObject *result; UnpicklerObject *unpickler = _Unpickler_New(); if (unpickler == NULL) return NULL; if (_Unpickler_SetInputStream(unpickler, file) < 0) goto error; if (_Unpickler_SetInputEncoding(unpickler, encoding, errors) < 0) goto error; unpickler->fix_imports = fix_imports; result = load(unpickler); Py_DECREF(unpickler); return result; error: Py_XDECREF(unpickler); return NULL; } /*[clinic input] _pickle.loads data: object * fix_imports: bool = True encoding: str = 'ASCII' errors: str = 'strict' Read and return an object from the given pickle data. The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled object's representation are ignored. Optional keyword arguments are *fix_imports*, *encoding* and *errors*, which are used to control compatibility support for pickle stream generated by Python 2. If *fix_imports* is True, pickle will try to map the old Python 2 names to the new names used in Python 3. The *encoding* and *errors* tell pickle how to decode 8-bit string instances pickled by Python 2; these default to 'ASCII' and 'strict', respectively. The *encoding* can be 'bytes' to read these 8-bit string instances as bytes objects. [clinic start generated code]*/ static PyObject * _pickle_loads_impl(PyObject *module, PyObject *data, int fix_imports, const char *encoding, const char *errors) /*[clinic end generated code: output=1e7cb2343f2c440f input=70605948a719feb9]*/ { PyObject *result; UnpicklerObject *unpickler = _Unpickler_New(); if (unpickler == NULL) return NULL; if (_Unpickler_SetStringInput(unpickler, data) < 0) goto error; if (_Unpickler_SetInputEncoding(unpickler, encoding, errors) < 0) goto error; unpickler->fix_imports = fix_imports; result = load(unpickler); Py_DECREF(unpickler); return result; error: Py_XDECREF(unpickler); return NULL; } static struct PyMethodDef pickle_methods[] = { _PICKLE_DUMP_METHODDEF _PICKLE_DUMPS_METHODDEF _PICKLE_LOAD_METHODDEF _PICKLE_LOADS_METHODDEF {NULL, NULL} /* sentinel */ }; static int pickle_clear(PyObject *m) { _Pickle_ClearState(_Pickle_GetState(m)); return 0; } static void pickle_free(PyObject *m) { _Pickle_ClearState(_Pickle_GetState(m)); } static int pickle_traverse(PyObject *m, visitproc visit, void *arg) { PickleState *st = _Pickle_GetState(m); Py_VISIT(st->PickleError); Py_VISIT(st->PicklingError); Py_VISIT(st->UnpicklingError); Py_VISIT(st->dispatch_table); Py_VISIT(st->extension_registry); Py_VISIT(st->extension_cache); Py_VISIT(st->inverted_registry); Py_VISIT(st->name_mapping_2to3); Py_VISIT(st->import_mapping_2to3); Py_VISIT(st->name_mapping_3to2); Py_VISIT(st->import_mapping_3to2); Py_VISIT(st->codecs_encode); Py_VISIT(st->getattr); return 0; } static struct PyModuleDef _picklemodule = { PyModuleDef_HEAD_INIT, "_pickle", /* m_name */ pickle_module_doc, /* m_doc */ sizeof(PickleState), /* m_size */ pickle_methods, /* m_methods */ NULL, /* m_reload */ pickle_traverse, /* m_traverse */ pickle_clear, /* m_clear */ (freefunc)pickle_free /* m_free */ }; PyMODINIT_FUNC PyInit__pickle(void) { PyObject *m; PickleState *st; m = PyState_FindModule(&_picklemodule); if (m) { Py_INCREF(m); return m; } if (PyType_Ready(&Unpickler_Type) < 0) return NULL; if (PyType_Ready(&Pickler_Type) < 0) return NULL; if (PyType_Ready(&Pdata_Type) < 0) return NULL; if (PyType_Ready(&PicklerMemoProxyType) < 0) return NULL; if (PyType_Ready(&UnpicklerMemoProxyType) < 0) return NULL; /* Create the module and add the functions. */ m = PyModule_Create(&_picklemodule); if (m == NULL) return NULL; Py_INCREF(&Pickler_Type); if (PyModule_AddObject(m, "Pickler", (PyObject *)&Pickler_Type) < 0) return NULL; Py_INCREF(&Unpickler_Type); if (PyModule_AddObject(m, "Unpickler", (PyObject *)&Unpickler_Type) < 0) return NULL; st = _Pickle_GetState(m); /* Initialize the exceptions. */ st->PickleError = PyErr_NewException("_pickle.PickleError", NULL, NULL); if (st->PickleError == NULL) return NULL; st->PicklingError = \ PyErr_NewException("_pickle.PicklingError", st->PickleError, NULL); if (st->PicklingError == NULL) return NULL; st->UnpicklingError = \ PyErr_NewException("_pickle.UnpicklingError", st->PickleError, NULL); if (st->UnpicklingError == NULL) return NULL; Py_INCREF(st->PickleError); if (PyModule_AddObject(m, "PickleError", st->PickleError) < 0) return NULL; Py_INCREF(st->PicklingError); if (PyModule_AddObject(m, "PicklingError", st->PicklingError) < 0) return NULL; Py_INCREF(st->UnpicklingError); if (PyModule_AddObject(m, "UnpicklingError", st->UnpicklingError) < 0) return NULL; if (_Pickle_InitState(st) < 0) return NULL; return m; }
290977.c
unsigned char icon_folder[1024] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x2, 0x3, 0x3, 0x2, 0x2, 0x2, 0x2, 0x1, 0x0, 0x1, 0x2, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x1, 0x2, 0x1, 0x1, 0x2, 0x2, 0x1, 0x2, 0x2, 0x2, 0x1, 0x2, 0x3, 0x3, 0x2, 0x1, 0x2, 0x2, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x24, 0x4e, 0x27, 0x25, 0x44, 0x75, 0x3b, 0x23, 0x42, 0x69, 0x35, 0x0, 0xb, 0x28, 0x14, 0x0, 0x17, 0x4b, 0x26, 0x0, 0x29, 0x67, 0x34, 0x7, 0x2a, 0x5f, 0x30, 0x1a, 0x35, 0x66, 0x33, 0x29, 0x46, 0x71, 0x39, 0x22, 0x44, 0x69, 0x35, 0x0, 0xa, 0x17, 0xc, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x38, 0x76, 0xb7, 0x5c, 0x9d, 0xd7, 0xff, 0x80, 0x96, 0xcb, 0xff, 0x80, 0x61, 0x93, 0xcc, 0x66, 0x6b, 0xa0, 0xdd, 0x6f, 0x7f, 0xb8, 0xf9, 0x7d, 0x87, 0xc0, 0xf7, 0x7c, 0x96, 0xca, 0xfd, 0x7f, 0x9f, 0xd8, 0xff, 0x80, 0x6e, 0xb4, 0xef, 0x78, 0x1, 0x1a, 0x36, 0x1b, 0x1, 0x6, 0xe, 0x7, 0x0, 0x9, 0x17, 0xc, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4b, 0x77, 0xa7, 0x54, 0xd3, 0xe7, 0xf8, 0x7c, 0xc8, 0xdd, 0xf8, 0x7c, 0xcb, 0xe9, 0xff, 0x80, 0xc8, 0xe5, 0xff, 0x80, 0xc0, 0xdf, 0xfc, 0x7e, 0xb7, 0xdb, 0xfc, 0x7e, 0xa7, 0xd1, 0xfa, 0x7d, 0x99, 0xce, 0xfb, 0x7e, 0x65, 0xaf, 0xe9, 0x75, 0x8, 0x1f, 0x3f, 0x20, 0x0, 0x14, 0x50, 0x28, 0x0, 0x18, 0x40, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2d, 0x50, 0x83, 0x42, 0xc5, 0xde, 0xfd, 0x7f, 0xc0, 0xd9, 0xf8, 0x7c, 0xb9, 0xd9, 0xf9, 0x7d, 0xb2, 0xd6, 0xfc, 0x7e, 0xa3, 0xcf, 0xfc, 0x7e, 0x96, 0xc9, 0xfc, 0x7e, 0x8b, 0xc1, 0xfc, 0x7e, 0x7c, 0xbd, 0xfe, 0x7f, 0x5f, 0xab, 0xef, 0x78, 0x20, 0x65, 0xb4, 0x5a, 0x16, 0x63, 0xca, 0x65, 0x6, 0x1c, 0x3c, 0x1e, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x15, 0x3c, 0x7b, 0x3e, 0xaa, 0xce, 0xf9, 0x7d, 0xbc, 0xda, 0xfc, 0x7e, 0x90, 0xc5, 0xfc, 0x7e, 0x6d, 0xb5, 0xfd, 0x7f, 0x68, 0xb2, 0xfc, 0x7e, 0x6b, 0xb4, 0xfd, 0x7f, 0x6e, 0xb4, 0xfd, 0x7f, 0x6a, 0xb4, 0xfd, 0x7f, 0x58, 0xa8, 0xf5, 0x7b, 0x2c, 0x84, 0xdc, 0x6e, 0x1b, 0x65, 0xb4, 0x5a, 0x5, 0x10, 0x1f, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xd, 0x23, 0x55, 0x2b, 0x99, 0xbc, 0xeb, 0x76, 0x7d, 0xb3, 0xfd, 0x7f, 0x20, 0x84, 0xf8, 0x7c, 0x2f, 0x96, 0xfc, 0x7e, 0x41, 0x9e, 0xfa, 0x7d, 0x4e, 0xa4, 0xfa, 0x7d, 0x53, 0xa5, 0xf9, 0x7d, 0x52, 0xa8, 0xf9, 0x7d, 0x42, 0x96, 0xed, 0x77, 0x23, 0x6c, 0xc8, 0x64, 0xb, 0x38, 0x6d, 0x37, 0x0, 0x2, 0x6, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, 0x23, 0x5d, 0x2f, 0x6b, 0x99, 0xe4, 0x72, 0x28, 0x74, 0xf6, 0x7b, 0x17, 0x71, 0xf0, 0x78, 0x30, 0x8e, 0xf9, 0x7d, 0x32, 0x97, 0xfb, 0x7e, 0x3c, 0x9f, 0xfe, 0x7f, 0x3f, 0xa4, 0xff, 0x80, 0x37, 0x9d, 0xff, 0x80, 0x57, 0xa4, 0xfa, 0x7d, 0x4e, 0x94, 0xe9, 0x75, 0x1, 0x1e, 0x46, 0x23, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x2, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0xb, 0x1e, 0xf, 0x2c, 0x58, 0xaa, 0x55, 0x20, 0x71, 0xff, 0x80, 0x1a, 0x6e, 0xff, 0x80, 0x24, 0x7f, 0xff, 0x80, 0x29, 0x85, 0xfb, 0x7e, 0x28, 0x82, 0xe8, 0x74, 0x27, 0x7e, 0xd8, 0x6c, 0x1c, 0x63, 0xbe, 0x5f, 0x3b, 0x6b, 0xac, 0x56, 0x2a, 0x53, 0x85, 0x43, 0x0, 0x4, 0x13, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0xe, 0x26, 0x13, 0x11, 0x3e, 0x95, 0x4b, 0xc, 0x36, 0x86, 0x43, 0xb, 0x2e, 0x69, 0x35, 0xb, 0x25, 0x52, 0x29, 0x8, 0x1b, 0x3c, 0x1e, 0x5, 0x13, 0x2b, 0x16, 0x1, 0x8, 0x18, 0xc, 0x0, 0x0, 0x8, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x2, 0x0, 0x0, 0x1, 0x2, 0x2, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x1, 0x2, 0x1, 0x0, 0x1, 0x3, 0x2, 0x0, 0x1, 0x3, 0x2, 0x0, 0x1, 0x3, 0x2, 0x0, 0x0, 0x2, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x1, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, }; unsigned char icon_warning[1024] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x0, 0x25, 0x2f, 0x31, 0x13, 0x0, 0x1, 0x2, 0x0, 0x3, 0x0, 0x0, 0x2, 0x1, 0x1, 0x1, 0x1, 0x3, 0x1, 0x1, 0x2, 0x0, 0x0, 0x0, 0x0, 0x25, 0x30, 0x30, 0x13, 0x2, 0x6, 0x6, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0xc, 0xd, 0x3, 0x5d, 0x5c, 0x5a, 0x2f, 0xdb, 0xa1, 0x8e, 0x6e, 0x5a, 0x40, 0x3c, 0x2d, 0x0, 0x3, 0x5, 0x0, 0x7, 0x4, 0x3, 0x4, 0x0, 0x0, 0x0, 0x0, 0x47, 0x42, 0x41, 0x24, 0xdb, 0x8e, 0x86, 0x6e, 0x6b, 0x64, 0x61, 0x36, 0x6, 0xa, 0xb, 0x3, 0x2, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x42, 0x50, 0x4f, 0x21, 0xfc, 0x9c, 0x8d, 0x7e, 0xf4, 0x19, 0xd, 0x7a, 0xef, 0x62, 0x47, 0x78, 0x57, 0x4a, 0x48, 0x2c, 0x0, 0x0, 0x0, 0x0, 0x48, 0x47, 0x47, 0x24, 0xd9, 0x63, 0x57, 0x6d, 0xd8, 0x10, 0xc, 0x6c, 0xe4, 0x73, 0x69, 0x72, 0x49, 0x51, 0x51, 0x25, 0x0, 0x0, 0x0, 0x0, 0x3, 0x3, 0x3, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x19, 0x1b, 0x1b, 0xd, 0x9b, 0x60, 0x56, 0x4e, 0xfd, 0x3b, 0x2c, 0x7f, 0xec, 0x13, 0x3, 0x76, 0xdc, 0x52, 0x40, 0x6e, 0x87, 0x75, 0x72, 0x44, 0xd0, 0x5c, 0x4e, 0x68, 0xd2, 0x8, 0x4, 0x69, 0xcf, 0x1f, 0x18, 0x68, 0x90, 0x4d, 0x48, 0x48, 0x1b, 0x1c, 0x1c, 0xe, 0x2, 0x0, 0x0, 0x1, 0x1, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x10, 0x11, 0x2, 0x99, 0x68, 0x5c, 0x4d, 0xee, 0x35, 0x24, 0x77, 0xd6, 0x11, 0x1, 0x6b, 0xe6, 0x41, 0x29, 0x73, 0xce, 0x11, 0x2, 0x67, 0xce, 0x1a, 0x11, 0x67, 0x95, 0x58, 0x54, 0x4b, 0x8, 0xf, 0xf, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x4, 0x4, 0x2, 0x0, 0x0, 0x0, 0x0, 0x2, 0x14, 0x17, 0x1, 0xa4, 0x73, 0x69, 0x52, 0xe4, 0x2e, 0x1e, 0x72, 0xbd, 0x5, 0x0, 0x5f, 0xce, 0x1a, 0x8, 0x67, 0xac, 0x6d, 0x68, 0x56, 0x0, 0x9, 0x9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x1, 0x0, 0x1, 0x2, 0x0, 0x44, 0x43, 0x42, 0x22, 0xcb, 0x5f, 0x55, 0x66, 0xce, 0x12, 0x3, 0x67, 0xc9, 0x12, 0x8, 0x65, 0xbf, 0x9, 0x0, 0x60, 0xbc, 0x47, 0x43, 0x5e, 0x48, 0x40, 0x40, 0x24, 0x0, 0x5, 0x5, 0x0, 0x1, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x4, 0x4, 0x1, 0x40, 0x3a, 0x39, 0x20, 0xdd, 0x6b, 0x5e, 0x6f, 0xd3, 0x4, 0x0, 0x6a, 0xc9, 0x1e, 0x16, 0x65, 0xbb, 0x62, 0x58, 0x5e, 0xc1, 0x25, 0x22, 0x61, 0xb2, 0x0, 0x0, 0x59, 0xbf, 0x4a, 0x48, 0x60, 0x46, 0x3d, 0x3c, 0x23, 0x1, 0x2, 0x2, 0x1, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3e, 0x49, 0x48, 0x1f, 0xe4, 0x82, 0x7a, 0x72, 0xc6, 0x0, 0x0, 0x63, 0xd5, 0x29, 0x1e, 0x6b, 0x8c, 0x4d, 0x49, 0x46, 0x20, 0x33, 0x35, 0x10, 0x82, 0x57, 0x55, 0x41, 0xbd, 0x25, 0x25, 0x5f, 0x99, 0x0, 0x0, 0x4d, 0xbd, 0x58, 0x56, 0x5f, 0x3f, 0x46, 0x46, 0x20, 0x0, 0x0, 0x0, 0x0, 0x3, 0x2, 0x2, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x26, 0x2b, 0x2a, 0x13, 0xa8, 0x7c, 0x79, 0x54, 0xed, 0x5f, 0x5c, 0x77, 0x8e, 0x4a, 0x45, 0x47, 0xf, 0x15, 0x16, 0x8, 0x0, 0x0, 0x0, 0x0, 0xc, 0x15, 0x15, 0x6, 0x7c, 0x53, 0x53, 0x3e, 0xc7, 0x54, 0x53, 0x64, 0x98, 0x6a, 0x69, 0x4c, 0x27, 0x2a, 0x2a, 0x14, 0x2, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x18, 0x22, 0x22, 0xc, 0x6a, 0x63, 0x61, 0x35, 0xb, 0xe, 0xe, 0x6, 0x0, 0x0, 0x0, 0x0, 0x4, 0x3, 0x3, 0x2, 0x0, 0x0, 0x0, 0x0, 0xc, 0x11, 0x11, 0x6, 0x63, 0x5b, 0x5b, 0x32, 0x19, 0x22, 0x22, 0xd, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x4, 0x0, 0x0, 0x2, 0x2, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x1, 0x1, 0x1, 0x3, 0x0, 0x0, 0x2, 0x2, 0x2, 0x2, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, };
517178.c
/* * Copyright (C) 2002 Sistina Software (UK) Limited. * Copyright (C) 2006 Red Hat GmbH * * This file is released under the GPL. * * Kcopyd provides a simple interface for copying an area of one * block-device to one or more other block-devices, with an asynchronous * completion notification. */ #include <linux/types.h> #include <linux/atomic.h> #include <linux/blkdev.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/list.h> #include <linux/mempool.h> #include <linux/module.h> #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/workqueue.h> #include <linux/mutex.h> #include <linux/delay.h> #include <linux/device-mapper.h> #include <linux/dm-kcopyd.h> #include "dm.h" #define SUB_JOB_SIZE 128 #define SPLIT_COUNT 8 #define MIN_JOBS 8 #define RESERVE_PAGES (DIV_ROUND_UP(SUB_JOB_SIZE << SECTOR_SHIFT, PAGE_SIZE)) /*----------------------------------------------------------------- * Each kcopyd client has its own little pool of preallocated * pages for kcopyd io. *---------------------------------------------------------------*/ struct dm_kcopyd_client { struct page_list *pages; unsigned nr_reserved_pages; unsigned nr_free_pages; struct dm_io_client *io_client; wait_queue_head_t destroyq; atomic_t nr_jobs; mempool_t *job_pool; struct workqueue_struct *kcopyd_wq; struct work_struct kcopyd_work; struct dm_kcopyd_throttle *throttle; /* * We maintain three lists of jobs: * * i) jobs waiting for pages * ii) jobs that have pages, and are waiting for the io to be issued. * iii) jobs that have completed. * * All three of these are protected by job_lock. */ spinlock_t job_lock; struct list_head complete_jobs; struct list_head io_jobs; struct list_head pages_jobs; }; static struct page_list zero_page_list; static DEFINE_SPINLOCK(throttle_spinlock); /* * IO/IDLE accounting slowly decays after (1 << ACCOUNT_INTERVAL_SHIFT) period. * When total_period >= (1 << ACCOUNT_INTERVAL_SHIFT) the counters are divided * by 2. */ #define ACCOUNT_INTERVAL_SHIFT SHIFT_HZ /* * Sleep this number of milliseconds. * * The value was decided experimentally. * Smaller values seem to cause an increased copy rate above the limit. * The reason for this is unknown but possibly due to jiffies rounding errors * or read/write cache inside the disk. */ #define SLEEP_MSEC 100 /* * Maximum number of sleep events. There is a theoretical livelock if more * kcopyd clients do work simultaneously which this limit avoids. */ #define MAX_SLEEPS 10 static void io_job_start(struct dm_kcopyd_throttle *t) { unsigned throttle, now, difference; int slept = 0, skew; if (unlikely(!t)) return; try_again: spin_lock_irq(&throttle_spinlock); throttle = ACCESS_ONCE(t->throttle); if (likely(throttle >= 100)) goto skip_limit; now = jiffies; difference = now - t->last_jiffies; t->last_jiffies = now; if (t->num_io_jobs) t->io_period += difference; t->total_period += difference; /* * Maintain sane values if we got a temporary overflow. */ if (unlikely(t->io_period > t->total_period)) t->io_period = t->total_period; if (unlikely(t->total_period >= (1 << ACCOUNT_INTERVAL_SHIFT))) { int shift = fls(t->total_period >> ACCOUNT_INTERVAL_SHIFT); t->total_period >>= shift; t->io_period >>= shift; } skew = t->io_period - throttle * t->total_period / 100; if (unlikely(skew > 0) && slept < MAX_SLEEPS) { slept++; spin_unlock_irq(&throttle_spinlock); msleep(SLEEP_MSEC); goto try_again; } skip_limit: t->num_io_jobs++; spin_unlock_irq(&throttle_spinlock); } static void io_job_finish(struct dm_kcopyd_throttle *t) { unsigned long flags; if (unlikely(!t)) return; spin_lock_irqsave(&throttle_spinlock, flags); t->num_io_jobs--; if (likely(ACCESS_ONCE(t->throttle) >= 100)) goto skip_limit; if (!t->num_io_jobs) { unsigned now, difference; now = jiffies; difference = now - t->last_jiffies; t->last_jiffies = now; t->io_period += difference; t->total_period += difference; /* * Maintain sane values if we got a temporary overflow. */ if (unlikely(t->io_period > t->total_period)) t->io_period = t->total_period; } skip_limit: spin_unlock_irqrestore(&throttle_spinlock, flags); } static void wake(struct dm_kcopyd_client *kc) { queue_work(kc->kcopyd_wq, &kc->kcopyd_work); } /* * Obtain one page for the use of kcopyd. */ static struct page_list *alloc_pl(gfp_t gfp) { struct page_list *pl; pl = kmalloc(sizeof(*pl), gfp); if (!pl) return NULL; pl->page = alloc_page(gfp); if (!pl->page) { kfree(pl); return NULL; } return pl; } static void free_pl(struct page_list *pl) { __free_page(pl->page); kfree(pl); } /* * Add the provided pages to a client's free page list, releasing * back to the system any beyond the reserved_pages limit. */ static void kcopyd_put_pages(struct dm_kcopyd_client *kc, struct page_list *pl) { struct page_list *next; do { next = pl->next; if (kc->nr_free_pages >= kc->nr_reserved_pages) free_pl(pl); else { pl->next = kc->pages; kc->pages = pl; kc->nr_free_pages++; } pl = next; } while (pl); } static int kcopyd_get_pages(struct dm_kcopyd_client *kc, unsigned int nr, struct page_list **pages) { struct page_list *pl; *pages = NULL; do { pl = alloc_pl(__GFP_NOWARN | __GFP_NORETRY); if (unlikely(!pl)) { /* Use reserved pages */ pl = kc->pages; if (unlikely(!pl)) goto out_of_memory; kc->pages = pl->next; kc->nr_free_pages--; } pl->next = *pages; *pages = pl; } while (--nr); return 0; out_of_memory: if (*pages) kcopyd_put_pages(kc, *pages); return -ENOMEM; } /* * These three functions resize the page pool. */ static void drop_pages(struct page_list *pl) { struct page_list *next; while (pl) { next = pl->next; free_pl(pl); pl = next; } } /* * Allocate and reserve nr_pages for the use of a specific client. */ static int client_reserve_pages(struct dm_kcopyd_client *kc, unsigned nr_pages) { unsigned i; struct page_list *pl = NULL, *next; for (i = 0; i < nr_pages; i++) { next = alloc_pl(GFP_KERNEL); if (!next) { if (pl) drop_pages(pl); return -ENOMEM; } next->next = pl; pl = next; } kc->nr_reserved_pages += nr_pages; kcopyd_put_pages(kc, pl); return 0; } static void client_free_pages(struct dm_kcopyd_client *kc) { BUG_ON(kc->nr_free_pages != kc->nr_reserved_pages); drop_pages(kc->pages); kc->pages = NULL; kc->nr_free_pages = kc->nr_reserved_pages = 0; } /*----------------------------------------------------------------- * kcopyd_jobs need to be allocated by the *clients* of kcopyd, * for this reason we use a mempool to prevent the client from * ever having to do io (which could cause a deadlock). *---------------------------------------------------------------*/ struct kcopyd_job { struct dm_kcopyd_client *kc; struct list_head list; unsigned long flags; /* * Error state of the job. */ int read_err; unsigned long write_err; /* * Either READ or WRITE */ int rw; struct dm_io_region source; /* * The destinations for the transfer. */ unsigned int num_dests; struct dm_io_region dests[DM_KCOPYD_MAX_REGIONS]; struct page_list *pages; /* * Set this to ensure you are notified when the job has * completed. 'context' is for callback to use. */ dm_kcopyd_notify_fn fn; void *context; /* * These fields are only used if the job has been split * into more manageable parts. */ struct mutex lock; atomic_t sub_jobs; sector_t progress; struct kcopyd_job *master_job; }; static struct kmem_cache *_job_cache; int __init dm_kcopyd_init(void) { _job_cache = kmem_cache_create("kcopyd_job", sizeof(struct kcopyd_job) * (SPLIT_COUNT + 1), __alignof__(struct kcopyd_job), 0, NULL); if (!_job_cache) return -ENOMEM; zero_page_list.next = &zero_page_list; zero_page_list.page = ZERO_PAGE(0); return 0; } void dm_kcopyd_exit(void) { kmem_cache_destroy(_job_cache); _job_cache = NULL; } /* * Functions to push and pop a job onto the head of a given job * list. */ static struct kcopyd_job *pop(struct list_head *jobs, struct dm_kcopyd_client *kc) { struct kcopyd_job *job = NULL; unsigned long flags; spin_lock_irqsave(&kc->job_lock, flags); if (!list_empty(jobs)) { job = list_entry(jobs->next, struct kcopyd_job, list); list_del(&job->list); } spin_unlock_irqrestore(&kc->job_lock, flags); return job; } static void push(struct list_head *jobs, struct kcopyd_job *job) { unsigned long flags; struct dm_kcopyd_client *kc = job->kc; spin_lock_irqsave(&kc->job_lock, flags); list_add_tail(&job->list, jobs); spin_unlock_irqrestore(&kc->job_lock, flags); } static void push_head(struct list_head *jobs, struct kcopyd_job *job) { unsigned long flags; struct dm_kcopyd_client *kc = job->kc; spin_lock_irqsave(&kc->job_lock, flags); list_add(&job->list, jobs); spin_unlock_irqrestore(&kc->job_lock, flags); } /* * These three functions process 1 item from the corresponding * job list. * * They return: * < 0: error * 0: success * > 0: can't process yet. */ static int run_complete_job(struct kcopyd_job *job) { void *context = job->context; int read_err = job->read_err; unsigned long write_err = job->write_err; dm_kcopyd_notify_fn fn = job->fn; struct dm_kcopyd_client *kc = job->kc; if (job->pages && job->pages != &zero_page_list) kcopyd_put_pages(kc, job->pages); /* * If this is the master job, the sub jobs have already * completed so we can free everything. */ if (job->master_job == job) mempool_free(job, kc->job_pool); fn(read_err, write_err, context); if (atomic_dec_and_test(&kc->nr_jobs)) wake_up(&kc->destroyq); return 0; } static void complete_io(unsigned long error, void *context) { struct kcopyd_job *job = (struct kcopyd_job *) context; struct dm_kcopyd_client *kc = job->kc; io_job_finish(kc->throttle); if (error) { if (job->rw & WRITE) job->write_err |= error; else job->read_err = 1; if (!test_bit(DM_KCOPYD_IGNORE_ERROR, &job->flags)) { push(&kc->complete_jobs, job); wake(kc); return; } } if (job->rw & WRITE) push(&kc->complete_jobs, job); else { job->rw = WRITE; push(&kc->io_jobs, job); } wake(kc); } /* * Request io on as many buffer heads as we can currently get for * a particular job. */ static int run_io_job(struct kcopyd_job *job) { int r; struct dm_io_request io_req = { .bi_rw = job->rw, .mem.type = DM_IO_PAGE_LIST, .mem.ptr.pl = job->pages, .mem.offset = 0, .notify.fn = complete_io, .notify.context = job, .client = job->kc->io_client, }; io_job_start(job->kc->throttle); if (job->rw == READ) r = dm_io(&io_req, 1, &job->source, NULL); else r = dm_io(&io_req, job->num_dests, job->dests, NULL); return r; } static int run_pages_job(struct kcopyd_job *job) { int r; unsigned nr_pages = dm_div_up(job->dests[0].count, PAGE_SIZE >> 9); r = kcopyd_get_pages(job->kc, nr_pages, &job->pages); if (!r) { /* this job is ready for io */ push(&job->kc->io_jobs, job); return 0; } if (r == -ENOMEM) /* can't complete now */ return 1; return r; } /* * Run through a list for as long as possible. Returns the count * of successful jobs. */ static int process_jobs(struct list_head *jobs, struct dm_kcopyd_client *kc, int (*fn) (struct kcopyd_job *)) { struct kcopyd_job *job; int r, count = 0; while ((job = pop(jobs, kc))) { r = fn(job); if (r < 0) { /* error this rogue job */ if (job->rw & WRITE) job->write_err = (unsigned long) -1L; else job->read_err = 1; push(&kc->complete_jobs, job); break; } if (r > 0) { /* * We couldn't service this job ATM, so * push this job back onto the list. */ push_head(jobs, job); break; } count++; } return count; } /* * kcopyd does this every time it's woken up. */ static void do_work(struct work_struct *work) { struct dm_kcopyd_client *kc = container_of(work, struct dm_kcopyd_client, kcopyd_work); struct blk_plug plug; /* * The order that these are called is *very* important. * complete jobs can free some pages for pages jobs. * Pages jobs when successful will jump onto the io jobs * list. io jobs call wake when they complete and it all * starts again. */ blk_start_plug(&plug); process_jobs(&kc->complete_jobs, kc, run_complete_job); process_jobs(&kc->pages_jobs, kc, run_pages_job); process_jobs(&kc->io_jobs, kc, run_io_job); blk_finish_plug(&plug); } /* * If we are copying a small region we just dispatch a single job * to do the copy, otherwise the io has to be split up into many * jobs. */ static void dispatch_job(struct kcopyd_job *job) { struct dm_kcopyd_client *kc = job->kc; atomic_inc(&kc->nr_jobs); if (unlikely(!job->source.count)) push(&kc->complete_jobs, job); else if (job->pages == &zero_page_list) push(&kc->io_jobs, job); else push(&kc->pages_jobs, job); wake(kc); } static void segment_complete(int read_err, unsigned long write_err, void *context) { /* FIXME: tidy this function */ sector_t progress = 0; sector_t count = 0; struct kcopyd_job *sub_job = (struct kcopyd_job *) context; struct kcopyd_job *job = sub_job->master_job; struct dm_kcopyd_client *kc = job->kc; mutex_lock(&job->lock); /* update the error */ if (read_err) job->read_err = 1; if (write_err) job->write_err |= write_err; /* * Only dispatch more work if there hasn't been an error. */ if ((!job->read_err && !job->write_err) || test_bit(DM_KCOPYD_IGNORE_ERROR, &job->flags)) { /* get the next chunk of work */ progress = job->progress; count = job->source.count - progress; if (count) { if (count > SUB_JOB_SIZE) count = SUB_JOB_SIZE; job->progress += count; } } mutex_unlock(&job->lock); if (count) { int i; *sub_job = *job; sub_job->source.sector += progress; sub_job->source.count = count; for (i = 0; i < job->num_dests; i++) { sub_job->dests[i].sector += progress; sub_job->dests[i].count = count; } sub_job->fn = segment_complete; sub_job->context = sub_job; dispatch_job(sub_job); } else if (atomic_dec_and_test(&job->sub_jobs)) { /* * Queue the completion callback to the kcopyd thread. * * Some callers assume that all the completions are called * from a single thread and don't race with each other. * * We must not call the callback directly here because this * code may not be executing in the thread. */ push(&kc->complete_jobs, job); wake(kc); } } /* * Create some sub jobs to share the work between them. */ static void split_job(struct kcopyd_job *master_job) { int i; atomic_inc(&master_job->kc->nr_jobs); atomic_set(&master_job->sub_jobs, SPLIT_COUNT); for (i = 0; i < SPLIT_COUNT; i++) { master_job[i + 1].master_job = master_job; segment_complete(0, 0u, &master_job[i + 1]); } } int dm_kcopyd_copy(struct dm_kcopyd_client *kc, struct dm_io_region *from, unsigned int num_dests, struct dm_io_region *dests, unsigned int flags, dm_kcopyd_notify_fn fn, void *context) { struct kcopyd_job *job; int i; /* * Allocate an array of jobs consisting of one master job * followed by SPLIT_COUNT sub jobs. */ job = mempool_alloc(kc->job_pool, GFP_NOIO); /* * set up for the read. */ job->kc = kc; job->flags = flags; job->read_err = 0; job->write_err = 0; job->num_dests = num_dests; memcpy(&job->dests, dests, sizeof(*dests) * num_dests); if (from) { job->source = *from; job->pages = NULL; job->rw = READ; } else { memset(&job->source, 0, sizeof job->source); job->source.count = job->dests[0].count; job->pages = &zero_page_list; /* * Use WRITE SAME to optimize zeroing if all dests support it. */ job->rw = WRITE | REQ_WRITE_SAME; for (i = 0; i < job->num_dests; i++) if (!bdev_write_same(job->dests[i].bdev)) { job->rw = WRITE; break; } } job->fn = fn; job->context = context; job->master_job = job; if (job->source.count <= SUB_JOB_SIZE) dispatch_job(job); else { mutex_init(&job->lock); job->progress = 0; split_job(job); } return 0; } EXPORT_SYMBOL(dm_kcopyd_copy); int dm_kcopyd_zero(struct dm_kcopyd_client *kc, unsigned num_dests, struct dm_io_region *dests, unsigned flags, dm_kcopyd_notify_fn fn, void *context) { return dm_kcopyd_copy(kc, NULL, num_dests, dests, flags, fn, context); } EXPORT_SYMBOL(dm_kcopyd_zero); void *dm_kcopyd_prepare_callback(struct dm_kcopyd_client *kc, dm_kcopyd_notify_fn fn, void *context) { struct kcopyd_job *job; job = mempool_alloc(kc->job_pool, GFP_NOIO); memset(job, 0, sizeof(struct kcopyd_job)); job->kc = kc; job->fn = fn; job->context = context; job->master_job = job; atomic_inc(&kc->nr_jobs); return job; } EXPORT_SYMBOL(dm_kcopyd_prepare_callback); void dm_kcopyd_do_callback(void *j, int read_err, unsigned long write_err) { struct kcopyd_job *job = j; struct dm_kcopyd_client *kc = job->kc; job->read_err = read_err; job->write_err = write_err; push(&kc->complete_jobs, job); wake(kc); } EXPORT_SYMBOL(dm_kcopyd_do_callback); /* * Cancels a kcopyd job, eg. someone might be deactivating a * mirror. */ #if 0 int kcopyd_cancel(struct kcopyd_job *job, int block) { /* FIXME: finish */ return -1; } #endif /* 0 */ /*----------------------------------------------------------------- * Client setup *---------------------------------------------------------------*/ struct dm_kcopyd_client *dm_kcopyd_client_create(struct dm_kcopyd_throttle *throttle) { int r = -ENOMEM; struct dm_kcopyd_client *kc; kc = kmalloc(sizeof(*kc), GFP_KERNEL); if (!kc) return ERR_PTR(-ENOMEM); spin_lock_init(&kc->job_lock); INIT_LIST_HEAD(&kc->complete_jobs); INIT_LIST_HEAD(&kc->io_jobs); INIT_LIST_HEAD(&kc->pages_jobs); kc->throttle = throttle; kc->job_pool = mempool_create_slab_pool(MIN_JOBS, _job_cache); if (!kc->job_pool) goto bad_slab; INIT_WORK(&kc->kcopyd_work, do_work); kc->kcopyd_wq = alloc_workqueue("kcopyd", WQ_NON_REENTRANT | WQ_MEM_RECLAIM, 0); if (!kc->kcopyd_wq) goto bad_workqueue; kc->pages = NULL; kc->nr_reserved_pages = kc->nr_free_pages = 0; r = client_reserve_pages(kc, RESERVE_PAGES); if (r) goto bad_client_pages; kc->io_client = dm_io_client_create(); if (IS_ERR(kc->io_client)) { r = PTR_ERR(kc->io_client); goto bad_io_client; } init_waitqueue_head(&kc->destroyq); atomic_set(&kc->nr_jobs, 0); return kc; bad_io_client: client_free_pages(kc); bad_client_pages: destroy_workqueue(kc->kcopyd_wq); bad_workqueue: mempool_destroy(kc->job_pool); bad_slab: kfree(kc); return ERR_PTR(r); } EXPORT_SYMBOL(dm_kcopyd_client_create); void dm_kcopyd_client_destroy(struct dm_kcopyd_client *kc) { /* Wait for completion of all jobs submitted by this client. */ wait_event(kc->destroyq, !atomic_read(&kc->nr_jobs)); BUG_ON(!list_empty(&kc->complete_jobs)); BUG_ON(!list_empty(&kc->io_jobs)); BUG_ON(!list_empty(&kc->pages_jobs)); destroy_workqueue(kc->kcopyd_wq); dm_io_client_destroy(kc->io_client); client_free_pages(kc); mempool_destroy(kc->job_pool); kfree(kc); } EXPORT_SYMBOL(dm_kcopyd_client_destroy);
218673.c
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2010 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: Andrew Skalski <[email protected]> | | Stefan Esser <[email protected]> (resume functions) | +----------------------------------------------------------------------+ */ /* $Id: php_ftp.c 293036 2010-01-03 09:23:27Z sebastian $ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if defined(NETWARE) && defined(USE_WINSOCK) #include <novsock2.h> #endif #if HAVE_OPENSSL_EXT # include <openssl/ssl.h> #endif #if HAVE_FTP #include "ext/standard/info.h" #include "ext/standard/file.h" #include "php_ftp.h" #include "ftp.h" static int le_ftpbuf; #define le_ftpbuf_name "FTP Buffer" /* {{{ arginfo */ static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_connect, 0, 0, 1) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() #if HAVE_OPENSSL_EXT static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_ssl_connect, 0, 0, 1) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() #endif static ZEND_BEGIN_ARG_INFO(arginfo_ftp_login, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, username) ZEND_ARG_INFO(0, password) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_pwd, 0) ZEND_ARG_INFO(0, ftp) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_cdup, 0) ZEND_ARG_INFO(0, ftp) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_chdir, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, directory) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_exec, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, command) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_raw, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, command) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_mkdir, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, directory) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_rmdir, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, directory) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_chmod, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_alloc, 0, 0, 2) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(1, response) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_nlist, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, directory) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_rawlist, 0, 0, 2) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, directory) ZEND_ARG_INFO(0, recursive) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_systype, 0) ZEND_ARG_INFO(0, ftp) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_fget, 0, 0, 4) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, remote_file) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, resumepos) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_nb_fget, 0, 0, 4) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, remote_file) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, resumepos) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_pasv, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, pasv) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_get, 0, 0, 4) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, local_file) ZEND_ARG_INFO(0, remote_file) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, resume_pos) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_nb_get, 0, 0, 4) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, local_file) ZEND_ARG_INFO(0, remote_file) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, resume_pos) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_nb_continue, 0) ZEND_ARG_INFO(0, ftp) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_fput, 0, 0, 4) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, remote_file) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, startpos) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_nb_fput, 0, 0, 4) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, remote_file) ZEND_ARG_INFO(0, fp) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, startpos) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_put, 0, 0, 4) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, remote_file) ZEND_ARG_INFO(0, local_file) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, startpos) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO_EX(arginfo_ftp_nb_put, 0, 0, 4) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, remote_file) ZEND_ARG_INFO(0, local_file) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, startpos) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_size, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_mdtm, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_rename, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, src) ZEND_ARG_INFO(0, dest) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_delete, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, file) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_site, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, cmd) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_close, 0) ZEND_ARG_INFO(0, ftp) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_set_option, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, option) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() static ZEND_BEGIN_ARG_INFO(arginfo_ftp_get_option, 0) ZEND_ARG_INFO(0, ftp) ZEND_ARG_INFO(0, option) ZEND_END_ARG_INFO() /* }}} */ zend_function_entry php_ftp_functions[] = { PHP_FE(ftp_connect, arginfo_ftp_connect) #if HAVE_OPENSSL_EXT PHP_FE(ftp_ssl_connect, arginfo_ftp_ssl_connect) #endif PHP_FE(ftp_login, arginfo_ftp_login) PHP_FE(ftp_pwd, arginfo_ftp_pwd) PHP_FE(ftp_cdup, arginfo_ftp_cdup) PHP_FE(ftp_chdir, arginfo_ftp_chdir) PHP_FE(ftp_exec, arginfo_ftp_exec) PHP_FE(ftp_raw, arginfo_ftp_raw) PHP_FE(ftp_mkdir, arginfo_ftp_mkdir) PHP_FE(ftp_rmdir, arginfo_ftp_rmdir) PHP_FE(ftp_chmod, arginfo_ftp_chmod) PHP_FE(ftp_alloc, arginfo_ftp_alloc) PHP_FE(ftp_nlist, arginfo_ftp_nlist) PHP_FE(ftp_rawlist, arginfo_ftp_rawlist) PHP_FE(ftp_systype, arginfo_ftp_systype) PHP_FE(ftp_pasv, arginfo_ftp_pasv) PHP_FE(ftp_get, arginfo_ftp_get) PHP_FE(ftp_fget, arginfo_ftp_fget) PHP_FE(ftp_put, arginfo_ftp_put) PHP_FE(ftp_fput, arginfo_ftp_fput) PHP_FE(ftp_size, arginfo_ftp_size) PHP_FE(ftp_mdtm, arginfo_ftp_mdtm) PHP_FE(ftp_rename, arginfo_ftp_rename) PHP_FE(ftp_delete, arginfo_ftp_delete) PHP_FE(ftp_site, arginfo_ftp_site) PHP_FE(ftp_close, arginfo_ftp_close) PHP_FE(ftp_set_option, arginfo_ftp_set_option) PHP_FE(ftp_get_option, arginfo_ftp_get_option) PHP_FE(ftp_nb_fget, arginfo_ftp_nb_fget) PHP_FE(ftp_nb_get, arginfo_ftp_nb_get) PHP_FE(ftp_nb_continue, arginfo_ftp_nb_continue) PHP_FE(ftp_nb_put, arginfo_ftp_nb_put) PHP_FE(ftp_nb_fput, arginfo_ftp_nb_fput) PHP_FALIAS(ftp_quit, ftp_close, arginfo_ftp_close) {NULL, NULL, NULL} }; zend_module_entry php_ftp_module_entry = { STANDARD_MODULE_HEADER, "ftp", php_ftp_functions, PHP_MINIT(ftp), NULL, NULL, NULL, PHP_MINFO(ftp), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; #if COMPILE_DL_FTP ZEND_GET_MODULE(php_ftp) #endif static void ftp_destructor_ftpbuf(zend_rsrc_list_entry *rsrc TSRMLS_DC) { ftpbuf_t *ftp = (ftpbuf_t *)rsrc->ptr; ftp_close(ftp); } PHP_MINIT_FUNCTION(ftp) { le_ftpbuf = zend_register_list_destructors_ex(ftp_destructor_ftpbuf, NULL, le_ftpbuf_name, module_number); REGISTER_LONG_CONSTANT("FTP_ASCII", FTPTYPE_ASCII, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_TEXT", FTPTYPE_ASCII, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_BINARY", FTPTYPE_IMAGE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_IMAGE", FTPTYPE_IMAGE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_AUTORESUME", PHP_FTP_AUTORESUME, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_TIMEOUT_SEC", PHP_FTP_OPT_TIMEOUT_SEC, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_AUTOSEEK", PHP_FTP_OPT_AUTOSEEK, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_FAILED", PHP_FTP_FAILED, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_FINISHED", PHP_FTP_FINISHED, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("FTP_MOREDATA", PHP_FTP_MOREDATA, CONST_PERSISTENT | CONST_CS); return SUCCESS; } PHP_MINFO_FUNCTION(ftp) { php_info_print_table_start(); php_info_print_table_row(2, "FTP support", "enabled"); php_info_print_table_end(); } #define XTYPE(xtype, mode) { \ if (mode != FTPTYPE_ASCII && mode != FTPTYPE_IMAGE) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Mode must be FTP_ASCII or FTP_BINARY"); \ RETURN_FALSE; \ } \ xtype = mode; \ } /* {{{ proto resource ftp_connect(string host [, int port [, int timeout]]) Opens a FTP stream */ PHP_FUNCTION(ftp_connect) { ftpbuf_t *ftp; char *host; int host_len; long port = 0; long timeout_sec = FTP_DEFAULT_TIMEOUT; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &host, &host_len, &port, &timeout_sec) == FAILURE) { return; } if (timeout_sec <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Timeout has to be greater than 0"); RETURN_FALSE; } /* connect */ if (!(ftp = ftp_open(host, (short)port, timeout_sec TSRMLS_CC))) { RETURN_FALSE; } /* autoseek for resuming */ ftp->autoseek = FTP_DEFAULT_AUTOSEEK; #if HAVE_OPENSSL_EXT /* disable ssl */ ftp->use_ssl = 0; #endif ZEND_REGISTER_RESOURCE(return_value, ftp, le_ftpbuf); } /* }}} */ #if HAVE_OPENSSL_EXT /* {{{ proto resource ftp_ssl_connect(string host [, int port [, int timeout]]) Opens a FTP-SSL stream */ PHP_FUNCTION(ftp_ssl_connect) { ftpbuf_t *ftp; char *host; int host_len; long port = 0; long timeout_sec = FTP_DEFAULT_TIMEOUT; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &host, &host_len, &port, &timeout_sec) == FAILURE) { return; } if (timeout_sec <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Timeout has to be greater than 0"); RETURN_FALSE; } /* connect */ if (!(ftp = ftp_open(host, (short)port, timeout_sec TSRMLS_CC))) { RETURN_FALSE; } /* autoseek for resuming */ ftp->autoseek = FTP_DEFAULT_AUTOSEEK; /* enable ssl */ ftp->use_ssl = 1; ZEND_REGISTER_RESOURCE(return_value, ftp, le_ftpbuf); } /* }}} */ #endif /* {{{ proto bool ftp_login(resource stream, string username, string password) Logs into the FTP server */ PHP_FUNCTION(ftp_login) { zval *z_ftp; ftpbuf_t *ftp; char *user, *pass; int user_len, pass_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &z_ftp, &user, &user_len, &pass, &pass_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* log in */ if (!ftp_login(ftp, user, pass TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto string ftp_pwd(resource stream) Returns the present working directory */ PHP_FUNCTION(ftp_pwd) { zval *z_ftp; ftpbuf_t *ftp; const char *pwd; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_ftp) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); if (!(pwd = ftp_pwd(ftp))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_STRING((char*) pwd, 1); } /* }}} */ /* {{{ proto bool ftp_cdup(resource stream) Changes to the parent directory */ PHP_FUNCTION(ftp_cdup) { zval *z_ftp; ftpbuf_t *ftp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_ftp) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); if (!ftp_cdup(ftp)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ftp_chdir(resource stream, string directory) Changes directories */ PHP_FUNCTION(ftp_chdir) { zval *z_ftp; ftpbuf_t *ftp; char *dir; int dir_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &dir, &dir_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* change directories */ if (!ftp_chdir(ftp, dir)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ftp_exec(resource stream, string command) Requests execution of a program on the FTP server */ PHP_FUNCTION(ftp_exec) { zval *z_ftp; ftpbuf_t *ftp; char *cmd; int cmd_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &cmd, &cmd_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* execute serverside command */ if (!ftp_exec(ftp, cmd)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array ftp_raw(resource stream, string command) Sends a literal command to the FTP server */ PHP_FUNCTION(ftp_raw) { zval *z_ftp; ftpbuf_t *ftp; char *cmd; int cmd_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &cmd, &cmd_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* execute arbitrary ftp command */ ftp_raw(ftp, cmd, return_value); } /* }}} */ /* {{{ proto string ftp_mkdir(resource stream, string directory) Creates a directory and returns the absolute path for the new directory or false on error */ PHP_FUNCTION(ftp_mkdir) { zval *z_ftp; ftpbuf_t *ftp; char *dir, *tmp; int dir_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &dir, &dir_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* create directorie */ if (NULL == (tmp = ftp_mkdir(ftp, dir))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_STRING(tmp, 0); } /* }}} */ /* {{{ proto bool ftp_rmdir(resource stream, string directory) Removes a directory */ PHP_FUNCTION(ftp_rmdir) { zval *z_ftp; ftpbuf_t *ftp; char *dir; int dir_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &dir, &dir_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* remove directorie */ if (!ftp_rmdir(ftp, dir)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto int ftp_chmod(resource stream, int mode, string filename) Sets permissions on a file */ PHP_FUNCTION(ftp_chmod) { zval *z_ftp; ftpbuf_t *ftp; char *filename; int filename_len; long mode; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rls", &z_ftp, &mode, &filename, &filename_len) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); if (!ftp_chmod(ftp, mode, filename, filename_len)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_LONG(mode); } /* }}} */ /* {{{ proto bool ftp_alloc(resource stream, int size[, &response]) Attempt to allocate space on the remote FTP server */ PHP_FUNCTION(ftp_alloc) { zval *z_ftp, *zresponse = NULL; ftpbuf_t *ftp; long size, ret; char *response = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|z", &z_ftp, &size, &zresponse) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); ret = ftp_alloc(ftp, size, zresponse ? &response : NULL); if (response) { zval_dtor(zresponse); ZVAL_STRING(zresponse, response, 0); } if (!ret) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array ftp_nlist(resource stream, string directory) Returns an array of filenames in the given directory */ PHP_FUNCTION(ftp_nlist) { zval *z_ftp; ftpbuf_t *ftp; char **nlist, **ptr, *dir; int dir_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &dir, &dir_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* get list of files */ if (NULL == (nlist = ftp_nlist(ftp, dir TSRMLS_CC))) { RETURN_FALSE; } array_init(return_value); for (ptr = nlist; *ptr; ptr++) { add_next_index_string(return_value, *ptr, 1); } efree(nlist); } /* }}} */ /* {{{ proto array ftp_rawlist(resource stream, string directory [, bool recursive]) Returns a detailed listing of a directory as an array of output lines */ PHP_FUNCTION(ftp_rawlist) { zval *z_ftp; ftpbuf_t *ftp; char **llist, **ptr, *dir; int dir_len; zend_bool recursive = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|b", &z_ftp, &dir, &dir_len, &recursive) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* get raw directory listing */ if (NULL == (llist = ftp_list(ftp, dir, recursive TSRMLS_CC))) { RETURN_FALSE; } array_init(return_value); for (ptr = llist; *ptr; ptr++) { add_next_index_string(return_value, *ptr, 1); } efree(llist); } /* }}} */ /* {{{ proto string ftp_systype(resource stream) Returns the system type identifier */ PHP_FUNCTION(ftp_systype) { zval *z_ftp; ftpbuf_t *ftp; const char *syst; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_ftp) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); if (NULL == (syst = ftp_syst(ftp))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_STRING((char*) syst, 1); } /* }}} */ /* {{{ proto bool ftp_fget(resource stream, resource fp, string remote_file, int mode[, int resumepos]) Retrieves a file from the FTP server and writes it to an open file */ PHP_FUNCTION(ftp_fget) { zval *z_ftp, *z_file; ftpbuf_t *ftp; ftptype_t xtype; php_stream *stream; char *file; int file_len; long mode, resumepos=0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrsl|l", &z_ftp, &z_file, &file, &file_len, &mode, &resumepos) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); php_stream_from_zval(stream, &z_file); XTYPE(xtype, mode); /* ignore autoresume if autoseek is switched off */ if (!ftp->autoseek && resumepos == PHP_FTP_AUTORESUME) { resumepos = 0; } if (ftp->autoseek && resumepos) { /* if autoresume is wanted seek to end */ if (resumepos == PHP_FTP_AUTORESUME) { php_stream_seek(stream, 0, SEEK_END); resumepos = php_stream_tell(stream); } else { php_stream_seek(stream, resumepos, SEEK_SET); } } if (!ftp_get(ftp, stream, file, xtype, resumepos TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto int ftp_nb_fget(resource stream, resource fp, string remote_file, int mode[, int resumepos]) Retrieves a file from the FTP server asynchronly and writes it to an open file */ PHP_FUNCTION(ftp_nb_fget) { zval *z_ftp, *z_file; ftpbuf_t *ftp; ftptype_t xtype; php_stream *stream; char *file; int file_len, ret; long mode, resumepos=0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrsl|l", &z_ftp, &z_file, &file, &file_len, &mode, &resumepos) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); php_stream_from_zval(stream, &z_file); XTYPE(xtype, mode); /* ignore autoresume if autoseek is switched off */ if (!ftp->autoseek && resumepos == PHP_FTP_AUTORESUME) { resumepos = 0; } if (ftp->autoseek && resumepos) { /* if autoresume is wanted seek to end */ if (resumepos == PHP_FTP_AUTORESUME) { php_stream_seek(stream, 0, SEEK_END); resumepos = php_stream_tell(stream); } else { php_stream_seek(stream, resumepos, SEEK_SET); } } /* configuration */ ftp->direction = 0; /* recv */ ftp->closestream = 0; /* do not close */ if ((ret = ftp_nb_get(ftp, stream, file, xtype, resumepos TSRMLS_CC)) == PHP_FTP_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_LONG(ret); } RETURN_LONG(ret); } /* }}} */ /* {{{ proto bool ftp_pasv(resource stream, bool pasv) Turns passive mode on or off */ PHP_FUNCTION(ftp_pasv) { zval *z_ftp; ftpbuf_t *ftp; zend_bool pasv; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &z_ftp, &pasv) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); if (!ftp_pasv(ftp, pasv ? 1 : 0)) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ftp_get(resource stream, string local_file, string remote_file, int mode[, int resume_pos]) Retrieves a file from the FTP server and writes it to a local file */ PHP_FUNCTION(ftp_get) { zval *z_ftp; ftpbuf_t *ftp; ftptype_t xtype; php_stream *outstream; char *local, *remote; int local_len, remote_len; long mode, resumepos=0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rssl|l", &z_ftp, &local, &local_len, &remote, &remote_len, &mode, &resumepos) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); XTYPE(xtype, mode); /* ignore autoresume if autoseek is switched off */ if (!ftp->autoseek && resumepos == PHP_FTP_AUTORESUME) { resumepos = 0; } #ifdef PHP_WIN32 mode = FTPTYPE_IMAGE; #endif if (ftp->autoseek && resumepos) { outstream = php_stream_open_wrapper(local, mode == FTPTYPE_ASCII ? "rt+" : "rb+", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL); if (outstream == NULL) { outstream = php_stream_open_wrapper(local, mode == FTPTYPE_ASCII ? "wt" : "wb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL); } if (outstream != NULL) { /* if autoresume is wanted seek to end */ if (resumepos == PHP_FTP_AUTORESUME) { php_stream_seek(outstream, 0, SEEK_END); resumepos = php_stream_tell(outstream); } else { php_stream_seek(outstream, resumepos, SEEK_SET); } } } else { outstream = php_stream_open_wrapper(local, mode == FTPTYPE_ASCII ? "wt" : "wb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL); } if (outstream == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error opening %s", local); RETURN_FALSE; } if (!ftp_get(ftp, outstream, remote, xtype, resumepos TSRMLS_CC)) { php_stream_close(outstream); VCWD_UNLINK(local); php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } php_stream_close(outstream); RETURN_TRUE; } /* }}} */ /* {{{ proto int ftp_nb_get(resource stream, string local_file, string remote_file, int mode[, int resume_pos]) Retrieves a file from the FTP server nbhronly and writes it to a local file */ PHP_FUNCTION(ftp_nb_get) { zval *z_ftp; ftpbuf_t *ftp; ftptype_t xtype; php_stream *outstream; char *local, *remote; int local_len, remote_len, ret; long mode, resumepos=0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rssl|l", &z_ftp, &local, &local_len, &remote, &remote_len, &mode, &resumepos) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); XTYPE(xtype, mode); /* ignore autoresume if autoseek is switched off */ if (!ftp->autoseek && resumepos == PHP_FTP_AUTORESUME) { resumepos = 0; } #ifdef PHP_WIN32 mode = FTPTYPE_IMAGE; #endif if (ftp->autoseek && resumepos) { outstream = php_stream_open_wrapper(local, mode == FTPTYPE_ASCII ? "rt+" : "rb+", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL); if (outstream == NULL) { outstream = php_stream_open_wrapper(local, mode == FTPTYPE_ASCII ? "wt" : "wb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL); } if (outstream != NULL) { /* if autoresume is wanted seek to end */ if (resumepos == PHP_FTP_AUTORESUME) { php_stream_seek(outstream, 0, SEEK_END); resumepos = php_stream_tell(outstream); } else { php_stream_seek(outstream, resumepos, SEEK_SET); } } } else { outstream = php_stream_open_wrapper(local, mode == FTPTYPE_ASCII ? "wt" : "wb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL); } if (outstream == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error opening %s", local); RETURN_FALSE; } /* configuration */ ftp->direction = 0; /* recv */ ftp->closestream = 1; /* do close */ if ((ret = ftp_nb_get(ftp, outstream, remote, xtype, resumepos TSRMLS_CC)) == PHP_FTP_FAILED) { php_stream_close(outstream); VCWD_UNLINK(local); php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_LONG(PHP_FTP_FAILED); } if (ret == PHP_FTP_FINISHED) { php_stream_close(outstream); } RETURN_LONG(ret); } /* }}} */ /* {{{ proto int ftp_nb_continue(resource stream) Continues retrieving/sending a file nbronously */ PHP_FUNCTION(ftp_nb_continue) { zval *z_ftp; ftpbuf_t *ftp; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_ftp) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); if (!ftp->nb) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "no nbronous transfer to continue."); RETURN_LONG(PHP_FTP_FAILED); } if (ftp->direction) { ret=ftp_nb_continue_write(ftp TSRMLS_CC); } else { ret=ftp_nb_continue_read(ftp TSRMLS_CC); } if (ret != PHP_FTP_MOREDATA && ftp->closestream) { php_stream_close(ftp->stream); } if (ret == PHP_FTP_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); } RETURN_LONG(ret); } /* }}} */ /* {{{ proto bool ftp_fput(resource stream, string remote_file, resource fp, int mode[, int startpos]) Stores a file from an open file to the FTP server */ PHP_FUNCTION(ftp_fput) { zval *z_ftp, *z_file; ftpbuf_t *ftp; ftptype_t xtype; int remote_len; long mode, startpos=0; php_stream *stream; char *remote; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsrl|l", &z_ftp, &remote, &remote_len, &z_file, &mode, &startpos) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); php_stream_from_zval(stream, &z_file); XTYPE(xtype, mode); /* ignore autoresume if autoseek is switched off */ if (!ftp->autoseek && startpos == PHP_FTP_AUTORESUME) { startpos = 0; } if (ftp->autoseek && startpos) { /* if autoresume is wanted ask for remote size */ if (startpos == PHP_FTP_AUTORESUME) { startpos = ftp_size(ftp, remote); if (startpos < 0) { startpos = 0; } } if (startpos) { php_stream_seek(stream, startpos, SEEK_SET); } } if (!ftp_put(ftp, remote, stream, xtype, startpos TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto int ftp_nb_fput(resource stream, string remote_file, resource fp, int mode[, int startpos]) Stores a file from an open file to the FTP server nbronly */ PHP_FUNCTION(ftp_nb_fput) { zval *z_ftp, *z_file; ftpbuf_t *ftp; ftptype_t xtype; int remote_len, ret; long mode, startpos=0; php_stream *stream; char *remote; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsrl|l", &z_ftp, &remote, &remote_len, &z_file, &mode, &startpos) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); php_stream_from_zval(stream, &z_file); XTYPE(xtype, mode); /* ignore autoresume if autoseek is switched off */ if (!ftp->autoseek && startpos == PHP_FTP_AUTORESUME) { startpos = 0; } if (ftp->autoseek && startpos) { /* if autoresume is wanted ask for remote size */ if (startpos == PHP_FTP_AUTORESUME) { startpos = ftp_size(ftp, remote); if (startpos < 0) { startpos = 0; } } if (startpos) { php_stream_seek(stream, startpos, SEEK_SET); } } /* configuration */ ftp->direction = 1; /* send */ ftp->closestream = 0; /* do not close */ if (((ret = ftp_nb_put(ftp, remote, stream, xtype, startpos TSRMLS_CC)) == PHP_FTP_FAILED)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_LONG(ret); } RETURN_LONG(ret); } /* }}} */ /* {{{ proto bool ftp_put(resource stream, string remote_file, string local_file, int mode[, int startpos]) Stores a file on the FTP server */ PHP_FUNCTION(ftp_put) { zval *z_ftp; ftpbuf_t *ftp; ftptype_t xtype; char *remote, *local; int remote_len, local_len; long mode, startpos=0; php_stream *instream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rssl|l", &z_ftp, &remote, &remote_len, &local, &local_len, &mode, &startpos) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); XTYPE(xtype, mode); if (!(instream = php_stream_open_wrapper(local, mode == FTPTYPE_ASCII ? "rt" : "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL))) { RETURN_FALSE; } /* ignore autoresume if autoseek is switched off */ if (!ftp->autoseek && startpos == PHP_FTP_AUTORESUME) { startpos = 0; } if (ftp->autoseek && startpos) { /* if autoresume is wanted ask for remote size */ if (startpos == PHP_FTP_AUTORESUME) { startpos = ftp_size(ftp, remote); if (startpos < 0) { startpos = 0; } } if (startpos) { php_stream_seek(instream, startpos, SEEK_SET); } } if (!ftp_put(ftp, remote, instream, xtype, startpos TSRMLS_CC)) { php_stream_close(instream); php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } php_stream_close(instream); RETURN_TRUE; } /* }}} */ /* {{{ proto int ftp_nb_put(resource stream, string remote_file, string local_file, int mode[, int startpos]) Stores a file on the FTP server */ PHP_FUNCTION(ftp_nb_put) { zval *z_ftp; ftpbuf_t *ftp; ftptype_t xtype; char *remote, *local; int remote_len, local_len, ret; long mode, startpos=0; php_stream *instream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rssl|l", &z_ftp, &remote, &remote_len, &local, &local_len, &mode, &startpos) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); XTYPE(xtype, mode); if (!(instream = php_stream_open_wrapper(local, mode == FTPTYPE_ASCII ? "rt" : "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL))) { RETURN_FALSE; } /* ignore autoresume if autoseek is switched off */ if (!ftp->autoseek && startpos == PHP_FTP_AUTORESUME) { startpos = 0; } if (ftp->autoseek && startpos) { /* if autoresume is wanted ask for remote size */ if (startpos == PHP_FTP_AUTORESUME) { startpos = ftp_size(ftp, remote); if (startpos < 0) { startpos = 0; } } if (startpos) { php_stream_seek(instream, startpos, SEEK_SET); } } /* configuration */ ftp->direction = 1; /* send */ ftp->closestream = 1; /* do close */ ret = ftp_nb_put(ftp, remote, instream, xtype, startpos TSRMLS_CC); if (ret != PHP_FTP_MOREDATA) { php_stream_close(instream); } if (ret == PHP_FTP_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); } RETURN_LONG(ret); } /* }}} */ /* {{{ proto int ftp_size(resource stream, string filename) Returns the size of the file, or -1 on error */ PHP_FUNCTION(ftp_size) { zval *z_ftp; ftpbuf_t *ftp; char *file; int file_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &file, &file_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* get file size */ RETURN_LONG(ftp_size(ftp, file)); } /* }}} */ /* {{{ proto int ftp_mdtm(resource stream, string filename) Returns the last modification time of the file, or -1 on error */ PHP_FUNCTION(ftp_mdtm) { zval *z_ftp; ftpbuf_t *ftp; char *file; int file_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &file, &file_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* get file mod time */ RETURN_LONG(ftp_mdtm(ftp, file)); } /* }}} */ /* {{{ proto bool ftp_rename(resource stream, string src, string dest) Renames the given file to a new path */ PHP_FUNCTION(ftp_rename) { zval *z_ftp; ftpbuf_t *ftp; char *src, *dest; int src_len, dest_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &z_ftp, &src, &src_len, &dest, &dest_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* rename the file */ if (!ftp_rename(ftp, src, dest)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ftp_delete(resource stream, string file) Deletes a file */ PHP_FUNCTION(ftp_delete) { zval *z_ftp; ftpbuf_t *ftp; char *file; int file_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &file, &file_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* delete the file */ if (!ftp_delete(ftp, file)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ftp_site(resource stream, string cmd) Sends a SITE command to the server */ PHP_FUNCTION(ftp_site) { zval *z_ftp; ftpbuf_t *ftp; char *cmd; int cmd_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &z_ftp, &cmd, &cmd_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); /* send the site command */ if (!ftp_site(ftp, cmd)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", ftp->inbuf); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ftp_close(resource stream) Closes the FTP stream */ PHP_FUNCTION(ftp_close) { zval *z_ftp; ftpbuf_t *ftp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &z_ftp) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); ftp_quit(ftp); RETURN_BOOL(zend_list_delete(Z_LVAL_P(z_ftp)) == SUCCESS); } /* }}} */ /* {{{ proto bool ftp_set_option(resource stream, int option, mixed value) Sets an FTP option */ PHP_FUNCTION(ftp_set_option) { zval *z_ftp, *z_value; long option; ftpbuf_t *ftp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlz", &z_ftp, &option, &z_value) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); switch (option) { case PHP_FTP_OPT_TIMEOUT_SEC: if (Z_TYPE_P(z_value) != IS_LONG) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Option TIMEOUT_SEC expects value of type long, %s given", zend_zval_type_name(z_value)); RETURN_FALSE; } if (Z_LVAL_P(z_value) <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Timeout has to be greater than 0"); RETURN_FALSE; } ftp->timeout_sec = Z_LVAL_P(z_value); RETURN_TRUE; break; case PHP_FTP_OPT_AUTOSEEK: if (Z_TYPE_P(z_value) != IS_BOOL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Option AUTOSEEK expects value of type boolean, %s given", zend_zval_type_name(z_value)); RETURN_FALSE; } ftp->autoseek = Z_LVAL_P(z_value); RETURN_TRUE; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown option '%ld'", option); RETURN_FALSE; break; } } /* }}} */ /* {{{ proto mixed ftp_get_option(resource stream, int option) Gets an FTP option */ PHP_FUNCTION(ftp_get_option) { zval *z_ftp; long option; ftpbuf_t *ftp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &z_ftp, &option) == FAILURE) { return; } ZEND_FETCH_RESOURCE(ftp, ftpbuf_t*, &z_ftp, -1, le_ftpbuf_name, le_ftpbuf); switch (option) { case PHP_FTP_OPT_TIMEOUT_SEC: RETURN_LONG(ftp->timeout_sec); break; case PHP_FTP_OPT_AUTOSEEK: RETURN_BOOL(ftp->autoseek); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown option '%ld'", option); RETURN_FALSE; break; } } /* }}} */ #endif /* HAVE_FTP */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
60108.c
#include <stdlib.h> #include <string.h> #include <homekit/types.h> bool homekit_value_equal(homekit_value_t *a, homekit_value_t *b) { if (a->is_null != b->is_null) return false; if (a->format != b->format) return false; switch (a->format) { case homekit_format_bool: return a->bool_value == b->bool_value; case homekit_format_uint8: case homekit_format_uint16: case homekit_format_uint32: case homekit_format_uint64: case homekit_format_int: return a->int_value == b->int_value; case homekit_format_float: return a->float_value == b->float_value; case homekit_format_string: return !strcmp(a->string_value, b->string_value); case homekit_format_tlv: { if (!a->tlv_values && !b->tlv_values) return true; if (!a->tlv_values || !b->tlv_values) return false; // TODO: implement order independent comparison? tlv_t *ta = a->tlv_values->head, *tb = b->tlv_values->head; for (; ta && tb; ta=ta->next, tb=tb->next) { if (ta->type != tb->type || ta->size != tb->size) return false; if (strncmp((char *)ta->value, (char *)tb->value, ta->size)) return false; } return (!ta && !tb); } case homekit_format_data: // TODO: implement comparison return false; } return false; } void homekit_value_copy(homekit_value_t *dst, homekit_value_t *src) { memset(dst, 0, sizeof(*dst)); dst->format = src->format; dst->is_null = src->is_null; if (!src->is_null) { switch (src->format) { case homekit_format_bool: dst->bool_value = src->bool_value; break; case homekit_format_uint8: case homekit_format_uint16: case homekit_format_uint32: case homekit_format_uint64: case homekit_format_int: dst->int_value = src->int_value; break; case homekit_format_float: dst->float_value = src->float_value; break; case homekit_format_string: if (src->is_static) { dst->string_value = src->string_value; dst->is_static = true; } else { dst->string_value = strdup(src->string_value); } break; case homekit_format_tlv: { if (src->is_static) { dst->tlv_values = src->tlv_values; dst->is_static = true; } else { dst->tlv_values = tlv_new(); for (tlv_t *v=src->tlv_values->head; v; v=v->next) { tlv_add_value(dst->tlv_values, v->type, v->value, v->size); } } break; } case homekit_format_data: // TODO: break; default: // unknown format break; } } } homekit_value_t *homekit_value_clone(homekit_value_t *value) { homekit_value_t *copy = malloc(sizeof(homekit_value_t)); homekit_value_copy(copy, value); return copy; } void homekit_value_destruct(homekit_value_t *value) { if (!value->is_null) { switch (value->format) { case homekit_format_string: if (!value->is_static && value->string_value) free(value->string_value); break; case homekit_format_tlv: if (!value->is_static && value->tlv_values) tlv_free(value->tlv_values); break; case homekit_format_data: // TODO: break; default: // unknown format break; } } } void homekit_value_free(homekit_value_t *value) { homekit_value_destruct(value); free(value); } size_t align_size(size_t size) { if (size % sizeof(void*)) { size += sizeof(void*) - size % sizeof(void*); } return size; } void *align_pointer(void *ptr) { uintptr_t p = (uintptr_t) ptr; if (p % sizeof(void*)) { p += sizeof(void*) - p % sizeof(void*); } return (void*) p; } homekit_characteristic_t* homekit_characteristic_clone(homekit_characteristic_t* ch) { size_t type_len = strlen(ch->type) + 1; size_t description_len = ch->description ? strlen(ch->description) + 1 : 0; size_t size = align_size(sizeof(homekit_characteristic_t) + type_len + description_len); if (ch->min_value) size += sizeof(float); if (ch->max_value) size += sizeof(float); if (ch->min_step) size += sizeof(float); if (ch->max_len) size += sizeof(int); if (ch->max_data_len) size += sizeof(int); if (ch->valid_values.count) size += align_size(sizeof(uint8_t) * ch->valid_values.count); if (ch->valid_values_ranges.count) size += align_size(sizeof(homekit_valid_values_range_t) * ch->valid_values_ranges.count); if (ch->callback) { homekit_characteristic_change_callback_t *c = ch->callback; while (c) { size += align_size(sizeof(homekit_characteristic_change_callback_t)); c = c->next; } } uint8_t* p = calloc(1, size); homekit_characteristic_t* clone = (homekit_characteristic_t*) p; p += sizeof(homekit_characteristic_t); clone->service = ch->service; clone->id = ch->id; clone->type = (char*) p; strncpy((char*) p, ch->type, type_len); p[type_len - 1] = 0; p += type_len; clone->description = (char*) p; strncpy((char*) p, ch->description, description_len); p[description_len - 1] = 0; p += description_len; p = align_pointer(p); clone->format = ch->format; clone->unit = ch->unit; clone->permissions = ch->permissions; homekit_value_copy(&clone->value, &ch->value); if (ch->min_value) { clone->min_value = (float*) p; *clone->min_value = *ch->min_value; p += sizeof(float); } if (ch->max_value) { clone->max_value = (float*) p; *clone->max_value = *ch->max_value; p += sizeof(float); } if (ch->min_step) { clone->min_step = (float*) p; *clone->min_step = *ch->min_step; p += sizeof(float); } if (ch->max_len) { clone->max_len = (int*) p; *clone->max_len = *ch->max_len; p += sizeof(int); } if (ch->max_data_len) { clone->max_data_len = (int*) p; *clone->max_data_len = *ch->max_data_len; p += sizeof(int); } if (ch->valid_values.count) { clone->valid_values.count = ch->valid_values.count; clone->valid_values.values = (uint8_t*) p; memcpy(clone->valid_values.values, ch->valid_values.values, sizeof(uint8_t) * ch->valid_values.count); p += align_size(sizeof(uint8_t) * ch->valid_values.count); } if (ch->valid_values_ranges.count) { int c = ch->valid_values_ranges.count; clone->valid_values_ranges.count = c; clone->valid_values_ranges.ranges = (homekit_valid_values_range_t*) p; memcpy(clone->valid_values_ranges.ranges, ch->valid_values_ranges.ranges, sizeof(homekit_valid_values_range_t*) * c); p += align_size(sizeof(homekit_valid_values_range_t*) * c); } if (ch->callback) { int c = 1; homekit_characteristic_change_callback_t *callback_in = ch->callback; clone->callback = (homekit_characteristic_change_callback_t*)p; homekit_characteristic_change_callback_t *callback_out = clone->callback; memcpy(callback_out, callback_in, sizeof(*callback_out)); while (callback_in->next) { callback_in = callback_in->next; callback_out->next = callback_out + 1; callback_out = callback_out->next; memcpy(callback_out, callback_in, sizeof(*callback_out)); c++; } callback_out->next = NULL; p += align_size(sizeof(homekit_characteristic_change_callback_t)) * c; } clone->getter = ch->getter; clone->setter = ch->setter; clone->getter_ex = ch->getter_ex; clone->setter_ex = ch->setter_ex; clone->context = ch->context; return clone; } homekit_service_t* homekit_service_clone(homekit_service_t* service) { size_t type_len = strlen(service->type) + 1; size_t size = align_size(sizeof(homekit_service_t) + type_len); if (service->linked) { int i = 0; while (service->linked[i]) i++; size += sizeof(homekit_service_t*) * (i + 1); } if (service->characteristics) { int i = 0; while (service->characteristics[i]) i++; size += sizeof(homekit_characteristic_t*) * (i + 1); } uint8_t *p = calloc(1, size); homekit_service_t *clone = (homekit_service_t*) p; p += sizeof(homekit_service_t); clone->accessory = service->accessory; clone->id = service->id; clone->type = strncpy((char*) p, service->type, type_len); p[type_len - 1] = 0; p += align_size(type_len); clone->hidden = service->hidden; clone->primary = service->primary; if (service->linked) { clone->linked = (homekit_service_t**) p; int i = 0; while (service->linked[i]) { clone->linked[i] = service->linked[i]; i++; } clone->linked[i] = NULL; p += (i + 1) * sizeof(homekit_service_t*); } if (service->characteristics) { clone->characteristics = (homekit_characteristic_t**) p; int i = 0; while (service->characteristics[i]) { clone->characteristics[i] = service->characteristics[i]; i++; } clone->characteristics[i] = NULL; p += (i + 1) * sizeof(homekit_characteristic_t*); } return clone; } homekit_accessory_t* homekit_accessory_clone(homekit_accessory_t* ac) { size_t size = sizeof(homekit_accessory_t); if (ac->services) { for (int i=0; ac->services[i]; i++) { size += sizeof(homekit_service_t*); } size += sizeof(homekit_service_t*); } uint8_t* p = calloc(1, size); homekit_accessory_t* clone = (homekit_accessory_t*) p; p += align_size(sizeof(homekit_accessory_t)); clone->id = ac->id; clone->category = ac->category; clone->config_number = ac->config_number; if (ac->services) { clone->services = (homekit_service_t**) p; int i = 0; while (ac->services[i]) { clone->services[i] = ac->services[i]; i++; } clone->services[i] = NULL; p += sizeof(homekit_service_t*) * (i + 1); } return clone; } homekit_value_t homekit_characteristic_ex_old_getter(const homekit_characteristic_t *ch) { return ch->getter(); } void homekit_characteristic_ex_old_setter(homekit_characteristic_t *ch, homekit_value_t value) { ch->setter(value); } void homekit_accessories_init(homekit_accessory_t **accessories) { int aid = 1; for (homekit_accessory_t **accessory_it = accessories; *accessory_it; accessory_it++) { homekit_accessory_t *accessory = *accessory_it; if (accessory->id) { if (accessory->id >= aid) aid = accessory->id+1; } else { accessory->id = aid++; } int iid = 1; for (homekit_service_t **service_it = accessory->services; *service_it; service_it++) { homekit_service_t *service = *service_it; service->accessory = accessory; if (service->id) { if (service->id >= iid) iid = service->id+1; } else { service->id = iid++; } for (homekit_characteristic_t **ch_it = service->characteristics; *ch_it; ch_it++) { homekit_characteristic_t *ch = *ch_it; ch->service = service; if (ch->id) { if (ch->id >= iid) iid = ch->id+1; } else { ch->id = iid++; } if (!ch->getter_ex && ch->getter) { ch->getter_ex = homekit_characteristic_ex_old_getter; } if (!ch->setter_ex && ch->setter) { ch->setter_ex = homekit_characteristic_ex_old_setter; } ch->value.format = ch->format; } } } printf("homekit_accessories_init done\n"); } homekit_accessory_t *homekit_accessory_by_id(homekit_accessory_t **accessories, int aid) { for (homekit_accessory_t **accessory_it = accessories; *accessory_it; accessory_it++) { homekit_accessory_t *accessory = *accessory_it; if (accessory->id == aid) return accessory; } return NULL; } homekit_service_t *homekit_service_by_type(homekit_accessory_t *accessory, const char *type) { for (homekit_service_t **service_it = accessory->services; *service_it; service_it++) { homekit_service_t *service = *service_it; if (!strcmp(service->type, type)) return service; } return NULL; } homekit_characteristic_t *homekit_service_characteristic_by_type(homekit_service_t *service, const char *type) { for (homekit_characteristic_t **ch_it = service->characteristics; *ch_it; ch_it++) { homekit_characteristic_t *ch = *ch_it; if (!strcmp(ch->type, type)) return ch; } return NULL; } homekit_characteristic_t *homekit_characteristic_by_aid_and_iid(homekit_accessory_t **accessories, int aid, int iid) { for (homekit_accessory_t **accessory_it = accessories; *accessory_it; accessory_it++) { homekit_accessory_t *accessory = *accessory_it; if (accessory->id != aid) continue; for (homekit_service_t **service_it = accessory->services; *service_it; service_it++) { homekit_service_t *service = *service_it; for (homekit_characteristic_t **ch_it = service->characteristics; *ch_it; ch_it++) { homekit_characteristic_t *ch = *ch_it; if (ch->id == iid) return ch; } } } return NULL; } homekit_characteristic_t *homekit_characteristic_find_by_type(homekit_accessory_t **accessories, int aid, const char *type) { for (homekit_accessory_t **accessory_it = accessories; *accessory_it; accessory_it++) { homekit_accessory_t *accessory = *accessory_it; if (accessory->id != aid) continue; for (homekit_service_t **service_it = accessory->services; *service_it; service_it++) { homekit_service_t *service = *service_it; for (homekit_characteristic_t **ch_it = service->characteristics; *ch_it; ch_it++) { homekit_characteristic_t *ch = *ch_it; if (!strcmp(ch->type, type)) return ch; } } } return NULL; } void homekit_characteristic_notify(homekit_characteristic_t *ch, homekit_value_t value) { homekit_characteristic_change_callback_t *callback = ch->callback; while (callback) { callback->function(ch, value, callback->context); callback = callback->next; } } void homekit_characteristic_add_notify_callback( homekit_characteristic_t *ch, homekit_characteristic_change_callback_fn function, void *context ) { homekit_characteristic_change_callback_t *new_callback = malloc(sizeof(homekit_characteristic_change_callback_t)); new_callback->function = function; new_callback->context = context; new_callback->next = NULL; if (!ch->callback) { ch->callback = new_callback; } else { homekit_characteristic_change_callback_t *callback = ch->callback; if (callback->function == function && callback->context == context) { free(new_callback); return; } while (callback->next) { if (callback->next->function == function && callback->next->context == context) { free(new_callback); return; } callback = callback->next; } callback->next = new_callback; } } void homekit_characteristic_remove_notify_callback( homekit_characteristic_t *ch, homekit_characteristic_change_callback_fn function, void *context ) { while (ch->callback) { if (ch->callback->function != function || ch->callback->context != context) { break; } homekit_characteristic_change_callback_t *c = ch->callback; ch->callback = ch->callback->next; free(c); } if (!ch->callback) return; homekit_characteristic_change_callback_t *callback = ch->callback; while (callback->next) { if (callback->next->function == function && callback->next->context == context) { homekit_characteristic_change_callback_t *c = callback->next; callback->next = callback->next->next; free(c); } else { callback = callback->next; } } } // Removes particular callback from all characteristics void homekit_accessories_clear_notify_callbacks( homekit_accessory_t **accessories, homekit_characteristic_change_callback_fn function, void *context ) { for (homekit_accessory_t **accessory_it = accessories; *accessory_it; accessory_it++) { homekit_accessory_t *accessory = *accessory_it; for (homekit_service_t **service_it = accessory->services; *service_it; service_it++) { homekit_service_t *service = *service_it; for (homekit_characteristic_t **ch_it = service->characteristics; *ch_it; ch_it++) { homekit_characteristic_t *ch = *ch_it; homekit_characteristic_remove_notify_callback(ch, function, context); } } } } bool homekit_characteristic_has_notify_callback( const homekit_characteristic_t *ch, homekit_characteristic_change_callback_fn function, void *context ) { homekit_characteristic_change_callback_t *callback = ch->callback; while (callback) { if (callback->function == function && callback->context == context) return true; callback = callback->next; } return false; }
882500.c
/* * uci.c: UCI binding for the switch configuration utility * * Copyright (C) 2009 Felix Fietkau <[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 Foundatio. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <inttypes.h> #include <errno.h> #include <stdint.h> #include <getopt.h> #include <sys/types.h> #include <sys/socket.h> #include <uci.h> #include <linux/types.h> #include <linux/netlink.h> #include <linux/genetlink.h> #include <netlink/netlink.h> #include <netlink/genl/genl.h> #include <netlink/genl/ctrl.h> #include <linux/switch.h> #include "swlib.h" #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) #endif struct swlib_setting { struct switch_attr *attr; const char *name; int port_vlan; const char *val; struct swlib_setting *next; }; struct swlib_setting early_settings[] = { { .name = "reset", .val = "1" }, { .name = "enable_vlan", .val = "1" }, }; static struct swlib_setting *settings; static struct swlib_setting **head; static bool swlib_match_name(struct switch_dev *dev, const char *name) { return (strcmp(name, dev->dev_name) == 0 || strcmp(name, dev->alias) == 0); } static void swlib_map_settings(struct switch_dev *dev, int type, int port_vlan, struct uci_section *s) { struct swlib_setting *setting; struct switch_attr *attr; struct uci_element *e; struct uci_option *o; uci_foreach_element(&s->options, e) { o = uci_to_option(e); if (o->type != UCI_TYPE_STRING) continue; if (!strcmp(e->name, "device")) continue; /* map early settings */ if (type == SWLIB_ATTR_GROUP_GLOBAL) { int i; for (i = 0; i < ARRAY_SIZE(early_settings); i++) { if (strcmp(e->name, early_settings[i].name) != 0) continue; early_settings[i].val = o->v.string; goto skip; } } attr = swlib_lookup_attr(dev, type, e->name); if (!attr) continue; setting = malloc(sizeof(struct swlib_setting)); memset(setting, 0, sizeof(struct swlib_setting)); setting->attr = attr; setting->port_vlan = port_vlan; setting->val = o->v.string; *head = setting; head = &setting->next; skip: continue; } } int swlib_apply_from_uci(struct switch_dev *dev, struct uci_package *p) { struct switch_attr *attr; struct uci_element *e; struct uci_section *s; struct uci_option *o; struct uci_ptr ptr; struct switch_val val; int i; settings = NULL; head = &settings; uci_foreach_element(&p->sections, e) { struct uci_element *n; s = uci_to_section(e); if (strcmp(s->type, "switch") != 0) continue; uci_foreach_element(&s->options, n) { struct uci_option *o = uci_to_option(n); if (strcmp(n->name, "name") != 0) continue; if (o->type != UCI_TYPE_STRING) continue; if (swlib_match_name(dev, o->v.string)) goto found; break; } if (!swlib_match_name(dev, e->name)) continue; goto found; } /* not found */ return -1; found: /* look up available early options, which need to be taken care * of in the correct order */ for (i = 0; i < ARRAY_SIZE(early_settings); i++) { early_settings[i].attr = swlib_lookup_attr(dev, SWLIB_ATTR_GROUP_GLOBAL, early_settings[i].name); } swlib_map_settings(dev, SWLIB_ATTR_GROUP_GLOBAL, 0, s); /* look for port or vlan sections */ uci_foreach_element(&p->sections, e) { struct uci_element *os; s = uci_to_section(e); if (!strcmp(s->type, "switch_vlan")) { char *devn = NULL, *vlan = NULL, *vlan_err = NULL; int vlan_n; uci_foreach_element(&s->options, os) { o = uci_to_option(os); if (o->type != UCI_TYPE_STRING) continue; if (!strcmp(os->name, "device")) { devn = o->v.string; if (!swlib_match_name(dev, devn)) devn = NULL; } else if (!strcmp(os->name, "vlan")) { vlan = o->v.string; } } if (!devn || !vlan || !vlan[0]) continue; vlan_n = strtoul(vlan, &vlan_err, 0); if (vlan_err && vlan_err[0]) continue; swlib_map_settings(dev, SWLIB_ATTR_GROUP_VLAN, vlan_n, s); } } uci_foreach_element(&p->sections, e) { struct uci_element *os; char *devn = NULL, *port = NULL, *port_err = NULL; int port_n; s = uci_to_section(e); if (strcmp(s->type, "switch_port")) continue; uci_foreach_element(&s->options, os) { o = uci_to_option(os); if (o->type != UCI_TYPE_STRING) continue; if (!strcmp(os->name, "device")) { devn = o->v.string; if (!swlib_match_name(dev, devn)) devn = NULL; } else if (!strcmp(os->name, "port")) { port = o->v.string; } } if (!devn || !port || !port[0]) continue; port_n = strtoul(port, &port_err, 0); if (port_err && port_err[0]) continue; swlib_map_settings(dev, SWLIB_ATTR_GROUP_PORT, port_n, s); } for (i = 0; i < ARRAY_SIZE(early_settings); i++) { struct swlib_setting *st = &early_settings[i]; if (!st->attr || !st->val) continue; swlib_set_attr_string(dev, st->attr, st->port_vlan, st->val); } while (settings) { struct swlib_setting *st = settings; swlib_set_attr_string(dev, st->attr, st->port_vlan, st->val); st = st->next; free(settings); settings = st; } /* Apply the config */ attr = swlib_lookup_attr(dev, SWLIB_ATTR_GROUP_GLOBAL, "apply"); if (!attr) return 0; memset(&val, 0, sizeof(val)); swlib_set_attr(dev, attr, &val); return 0; }
953639.c
/*------------------------------------------------------------------------------ * * Copyright (c) 2011-2018, EURid vzw. All rights reserved. * The YADIFA TM software product is provided under the BSD 3-clause license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of EURid 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. * *------------------------------------------------------------------------------ * */ /** @defgroup dnsdbcollection Collections used by the database * @ingroup dnsdb * @brief Functions used to hash a dns formatted string * * Implements the functions used to hash a dns formatted string. * There functions require the call to an initialization function (hash_init); * * @{ */ /*------------------------------------------------------------------------------ * * USE INCLUDES */ #include "dnsdb/dnsdb-config.h" #include <stdlib.h> #include <string.h> #include "dnsdb/hash.h" #define ZDBHTBL_TAG 0x4c42544842445a /* * [-] * [0;9] * [a;z] * * [2D] * [30;38] * [61;7A] * */ /** * * ['0';'9'] + ['A'/'a';'Z'/'z'] + ['-'] = 37 * */ #define ZDB_HASH_TABLE_CHAR_SET_SIZE 37 extern const u32 ZDB_HASH_TABLE[256][ZDB_HASH_TABLE_CHAR_SET_SIZE]; const u32 ZDB_HASH_TABLE_MAP[256]; const u8* WILD_LABEL = (u8*)"\001*"; const hashcode WILD_HASH; static bool hash_init_done = FALSE; /** @brief Initializes the hash functions * * Initializes the hash function */ void hash_init() { u32 i; if(hash_init_done) { return; } hash_init_done = TRUE; /* It's not big deal if it's done more * than once. I will not use a mutex * for this. */ u32* tmp = (u32*)ZDB_HASH_TABLE_MAP; ZEROMEMORY(tmp, sizeof(ZDB_HASH_TABLE_MAP)); tmp['-'] = 0; for(i = '0'; i <= '9'; i++) { tmp[i] = i - (48 - 1); /* one is taken by '-', '0'=48 */ } for(i = 'A'; i <= 'Z'; i++) { tmp[i] = i - (65 - 11); /* eleven are taken by '-' and '0' .. '9', 'A'=65 */ } for(i = 'a'; i <= 'z'; i++) { tmp[i] = i - (97 - 11); /* eleven are taken by '-' and '0' .. '9', 'a'=97 */ } tmp['*'] = 0; tmp['_'] = 0; hashcode* wild_hashp = (hashcode*) & WILD_HASH; *wild_hashp = hash_dnslabel(WILD_LABEL); } /** @brief Compute the hash code of a pascal name * * Compute the hash code of a pascal name. * The function hash_init() MUST be called once first. (This requirement will be lifted later) * An interesting thing about a dnsname label : it's a pascal string. * * @param[in] pascal_name the name in pascal form * * @return the hash code as a 32 bits integer */ hashcode hash_pascalname(const u8* pascal_name) { assert(pascal_name != NULL); u32 idx = 1; /* idx points into the HASH_TABLE */ /* I could initialize it to a hiher value (ie: 255) and * decrease it instead of the current behaviour. * This would allow to put a cpu-cheap limit on the * amount of chars taken in account in the hash computation. */ u32 len = *pascal_name++; u32 hash = ZDB_HASH_TABLE[len][0]; while(len-- > 0) { hash += ZDB_HASH_TABLE[idx++][ZDB_HASH_TABLE_MAP[*pascal_name++]]; } return hash; } /** @brief Compute the hash code of an asciiz name * * Compute the hash code of a pascal name from its asciiz form. * The function hash_init() MUST be called once first. (This requirement will be lifted later) * * @param[in] pascal_name the name in asciiz form * * @return the hash code as a 32 bits integer */ hashcode hash_asciizname(const char* asciiz_name) { assert(asciiz_name != NULL); u32 idx = 1; /* idx points into the HASH_TABLE */ /* I could initialize it to a hiher value (ie: 255) and * decrease it instead of the current behaviour. * This would allow to put a cpu-cheap limit on the * amount of chars taken in account in the hash computation. */ u32 len = (u32)strlen(asciiz_name); u32 hash = ZDB_HASH_TABLE[len][0]; while(len-- > 0) { hash += ZDB_HASH_TABLE[idx++][ZDB_HASH_TABLE_MAP[(u8)(*asciiz_name++)]]; } return hash; } /** @} */ /*----------------------------------------------------------------------------*/
328384.c
/* * Copyright (c) 2013-2015 Freescale Semiconductor, Inc. * Copyright 2016-2019 NXP. * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include "bootloader_common.h" #include "property/property.h" #include "memory/memory.h" #include "packet/command_packet.h" #include "packet/serial_packet.h" #include "bootloader/bl_peripheral.h" #include "bootloader/bl_context.h" #include "bootloader/bl_version.h" #include "utilities/fsl_assert.h" #include <string.h> #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH #include "fsl_flash.h" #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH #include "fsl_device_registers.h" #if BL_FEATURE_QSPI_MODULE #include "qspi.h" #endif // BL_FEATURE_QSPI_MODULE #if BL_FEATURE_CRC_CHECK #include "bootloader/bl_app_crc_check.h" #endif // BL_FEATURE_CRC_CHECK //////////////////////////////////////////////////////////////////////////////// // Declarations //////////////////////////////////////////////////////////////////////////////// #if (defined(__ICCARM__)) // IAR #pragma section = ".intvec" #pragma section = "ApplicationFlash" #pragma section = "ApplicationRam" #if defined(BL_TARGET_RAM) #define __RAM_START ((uint32_t)__section_begin(".intvec")) #else #define __RAM_START ((uint32_t)__section_begin("ApplicationRam")) #endif // #if defined(BL_TARGET_RAM) #define __RAM_END ((uint32_t)__section_end("ApplicationRam") - 1) #define __ROM_START ((uint32_t)__section_begin(".intvec")) #define __ROM_END ((uint32_t)__section_end("ApplicationFlash")) #elif(defined(__CC_ARM)) || (defined(__ARMCC_VERSION)) // MDK extern uint32_t Image$$VECTOR_ROM$$Base[]; extern uint32_t Load$$RW_m_data$$Limit[]; extern char Image$$VECTOR_RAM$$Base[]; extern uint32_t Image$$ARM_LIB_STACK$$ZI$$Limit[]; #define __RAM_START ((uint32_t)Image$$VECTOR_RAM$$Base) #define __RAM_END ((uint32_t)Image$$ARM_LIB_STACK$$ZI$$Limit - 1) #define __ROM_START ((uint32_t)Image$$VECTOR_ROM$$Base) #define __ROM_END ((uint32_t)Load$$RW_m_data$$Limit) #elif(defined(__GNUC__)) // GCC extern uint32_t __VECTOR_RAM[]; extern uint32_t __VECTOR_TABLE[]; extern char __DATA_END[]; extern uint32_t __STACK_TOP[]; #define __RAM_START ((uint32_t)__VECTOR_RAM) #define __RAM_END ((uint32_t)__STACK_TOP - 1) #define __ROM_START ((uint32_t)__VECTOR_TABLE) #define __ROM_END ((uint32_t)__DATA_END) #else #error Unknown toolchain! #endif // __ICCARM__ //////////////////////////////////////////////////////////////////////////////// // Variables //////////////////////////////////////////////////////////////////////////////// //! @brief Storage for property values. property_store_t g_propertyStore; //! @brief Map for external memory property interface. extern const external_memory_property_interface_t g_externalMemPropertyInterfaceMap[]; // See property.h for documentation on this data structure. const property_interface_t g_propertyInterface = { bootloader_property_load_user_config, bootloader_property_init, bootloader_property_get, bootloader_property_set_uint32, &g_propertyStore }; //! @brief Storage for property values computed every time they are read. static uint32_t s_propertyReturnValue; //////////////////////////////////////////////////////////////////////////////// // Prototypes //////////////////////////////////////////////////////////////////////////////// // !@brief Get external memory properties status_t bootloader_get_external_memory_properties(uint32_t memoryId, external_memory_property_store_t *store); //////////////////////////////////////////////////////////////////////////////// // Code //////////////////////////////////////////////////////////////////////////////// // See property.h for documentation on this function. status_t bootloader_property_load_user_config(void) { bootloader_configuration_data_t *config = &g_bootloaderContext.propertyInterface->store->configurationData; #if FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL if (is_in_execute_only_region(kBootloaderConfigAreaAddress, sizeof(bootloader_configuration_data_t))) { memset(config, 0xff, sizeof(bootloader_configuration_data_t)); } else #endif // FSL_FEATURE_FLASH_HAS_ACCESS_CONTROL { // Copy bootloader configuration data from the flash into the property store. memcpy(config, (const void *)kBootloaderConfigAreaAddress, sizeof(bootloader_configuration_data_t)); // Verify tag. If it is invalid, wipe the config data to all 0xff. if (kPropertyStoreTag != config->tag) { memset(config, 0xff, sizeof(bootloader_configuration_data_t)); } } // Update available peripherals based on specific chips update_available_peripherals(); return kStatus_Success; } // See property.h for documentation on this function. status_t bootloader_property_init(void) { property_store_t *propertyStore = g_bootloaderContext.propertyInterface->store; // Fill in default values. propertyStore->bootloaderVersion.name = kBootloader_Version_Name; propertyStore->bootloaderVersion.major = kBootloader_Version_Major; propertyStore->bootloaderVersion.minor = kBootloader_Version_Minor; propertyStore->bootloaderVersion.bugfix = kBootloader_Version_Bugfix; propertyStore->serialProtocolVersion.name = kSerialProtocol_Version_Name; propertyStore->serialProtocolVersion.major = kSerialProtocol_Version_Major; propertyStore->serialProtocolVersion.minor = kSerialProtocol_Version_Minor; propertyStore->serialProtocolVersion.bugfix = kSerialProtocol_Version_Bugfix; propertyStore->targetVersion.name = kTarget_Version_Name; propertyStore->targetVersion.major = kTarget_Version_Major; propertyStore->targetVersion.minor = kTarget_Version_Minor; propertyStore->targetVersion.bugfix = kTarget_Version_Bugfix; propertyStore->verifyWrites = true; propertyStore->availableCommands = kAvailableCommands; #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH /// Initialize flash properties. { g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash0BlockBaseAddr, &propertyStore->flashStartAddress[kFlashIndex_Main]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash0TotalSize, &propertyStore->flashSizeInBytes[kFlashIndex_Main]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash0SectorSize, &propertyStore->flashSectorSize[kFlashIndex_Main]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash0BlockSize, &propertyStore->flashBlockSize[kFlashIndex_Main]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash0BlockCount, &propertyStore->flashBlockCount[kFlashIndex_Main]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash0FacSupport, &propertyStore->flashFacSupport[kFlashIndex_Main]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash0AccessSegmentSize, &propertyStore->flashAccessSegmentSize[kFlashIndex_Main]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash0AccessSegmentCount, &propertyStore->flashAccessSegmentCount[kFlashIndex_Main]); #if BL_HAS_SECONDARY_INTERNAL_FLASH g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash1BlockBaseAddr, &propertyStore->flashStartAddress[kFlashIndex_Secondary]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash1TotalSize, &propertyStore->flashSizeInBytes[kFlashIndex_Secondary]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash1SectorSize, &propertyStore->flashSectorSize[kFlashIndex_Secondary]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash1BlockSize, &propertyStore->flashBlockSize[kFlashIndex_Secondary]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash1BlockCount, &propertyStore->flashBlockCount[kFlashIndex_Secondary]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash1FacSupport, &propertyStore->flashFacSupport[kFlashIndex_Secondary]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash1AccessSegmentSize, &propertyStore->flashAccessSegmentSize[kFlashIndex_Secondary]); g_bootloaderContext.flashDriverInterface->flash_get_property(g_bootloaderContext.allFlashState, kFLASH_PropertyPflash1AccessSegmentCount, &propertyStore->flashAccessSegmentCount[kFlashIndex_Secondary]); #endif #if BL_FEATURE_SUPPORT_DFLASH if (g_bootloaderContext.dflashDriverInterface != NULL) { g_bootloaderContext.dflashDriverInterface->flash_get_property(g_bootloaderContext.dFlashState, kFLEXNVM_PropertyDflashBlockBaseAddr, &propertyStore->flashStartAddress[kFalshIndex_DFlash]); g_bootloaderContext.dflashDriverInterface->flash_get_property(g_bootloaderContext.dFlashState, kFLEXNVM_PropertyDflashTotalSize, &propertyStore->flashSizeInBytes[kFalshIndex_DFlash]); g_bootloaderContext.dflashDriverInterface->flash_get_property(g_bootloaderContext.dFlashState, kFLEXNVM_PropertyDflashSectorSize, &propertyStore->flashSectorSize[kFalshIndex_DFlash]); g_bootloaderContext.dflashDriverInterface->flash_get_property(g_bootloaderContext.dFlashState, kFLEXNVM_PropertyDflashBlockSize, &propertyStore->flashBlockSize[kFalshIndex_DFlash]); g_bootloaderContext.dflashDriverInterface->flash_get_property(g_bootloaderContext.dFlashState, kFLEXNVM_PropertyDflashBlockCount, &propertyStore->flashBlockCount[kFalshIndex_DFlash]); // g_bootloaderContext.dflashDriverInterface->flash_get_property(g_bootloaderContext.dFlashState, // kFLEXNVM_PropertyFlexRamBlockBaseAddr, // &propertyStore->flashSectorSize[kFalshIndex_DFlash]); // g_bootloaderContext.dflashDriverInterface->flash_get_property(g_bootloaderContext.dFlashState, // kFLEXNVM_PropertyFlexRamTotalSize, // &propertyStore->flashSectorSize[kFalshIndex_DFlash]); // g_bootloaderContext.dflashDriverInterface->flash_get_property(g_bootloaderContext.dFlashState, // kFLEXNVM_PropertyEepromTotalSize, // &propertyStore->flashSectorSize[kFalshIndex_DFlash]); } #endif // BL_FEATURE_SUPPORT_DFLASH } #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH // Fill in reserved regions. //! @todo Support other tool chain uint32_t flashStart = 0; uint32_t flashEnd = 0; uint32_t ramStart = 0; uint32_t ramEnd = 0; #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH #if !BL_TARGET_FLASH flashStart = (&g_bootloaderContext.memoryMap[kIndexFlashArray])->startAddress; flashEnd = (&g_bootloaderContext.memoryMap[kIndexFlashArray])->startAddress; #else flashStart = __ROM_START; flashEnd = __ROM_END; assert(flashEnd); // Force flash erase size alignment. // Note: Assume that flash-resident bootloader is always in Main flash. flashStart = ALIGN_DOWN(flashStart, propertyStore->flashSectorSize[kFlashIndex_Main]); flashEnd = ALIGN_UP(flashEnd, propertyStore->flashSectorSize[kFlashIndex_Main]) - 1; #endif #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH ramStart = __RAM_START; ramEnd = __RAM_END; assert(ramEnd); propertyStore->reservedRegions[kProperty_FlashReservedRegionIndex].startAddress = flashStart; propertyStore->reservedRegions[kProperty_FlashReservedRegionIndex].endAddress = flashEnd; propertyStore->reservedRegions[kProperty_RamReservedRegionIndex].startAddress = ramStart; propertyStore->reservedRegions[kProperty_RamReservedRegionIndex].endAddress = ramEnd; // Fill in available peripherals array. const peripheral_descriptor_t *peripherals = g_bootloaderContext.allPeripherals; propertyStore->availablePeripherals = 0; for (uint32_t i = 0; peripherals[i].typeMask != 0; ++i) { // Check that the peripheral is enabled in the user configuration data. if (propertyStore->configurationData.enabledPeripherals & peripherals[i].typeMask) { propertyStore->availablePeripherals |= peripherals[i].typeMask; } } // Fill in unique device id value. // Different series have different length of UID (K series=128 bits, KL series=80 bits) #if (!FSL_FEATURE_SIM_HAS_NO_UID) && defined(SIM) #if defined(SIM_UIDH) | defined(SIM_UIDH_UID) #if defined(SIM_UIDM_UID) propertyStore->UniqueDeviceId.uid[2] = SIM->UIDH; #else propertyStore->UniqueDeviceId.uid[3] = SIM->UIDH; #endif #endif #if defined(SIM_UIDM_UID) propertyStore->UniqueDeviceId.uid[1] = SIM->UIDM; #else propertyStore->UniqueDeviceId.uid[2] = SIM->UIDMH; propertyStore->UniqueDeviceId.uid[1] = SIM->UIDML; #endif // defined(SIM_UIDM) propertyStore->UniqueDeviceId.uid[0] = SIM->UIDL; #endif // #if !FSL_FEATURE_SIM_HAS_NO_UID // Set address range of RAM in property interface const memory_map_entry_t *map = (memory_map_entry_t *)&g_bootloaderContext.memoryMap[kIndexSRAM]; propertyStore->ramStartAddress[kPropertyIndex_SRAM] = map->startAddress; propertyStore->ramSizeInBytes[kPropertyIndex_SRAM] = map->endAddress - map->startAddress + 1; #if defined(K28F15_SERIES) map = (memory_map_entry_t *)&g_bootloaderContext.memoryMap[kIndexOCRAM]; propertyStore->ramStartAddress[kPropertyIndex_OCRAM] = map->startAddress; propertyStore->ramSizeInBytes[kPropertyIndex_OCRAM] = map->endAddress - map->startAddress + 1; #elif defined(KV58F24_SERIES) map = (memory_map_entry_t *)&g_bootloaderContext.memoryMap[kIndexDTCM]; propertyStore->ramStartAddress[kPropertyIndex_DTCM] = map->startAddress; propertyStore->ramSizeInBytes[kPropertyIndex_DTCM] = map->endAddress - map->startAddress + 1; map = (memory_map_entry_t *)&g_bootloaderContext.memoryMap[kIndexOCRAM]; propertyStore->ramStartAddress[kPropertyIndex_OCRAM] = map->startAddress; if (map->startAddress == map->endAddress) { propertyStore->ramSizeInBytes[kPropertyIndex_OCRAM] = 0; } else { propertyStore->ramSizeInBytes[kPropertyIndex_OCRAM] = map->endAddress - map->startAddress + 1; } #endif // defined(K28F15_SERIES) #if BL_FEATURE_CRC_CHECK // Initialize crc check status property based on BCA related fields. init_crc_check_status(propertyStore); #endif #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH // Fill in default margin level. propertyStore->flashReadMargin = (uint32_t)kFTFx_MarginValueUser; #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH #if BL_FEATURE_QSPI_MODULE propertyStore->qspiInitStatus = get_qspi_otfad_init_status(); #endif // BL_FEATURE_QSPI_MODULE return kStatus_Success; } // See property.h for documentation on this function. status_t bootloader_property_get(uint8_t tag, uint32_t id, const void **value, uint32_t *valueSize) { property_store_t *propertyStore = g_bootloaderContext.propertyInterface->store; #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH uint32_t flashIndex = kFlashIndex_Main; #if BL_HAS_SECONDARY_INTERNAL_FLASH if (id < kFLASHCount) { flashIndex = id; } #endif // BL_HAS_SECONDARY_INTERNAL_FLASH #if BL_FEATURE_SUPPORT_DFLASH if (g_bootloaderContext.dflashDriverInterface != NULL) { flashIndex = id; } #endif // BL_FEATURE_SUPPORT_DFLASH #endif // !BL_FEATURE_HAS_NO_INTERNAL_FLASH // Set default value size, may be modified below. uint32_t returnSize = sizeof(uint32_t); const void *returnValue; switch (tag) { case kPropertyTag_BootloaderVersion: returnValue = &propertyStore->bootloaderVersion.version; break; case kPropertyTag_AvailablePeripherals: returnValue = &propertyStore->availablePeripherals; break; #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_FlashStartAddress: returnValue = &propertyStore->flashStartAddress[flashIndex]; break; case kPropertyTag_FlashSizeInBytes: returnValue = &propertyStore->flashSizeInBytes[flashIndex]; break; case kPropertyTag_FlashSectorSize: returnValue = &propertyStore->flashSectorSize[flashIndex]; break; case kPropertyTag_FlashBlockCount: returnValue = &propertyStore->flashBlockCount[flashIndex]; break; #endif // !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_RAMStartAddress: #if defined(KV58F24_SERIES) || defined(K28F15_SERIES) || defined(BL_FEATURE_MULTI_SRAM_SECTIONS) if (id >= kRAMCount) { returnValue = &propertyStore->ramStartAddress[0]; } else { returnValue = &propertyStore->ramStartAddress[id]; } #else returnValue = &propertyStore->ramStartAddress[0]; #endif // #if defined(KV58F24_SERIES) || defined(K28F15_SERIES) || defined(BL_FEATURE_MULTI_SRAM_SECTIONS) break; case kPropertyTag_RAMSizeInBytes: #if defined(KV58F24_SERIES) || defined(K28F15_SERIES) || defined(BL_FEATURE_MULTI_SRAM_SECTIONS) if (id >= kRAMCount) { returnValue = &propertyStore->ramSizeInBytes[0]; } else { returnValue = &propertyStore->ramSizeInBytes[id]; } #else returnValue = &propertyStore->ramSizeInBytes[0]; #endif // #if defined(KV58F24_SERIES) || defined(K28F15_SERIES) || defined(BL_FEATURE_MULTI_SRAM_SECTIONS) break; case kPropertyTag_AvailableCommands: returnValue = &propertyStore->availableCommands; break; #if BL_FEATURE_CRC_CHECK case kPropertyTag_CrcCheckStatus: returnValue = &propertyStore->crcCheckStatus; break; #endif // else falls through to unknown #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_VerifyWrites: returnValue = &propertyStore->verifyWrites; break; #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_MaxPacketSize: // Read the max packet size from the active peripheral. s_propertyReturnValue = g_bootloaderContext.activePeripheral->packetInterface->getMaxPacketSize( g_bootloaderContext.activePeripheral); returnValue = &s_propertyReturnValue; break; case kPropertyTag_ReservedRegions: returnSize = sizeof(propertyStore->reservedRegions); returnValue = propertyStore->reservedRegions; break; #if !FSL_FEATURE_SIM_HAS_NO_SDID && defined(SIM) case kPropertyTag_SystemDeviceId: s_propertyReturnValue = SIM->SDID; returnValue = &s_propertyReturnValue; break; #endif // #if !FSL_FEATURE_SIM_HAS_NO_SDID #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_FlashSecurityState: { // Note: Both Main and Secondary flash share the same security state // So it doesn't matter what index of allFlashState[] we use for this FLASH API. ftfx_security_state_t securityState; g_bootloaderContext.flashDriverInterface->flash_get_security_state( g_bootloaderContext.allFlashState, &securityState); s_propertyReturnValue = (securityState != kFTFx_SecurityStateNotSecure); returnValue = &s_propertyReturnValue; break; } #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH #if !FSL_FEATURE_SIM_HAS_NO_UID case kPropertyTag_UniqueDeviceId: returnSize = sizeof(propertyStore->UniqueDeviceId); returnValue = &propertyStore->UniqueDeviceId; break; #endif // #if !FSL_FEATURE_SIM_HAS_NO_UID #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_FacSupport: returnSize = sizeof(propertyStore->flashFacSupport[flashIndex]); returnValue = &propertyStore->flashFacSupport[flashIndex]; break; case kPropertyTag_FlashAccessSegmentSize: returnSize = sizeof(propertyStore->flashAccessSegmentSize[flashIndex]); returnValue = &propertyStore->flashAccessSegmentSize[flashIndex]; break; case kPropertyTag_FlashAccessSegmentCount: returnSize = sizeof(propertyStore->flashAccessSegmentCount[flashIndex]); returnValue = &propertyStore->flashAccessSegmentCount[flashIndex]; break; case kPropertyTag_FlashReadMargin: // Note: Currently both Main and Secondary flash share the same flash read margin returnSize = sizeof(propertyStore->flashReadMargin); returnValue = &propertyStore->flashReadMargin; break; #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH #if BL_FEATURE_QSPI_MODULE case kPropertyTag_QspiInitStatus: returnValue = &propertyStore->qspiInitStatus; break; #endif // else falls through to unknown case kPropertyTag_TargetVersion: returnValue = &propertyStore->targetVersion.version; break; #if BL_FEATURE_EXTERNAL_MEMORY_PROPERTY case kPropertyTag_ExternalMemoryAttributes: { status_t status = bootloader_get_external_memory_properties(id, &propertyStore->externalMemoryPropertyStore); if (status != kStatus_Success) { return status; } } returnSize = sizeof(propertyStore->externalMemoryPropertyStore); returnValue = &propertyStore->externalMemoryPropertyStore; break; #endif // BL_FEATURE_EXTERNAL_MEMORY_PROPERTY #if BL_FEATURE_RELIABLE_UPDATE case kPropertyTag_ReliableUpdateStatus: returnValue = &propertyStore->reliableUpdateStatus; break; #endif // BL_FEATURE_RELIABLE_UPDATE default: return kStatus_UnknownProperty; } // Set the return size. if (valueSize) { *valueSize = returnSize; } // Set the return value if (value) { *value = returnValue; } return kStatus_Success; } // See property.h for documentation on this function. status_t bootloader_property_set_uint32(uint8_t tag, uint32_t value) { #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH property_store_t *propertyStore = g_bootloaderContext.propertyInterface->store; #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH switch (tag) { #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_VerifyWrites: if (value != 0 && value != 1) { return kStatus_InvalidPropertyValue; } propertyStore->verifyWrites = value; return kStatus_Success; case kPropertyTag_FlashReadMargin: if (value >= kFTFx_MarginValueInvalid) { return kStatus_InvalidPropertyValue; } propertyStore->flashReadMargin = value; return kStatus_Success; #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_BootloaderVersion: case kPropertyTag_AvailablePeripherals: #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_FlashStartAddress: case kPropertyTag_FlashSizeInBytes: case kPropertyTag_FlashSectorSize: case kPropertyTag_FlashBlockCount: #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_RAMStartAddress: case kPropertyTag_RAMSizeInBytes: case kPropertyTag_AvailableCommands: #if BL_FEATURE_CRC_CHECK case kPropertyTag_CrcCheckStatus: #endif #if BL_FEATURE_QSPI_MODULE case kPropertyTag_QspiInitStatus: #endif #if BL_FEATURE_EXTERNAL_MEMORY_PROPERTY case kPropertyTag_ExternalMemoryAttributes: #endif // BL_FEATURE_EXTERNAL_MEMORY_PROPERTY #if BL_FEATURE_RELIABLE_UPDATE case kPropertyTag_ReliableUpdateStatus: #endif // BL_FEATURE_RELIABLE_UPDATE case kPropertyTag_MaxPacketSize: case kPropertyTag_ReservedRegions: case kPropertyTag_SystemDeviceId: #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_FlashSecurityState: #endif case kPropertyTag_UniqueDeviceId: #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_FacSupport: case kPropertyTag_FlashAccessSegmentSize: case kPropertyTag_FlashAccessSegmentCount: #endif // #if !BL_FEATURE_HAS_NO_INTERNAL_FLASH case kPropertyTag_TargetVersion: return kStatus_ReadOnlyProperty; default: return kStatus_UnknownProperty; } } #if BL_FEATURE_EXTERNAL_MEMORY_PROPERTY status_t bootloader_get_external_memory_properties(uint32_t memoryId, external_memory_property_store_t *store) { extern const external_memory_property_interface_t g_externalMemPropertyInterfaceMap[]; // Find external memory property interface map. const external_memory_property_interface_t *map = &g_externalMemPropertyInterfaceMap[0]; while (map && map->get) { if (map->memoryId == memoryId) { break; } map++; } if (map->get == NULL) { return kStatus_InvalidArgument; } external_memory_property_store_t propertyStore = { 0 }; uint32_t memoryInitStatus; map->get(kExternalMemoryPropertyTag_InitStatus, &memoryInitStatus); if (memoryInitStatus != kStatus_Success) { return memoryInitStatus; } uint32_t *property = (uint32_t *)&propertyStore.startAddress; propertyStore.availableAttributesFlag = 0; for (uint32_t tag = kExternalMemoryPropertyTag_Start; tag <= kExternalMemoryPropertyTag_End; tag++) { uint32_t tmp = 0; status_t status = map->get(tag, &tmp); if (status == kStatus_Success) { *property = tmp; propertyStore.availableAttributesFlag |= 1 << (tag - 1); } else { *property = 0; } property++; } memcpy(store, &propertyStore, sizeof(propertyStore)); return kStatus_Success; } #endif // BL_FEATURE_EXTERNAL_MEMORY_PROPERTY //////////////////////////////////////////////////////////////////////////////// // EOF
686013.c
// averaging past 32k samples // by fetching every 8k samples // for processing `csdr fmdemod_atan_cf/amdemod_cf` output // usage: // cc -O3 -o valuedump2 valuedump2.c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <math.h> #include <stdbool.h> #define SAMPLES (8000) int main(int argc, char* argv[]) { union { unsigned char byte[4]; float f; } v; size_t n; double d, ds[4], dav, av; float s[SAMPLES]; unsigned int p, q; uint64_t count; bool dsq_init = false; // Initialize float/double work area for (q = 0; q < SAMPLES; q++) { s[q] = 0.0; } p = 0; count = 0; while ((n = fread(&s, sizeof(float), SAMPLES, stdin)) > 0) { d = 0.0; for (size_t i = 0; i < n; i++) { d += (double)s[i]; } dav = d / (double)n; if (!dsq_init) { for (q = 0; q < 4; q++) { ds[q] = dav; } dsq_init = true; } ds[p] = dav; p++; if (p > 3) { p = 0; } av = (ds[0] + ds[1] + ds[2] + ds[3]) / 4.0; fprintf(stdout, "%" PRIu64 " %16.8f\n", count, av); count++; } exit(0); }
189718.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) 2001-2002 by NaN Holding BV. * All rights reserved. */ /** \file * \ingroup edinterface */ #include <math.h> #include <string.h> #include "DNA_color_types.h" #include "DNA_screen_types.h" #include "DNA_movieclip_types.h" #include "DNA_curveprofile_types.h" #include "BLI_math.h" #include "BLI_rect.h" #include "BLI_string.h" #include "BLI_utildefines.h" #include "BLI_polyfill_2d.h" #include "MEM_guardedalloc.h" #include "BKE_colorband.h" #include "BKE_colortools.h" #include "BKE_node.h" #include "BKE_tracking.h" #include "BKE_curveprofile.h" #include "IMB_imbuf.h" #include "IMB_imbuf_types.h" #include "IMB_colormanagement.h" #include "BIF_glutil.h" #include "BLF_api.h" #include "GPU_batch.h" #include "GPU_batch_presets.h" #include "GPU_immediate.h" #include "GPU_immediate_util.h" #include "GPU_matrix.h" #include "GPU_state.h" #include "UI_interface.h" /* own include */ #include "interface_intern.h" static int roundboxtype = UI_CNR_ALL; void UI_draw_roundbox_corner_set(int type) { /* Not sure the roundbox function is the best place to change this * if this is undone, it's not that big a deal, only makes curves edges * square for the */ roundboxtype = type; } #if 0 /* unused */ int UI_draw_roundbox_corner_get(void) { return roundboxtype; } #endif void UI_draw_roundbox_3ubAlpha(bool filled, float minx, float miny, float maxx, float maxy, float rad, const uchar col[3], uchar alpha) { float colv[4]; colv[0] = ((float)col[0]) / 255; colv[1] = ((float)col[1]) / 255; colv[2] = ((float)col[2]) / 255; colv[3] = ((float)alpha) / 255; UI_draw_roundbox_4fv(filled, minx, miny, maxx, maxy, rad, colv); } void UI_draw_roundbox_3fvAlpha(bool filled, float minx, float miny, float maxx, float maxy, float rad, const float col[3], float alpha) { float colv[4]; colv[0] = col[0]; colv[1] = col[1]; colv[2] = col[2]; colv[3] = alpha; UI_draw_roundbox_4fv(filled, minx, miny, maxx, maxy, rad, colv); } void UI_draw_roundbox_aa( bool filled, float minx, float miny, float maxx, float maxy, float rad, const float color[4]) { uiWidgetBaseParameters widget_params = { .recti.xmin = minx, .recti.ymin = miny, .recti.xmax = maxx, .recti.ymax = maxy, .radi = rad, .round_corners[0] = (roundboxtype & UI_CNR_BOTTOM_LEFT) ? 1.0f : 0.0f, .round_corners[1] = (roundboxtype & UI_CNR_BOTTOM_RIGHT) ? 1.0f : 0.0f, .round_corners[2] = (roundboxtype & UI_CNR_TOP_RIGHT) ? 1.0f : 0.0f, .round_corners[3] = (roundboxtype & UI_CNR_TOP_LEFT) ? 1.0f : 0.0f, .color_inner1[0] = color[0], .color_inner2[0] = color[0], .color_inner1[1] = color[1], .color_inner2[1] = color[1], .color_inner1[2] = color[2], .color_inner2[2] = color[2], .color_inner1[3] = color[3], .color_inner2[3] = color[3], .alpha_discard = 1.0f, }; GPU_blend(true); if (filled) { /* plain antialiased filled box */ widget_params.color_inner1[3] *= 0.125f; widget_params.color_inner2[3] *= 0.125f; /* WATCH: This is assuming the ModelViewProjectionMatrix is area pixel space. * If it has been scaled, then it's no longer valid. */ GPUBatch *batch = ui_batch_roundbox_get(filled, true); GPU_batch_program_set_builtin(batch, GPU_SHADER_2D_WIDGET_BASE); GPU_batch_uniform_4fv_array(batch, "parameters", 11, (float *)&widget_params); GPU_batch_draw(batch); } else { /* plain antialiased unfilled box */ GPU_line_smooth(true); GPUBatch *batch = ui_batch_roundbox_get(filled, false); GPU_batch_program_set_builtin(batch, GPU_SHADER_2D_WIDGET_BASE); GPU_batch_uniform_4fv_array(batch, "parameters", 11, (float *)&widget_params); GPU_batch_draw(batch); GPU_line_smooth(false); } GPU_blend(false); } void UI_draw_roundbox_4fv( bool filled, float minx, float miny, float maxx, float maxy, float rad, const float col[4]) { #if 0 float vec[7][2] = { {0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}, }; int a; GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); /* mult */ for (a = 0; a < 7; a++) { mul_v2_fl(vec[a], rad); } uint vert_len = 0; vert_len += (roundboxtype & UI_CNR_BOTTOM_RIGHT) ? 9 : 1; vert_len += (roundboxtype & UI_CNR_TOP_RIGHT) ? 9 : 1; vert_len += (roundboxtype & UI_CNR_TOP_LEFT) ? 9 : 1; vert_len += (roundboxtype & UI_CNR_BOTTOM_LEFT) ? 9 : 1; immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor4fv(col); immBegin(filled ? GPU_PRIM_TRI_FAN : GPU_PRIM_LINE_LOOP, vert_len); /* start with corner right-bottom */ if (roundboxtype & UI_CNR_BOTTOM_RIGHT) { immVertex2f(pos, maxx - rad, miny); for (a = 0; a < 7; a++) { immVertex2f(pos, maxx - rad + vec[a][0], miny + vec[a][1]); } immVertex2f(pos, maxx, miny + rad); } else { immVertex2f(pos, maxx, miny); } /* corner right-top */ if (roundboxtype & UI_CNR_TOP_RIGHT) { immVertex2f(pos, maxx, maxy - rad); for (a = 0; a < 7; a++) { immVertex2f(pos, maxx - vec[a][1], maxy - rad + vec[a][0]); } immVertex2f(pos, maxx - rad, maxy); } else { immVertex2f(pos, maxx, maxy); } /* corner left-top */ if (roundboxtype & UI_CNR_TOP_LEFT) { immVertex2f(pos, minx + rad, maxy); for (a = 0; a < 7; a++) { immVertex2f(pos, minx + rad - vec[a][0], maxy - vec[a][1]); } immVertex2f(pos, minx, maxy - rad); } else { immVertex2f(pos, minx, maxy); } /* corner left-bottom */ if (roundboxtype & UI_CNR_BOTTOM_LEFT) { immVertex2f(pos, minx, miny + rad); for (a = 0; a < 7; a++) { immVertex2f(pos, minx + vec[a][1], miny + rad - vec[a][0]); } immVertex2f(pos, minx + rad, miny); } else { immVertex2f(pos, minx, miny); } immEnd(); immUnbindProgram(); #endif uiWidgetBaseParameters widget_params = { .recti.xmin = minx, .recti.ymin = miny, .recti.xmax = maxx, .recti.ymax = maxy, .radi = rad, .round_corners[0] = (roundboxtype & UI_CNR_BOTTOM_LEFT) ? 1.0f : 0.0f, .round_corners[1] = (roundboxtype & UI_CNR_BOTTOM_RIGHT) ? 1.0f : 0.0f, .round_corners[2] = (roundboxtype & UI_CNR_TOP_RIGHT) ? 1.0f : 0.0f, .round_corners[3] = (roundboxtype & UI_CNR_TOP_LEFT) ? 1.0f : 0.0f, .color_inner1[0] = col[0], .color_inner2[0] = col[0], .color_inner1[1] = col[1], .color_inner2[1] = col[1], .color_inner1[2] = col[2], .color_inner2[2] = col[2], .color_inner1[3] = col[3], .color_inner2[3] = col[3], .alpha_discard = 1.0f, }; GPUBatch *batch = ui_batch_roundbox_get(filled, false); GPU_batch_program_set_builtin(batch, GPU_SHADER_2D_WIDGET_BASE); GPU_batch_uniform_4fv_array(batch, "parameters", 11, (float *)&widget_params); GPU_batch_draw(batch); } #if 0 static void round_box_shade_col(uint attr, const float col1[3], float const col2[3], const float fac) { float col[4] = { fac * col1[0] + (1.0f - fac) * col2[0], fac * col1[1] + (1.0f - fac) * col2[1], fac * col1[2] + (1.0f - fac) * col2[2], 1.0f, }; immAttr4fv(attr, col); } #endif /* linear horizontal shade within button or in outline */ /* view2d scrollers use it */ void UI_draw_roundbox_shade_x(bool filled, float minx, float miny, float maxx, float maxy, float rad, float shadetop, float shadedown, const float col[4]) { #if 0 float vec[7][2] = { {0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}, }; const float div = maxy - miny; const float idiv = 1.0f / div; float coltop[3], coldown[3]; int vert_count = 0; int a; GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); uint color = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 4, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR); /* mult */ for (a = 0; a < 7; a++) { mul_v2_fl(vec[a], rad); } /* 'shade' defines strength of shading */ coltop[0] = min_ff(1.0f, col[0] + shadetop); coltop[1] = min_ff(1.0f, col[1] + shadetop); coltop[2] = min_ff(1.0f, col[2] + shadetop); coldown[0] = max_ff(0.0f, col[0] + shadedown); coldown[1] = max_ff(0.0f, col[1] + shadedown); coldown[2] = max_ff(0.0f, col[2] + shadedown); vert_count += (roundboxtype & UI_CNR_BOTTOM_RIGHT) ? 9 : 1; vert_count += (roundboxtype & UI_CNR_TOP_RIGHT) ? 9 : 1; vert_count += (roundboxtype & UI_CNR_TOP_LEFT) ? 9 : 1; vert_count += (roundboxtype & UI_CNR_BOTTOM_LEFT) ? 9 : 1; immBegin(filled ? GPU_PRIM_TRI_FAN : GPU_PRIM_LINE_LOOP, vert_count); /* start with corner right-bottom */ if (roundboxtype & UI_CNR_BOTTOM_RIGHT) { round_box_shade_col(color, coltop, coldown, 0.0); immVertex2f(pos, maxx - rad, miny); for (a = 0; a < 7; a++) { round_box_shade_col(color, coltop, coldown, vec[a][1] * idiv); immVertex2f(pos, maxx - rad + vec[a][0], miny + vec[a][1]); } round_box_shade_col(color, coltop, coldown, rad * idiv); immVertex2f(pos, maxx, miny + rad); } else { round_box_shade_col(color, coltop, coldown, 0.0); immVertex2f(pos, maxx, miny); } /* corner right-top */ if (roundboxtype & UI_CNR_TOP_RIGHT) { round_box_shade_col(color, coltop, coldown, (div - rad) * idiv); immVertex2f(pos, maxx, maxy - rad); for (a = 0; a < 7; a++) { round_box_shade_col(color, coltop, coldown, (div - rad + vec[a][1]) * idiv); immVertex2f(pos, maxx - vec[a][1], maxy - rad + vec[a][0]); } round_box_shade_col(color, coltop, coldown, 1.0); immVertex2f(pos, maxx - rad, maxy); } else { round_box_shade_col(color, coltop, coldown, 1.0); immVertex2f(pos, maxx, maxy); } /* corner left-top */ if (roundboxtype & UI_CNR_TOP_LEFT) { round_box_shade_col(color, coltop, coldown, 1.0); immVertex2f(pos, minx + rad, maxy); for (a = 0; a < 7; a++) { round_box_shade_col(color, coltop, coldown, (div - vec[a][1]) * idiv); immVertex2f(pos, minx + rad - vec[a][0], maxy - vec[a][1]); } round_box_shade_col(color, coltop, coldown, (div - rad) * idiv); immVertex2f(pos, minx, maxy - rad); } else { round_box_shade_col(color, coltop, coldown, 1.0); immVertex2f(pos, minx, maxy); } /* corner left-bottom */ if (roundboxtype & UI_CNR_BOTTOM_LEFT) { round_box_shade_col(color, coltop, coldown, rad * idiv); immVertex2f(pos, minx, miny + rad); for (a = 0; a < 7; a++) { round_box_shade_col(color, coltop, coldown, (rad - vec[a][1]) * idiv); immVertex2f(pos, minx + vec[a][1], miny + rad - vec[a][0]); } round_box_shade_col(color, coltop, coldown, 0.0); immVertex2f(pos, minx + rad, miny); } else { round_box_shade_col(color, coltop, coldown, 0.0); immVertex2f(pos, minx, miny); } immEnd(); immUnbindProgram(); #endif uiWidgetBaseParameters widget_params = { .recti.xmin = minx, .recti.ymin = miny, .recti.xmax = maxx, .recti.ymax = maxy, .radi = rad, .round_corners[0] = (roundboxtype & UI_CNR_BOTTOM_LEFT) ? 1.0f : 0.0f, .round_corners[1] = (roundboxtype & UI_CNR_BOTTOM_RIGHT) ? 1.0f : 0.0f, .round_corners[2] = (roundboxtype & UI_CNR_TOP_RIGHT) ? 1.0f : 0.0f, .round_corners[3] = (roundboxtype & UI_CNR_TOP_LEFT) ? 1.0f : 0.0f, .color_inner1[0] = min_ff(1.0f, col[0] + shadetop), .color_inner2[0] = max_ff(0.0f, col[0] + shadedown), .color_inner1[1] = min_ff(1.0f, col[1] + shadetop), .color_inner2[1] = max_ff(0.0f, col[1] + shadedown), .color_inner1[2] = min_ff(1.0f, col[2] + shadetop), .color_inner2[2] = max_ff(0.0f, col[2] + shadedown), .color_inner1[3] = 1.0f, .color_inner2[3] = 1.0f, .alpha_discard = 1.0f, }; GPUBatch *batch = ui_batch_roundbox_get(filled, false); GPU_batch_program_set_builtin(batch, GPU_SHADER_2D_WIDGET_BASE); GPU_batch_uniform_4fv_array(batch, "parameters", 11, (float *)&widget_params); GPU_batch_draw(batch); } #if 0 /* unused */ /* linear vertical shade within button or in outline */ /* view2d scrollers use it */ void UI_draw_roundbox_shade_y(bool filled, float minx, float miny, float maxx, float maxy, float rad, float shadeleft, float shaderight, const float col[4]) { float vec[7][2] = { {0.195, 0.02}, {0.383, 0.067}, {0.55, 0.169}, {0.707, 0.293}, {0.831, 0.45}, {0.924, 0.617}, {0.98, 0.805}, }; const float div = maxx - minx; const float idiv = 1.0f / div; float colLeft[3], colRight[3]; int vert_count = 0; int a; /* mult */ for (a = 0; a < 7; a++) { mul_v2_fl(vec[a], rad); } GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); uint color = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 4, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR); /* 'shade' defines strength of shading */ colLeft[0] = min_ff(1.0f, col[0] + shadeleft); colLeft[1] = min_ff(1.0f, col[1] + shadeleft); colLeft[2] = min_ff(1.0f, col[2] + shadeleft); colRight[0] = max_ff(0.0f, col[0] + shaderight); colRight[1] = max_ff(0.0f, col[1] + shaderight); colRight[2] = max_ff(0.0f, col[2] + shaderight); vert_count += (roundboxtype & UI_CNR_BOTTOM_RIGHT) ? 9 : 1; vert_count += (roundboxtype & UI_CNR_TOP_RIGHT) ? 9 : 1; vert_count += (roundboxtype & UI_CNR_TOP_LEFT) ? 9 : 1; vert_count += (roundboxtype & UI_CNR_BOTTOM_LEFT) ? 9 : 1; immBegin(filled ? GPU_PRIM_TRI_FAN : GPU_PRIM_LINE_LOOP, vert_count); /* start with corner right-bottom */ if (roundboxtype & UI_CNR_BOTTOM_RIGHT) { round_box_shade_col(color, colLeft, colRight, 0.0); immVertex2f(pos, maxx - rad, miny); for (a = 0; a < 7; a++) { round_box_shade_col(color, colLeft, colRight, vec[a][0] * idiv); immVertex2f(pos, maxx - rad + vec[a][0], miny + vec[a][1]); } round_box_shade_col(color, colLeft, colRight, rad * idiv); immVertex2f(pos, maxx, miny + rad); } else { round_box_shade_col(color, colLeft, colRight, 0.0); immVertex2f(pos, maxx, miny); } /* corner right-top */ if (roundboxtype & UI_CNR_TOP_RIGHT) { round_box_shade_col(color, colLeft, colRight, 0.0); immVertex2f(pos, maxx, maxy - rad); for (a = 0; a < 7; a++) { round_box_shade_col(color, colLeft, colRight, (div - rad - vec[a][0]) * idiv); immVertex2f(pos, maxx - vec[a][1], maxy - rad + vec[a][0]); } round_box_shade_col(color, colLeft, colRight, (div - rad) * idiv); immVertex2f(pos, maxx - rad, maxy); } else { round_box_shade_col(color, colLeft, colRight, 0.0); immVertex2f(pos, maxx, maxy); } /* corner left-top */ if (roundboxtype & UI_CNR_TOP_LEFT) { round_box_shade_col(color, colLeft, colRight, (div - rad) * idiv); immVertex2f(pos, minx + rad, maxy); for (a = 0; a < 7; a++) { round_box_shade_col(color, colLeft, colRight, (div - rad + vec[a][0]) * idiv); immVertex2f(pos, minx + rad - vec[a][0], maxy - vec[a][1]); } round_box_shade_col(color, colLeft, colRight, 1.0); immVertex2f(pos, minx, maxy - rad); } else { round_box_shade_col(color, colLeft, colRight, 1.0); immVertex2f(pos, minx, maxy); } /* corner left-bottom */ if (roundboxtype & UI_CNR_BOTTOM_LEFT) { round_box_shade_col(color, colLeft, colRight, 1.0); immVertex2f(pos, minx, miny + rad); for (a = 0; a < 7; a++) { round_box_shade_col(color, colLeft, colRight, (vec[a][0]) * idiv); immVertex2f(pos, minx + vec[a][1], miny + rad - vec[a][0]); } round_box_shade_col(color, colLeft, colRight, 1.0); immVertex2f(pos, minx + rad, miny); } else { round_box_shade_col(color, colLeft, colRight, 1.0); immVertex2f(pos, minx, miny); } immEnd(); immUnbindProgram(); } #endif /* unused */ void UI_draw_text_underline(int pos_x, int pos_y, int len, int height, const float color[4]) { int ofs_y = 4 * U.pixelsize; GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_I32, 2, GPU_FETCH_INT_TO_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor4fv(color); immRecti(pos, pos_x, pos_y - ofs_y, pos_x + len, pos_y - ofs_y + (height * U.pixelsize)); immUnbindProgram(); } /* ************** SPECIAL BUTTON DRAWING FUNCTIONS ************* */ /* based on UI_draw_roundbox_gl_mode, * check on making a version which allows us to skip some sides */ void ui_draw_but_TAB_outline(const rcti *rect, float rad, uchar highlight[3], uchar highlight_fade[3]) { GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); uint col = GPU_vertformat_attr_add(format, "color", GPU_COMP_U8, 3, GPU_FETCH_INT_TO_FLOAT_UNIT); /* add a 1px offset, looks nicer */ const int minx = rect->xmin + U.pixelsize, maxx = rect->xmax - U.pixelsize; const int miny = rect->ymin + U.pixelsize, maxy = rect->ymax - U.pixelsize; int a; float vec[4][2] = { {0.195, 0.02}, {0.55, 0.169}, {0.831, 0.45}, {0.98, 0.805}, }; /* mult */ for (a = 0; a < 4; a++) { mul_v2_fl(vec[a], rad); } immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR); immBeginAtMost(GPU_PRIM_LINE_STRIP, 25); immAttr3ubv(col, highlight); /* start with corner left-top */ if (roundboxtype & UI_CNR_TOP_LEFT) { immVertex2f(pos, minx, maxy - rad); for (a = 0; a < 4; a++) { immVertex2f(pos, minx + vec[a][1], maxy - rad + vec[a][0]); } immVertex2f(pos, minx + rad, maxy); } else { immVertex2f(pos, minx, maxy); } /* corner right-top */ if (roundboxtype & UI_CNR_TOP_RIGHT) { immVertex2f(pos, maxx - rad, maxy); for (a = 0; a < 4; a++) { immVertex2f(pos, maxx - rad + vec[a][0], maxy - vec[a][1]); } immVertex2f(pos, maxx, maxy - rad); } else { immVertex2f(pos, maxx, maxy); } immAttr3ubv(col, highlight_fade); /* corner right-bottom */ if (roundboxtype & UI_CNR_BOTTOM_RIGHT) { immVertex2f(pos, maxx, miny + rad); for (a = 0; a < 4; a++) { immVertex2f(pos, maxx - vec[a][1], miny + rad - vec[a][0]); } immVertex2f(pos, maxx - rad, miny); } else { immVertex2f(pos, maxx, miny); } /* corner left-bottom */ if (roundboxtype & UI_CNR_BOTTOM_LEFT) { immVertex2f(pos, minx + rad, miny); for (a = 0; a < 4; a++) { immVertex2f(pos, minx + rad - vec[a][0], miny + vec[a][1]); } immVertex2f(pos, minx, miny + rad); } else { immVertex2f(pos, minx, miny); } immAttr3ubv(col, highlight); /* back to corner left-top */ immVertex2f(pos, minx, (roundboxtype & UI_CNR_TOP_LEFT) ? (maxy - rad) : maxy); immEnd(); immUnbindProgram(); } void ui_draw_but_IMAGE(ARegion *UNUSED(ar), uiBut *but, const uiWidgetColors *UNUSED(wcol), const rcti *rect) { #ifdef WITH_HEADLESS (void)rect; (void)but; #else ImBuf *ibuf = (ImBuf *)but->poin; if (!ibuf) { return; } float facx = 1.0f; float facy = 1.0f; int w = BLI_rcti_size_x(rect); int h = BLI_rcti_size_y(rect); /* scissor doesn't seem to be doing the right thing...? */ # if 0 /* prevent drawing outside widget area */ int scissor[4]; GPU_scissor_get_i(scissor); GPU_scissor(rect->xmin, rect->ymin, w, h); # endif GPU_blend(true); if (w != ibuf->x || h != ibuf->y) { facx = (float)w / (float)ibuf->x; facy = (float)h / (float)ibuf->y; } IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR); immDrawPixelsTex(&state, (float)rect->xmin, (float)rect->ymin, ibuf->x, ibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_NEAREST, ibuf->rect, facx, facy, NULL); GPU_blend(false); # if 0 // restore scissortest GPU_scissor(scissor[0], scissor[1], scissor[2], scissor[3]); # endif #endif } /** * Draw title and text safe areas. * * \note This function is to be used with the 2D dashed shader enabled. * * \param pos: is a PRIM_FLOAT, 2, GPU_FETCH_FLOAT vertex attribute. * \param line_origin: is a PRIM_FLOAT, 2, GPU_FETCH_FLOAT vertex attribute. * * The next 4 parameters are the offsets for the view, not the zones. */ void UI_draw_safe_areas(uint pos, float x1, float x2, float y1, float y2, const float title_aspect[2], const float action_aspect[2]) { const float size_x_half = (x2 - x1) * 0.5f; const float size_y_half = (y2 - y1) * 0.5f; const float *safe_areas[] = {title_aspect, action_aspect}; const int safe_len = ARRAY_SIZE(safe_areas); for (int i = 0; i < safe_len; i++) { if (safe_areas[i][0] || safe_areas[i][1]) { float margin_x = safe_areas[i][0] * size_x_half; float margin_y = safe_areas[i][1] * size_y_half; float minx = x1 + margin_x; float miny = y1 + margin_y; float maxx = x2 - margin_x; float maxy = y2 - margin_y; imm_draw_box_wire_2d(pos, minx, miny, maxx, maxy); } } } static void draw_scope_end(const rctf *rect, GLint *scissor) { /* restore scissortest */ GPU_scissor(scissor[0], scissor[1], scissor[2], scissor[3]); GPU_blend_set_func_separate( GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA); /* outline */ UI_draw_roundbox_corner_set(UI_CNR_ALL); float color[4] = {0.0f, 0.0f, 0.0f, 0.5f}; UI_draw_roundbox_4fv( false, rect->xmin - 1, rect->ymin, rect->xmax + 1, rect->ymax + 1, 3.0f, color); } static void histogram_draw_one(float r, float g, float b, float alpha, float x, float y, float w, float h, const float *data, int res, const bool is_line, uint pos_attr) { float color[4] = {r, g, b, alpha}; /* that can happen */ if (res == 0) { return; } GPU_line_smooth(true); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE); immUniformColor4fv(color); if (is_line) { /* curve outline */ GPU_line_width(1.5); immBegin(GPU_PRIM_LINE_STRIP, res); for (int i = 0; i < res; i++) { float x2 = x + i * (w / (float)res); immVertex2f(pos_attr, x2, y + (data[i] * h)); } immEnd(); } else { /* under the curve */ immBegin(GPU_PRIM_TRI_STRIP, res * 2); immVertex2f(pos_attr, x, y); immVertex2f(pos_attr, x, y + (data[0] * h)); for (int i = 1; i < res; i++) { float x2 = x + i * (w / (float)res); immVertex2f(pos_attr, x2, y + (data[i] * h)); immVertex2f(pos_attr, x2, y); } immEnd(); /* curve outline */ immUniformColor4f(0.0f, 0.0f, 0.0f, 0.25f); GPU_blend_set_func_separate( GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA); immBegin(GPU_PRIM_LINE_STRIP, res); for (int i = 0; i < res; i++) { float x2 = x + i * (w / (float)res); immVertex2f(pos_attr, x2, y + (data[i] * h)); } immEnd(); } GPU_line_smooth(false); } #define HISTOGRAM_TOT_GRID_LINES 4 void ui_draw_but_HISTOGRAM(ARegion *UNUSED(ar), uiBut *but, const uiWidgetColors *UNUSED(wcol), const rcti *recti) { Histogram *hist = (Histogram *)but->poin; int res = hist->x_resolution; const bool is_line = (hist->flag & HISTO_FLAG_LINE) != 0; rctf rect = { .xmin = (float)recti->xmin + 1, .xmax = (float)recti->xmax - 1, .ymin = (float)recti->ymin + 1, .ymax = (float)recti->ymax - 1, }; float w = BLI_rctf_size_x(&rect); float h = BLI_rctf_size_y(&rect) * hist->ymax; GPU_blend(true); GPU_blend_set_func_separate( GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA); float color[4]; UI_GetThemeColor4fv(TH_PREVIEW_BACK, color); UI_draw_roundbox_corner_set(UI_CNR_ALL); UI_draw_roundbox_4fv( true, rect.xmin - 1, rect.ymin - 1, rect.xmax + 1, rect.ymax + 1, 3.0f, color); /* need scissor test, histogram can draw outside of boundary */ int scissor[4]; GPU_scissor_get_i(scissor); GPU_scissor((rect.xmin - 1), (rect.ymin - 1), (rect.xmax + 1) - (rect.xmin - 1), (rect.ymax + 1) - (rect.ymin - 1)); GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor4f(1.0f, 1.0f, 1.0f, 0.08f); /* draw grid lines here */ for (int i = 1; i <= HISTOGRAM_TOT_GRID_LINES; i++) { const float fac = (float)i / (float)HISTOGRAM_TOT_GRID_LINES; /* so we can tell the 1.0 color point */ if (i == HISTOGRAM_TOT_GRID_LINES) { immUniformColor4f(1.0f, 1.0f, 1.0f, 0.5f); } immBegin(GPU_PRIM_LINES, 4); immVertex2f(pos, rect.xmin, rect.ymin + fac * h); immVertex2f(pos, rect.xmax, rect.ymin + fac * h); immVertex2f(pos, rect.xmin + fac * w, rect.ymin); immVertex2f(pos, rect.xmin + fac * w, rect.ymax); immEnd(); } if (hist->mode == HISTO_MODE_LUMA) { histogram_draw_one( 1.0, 1.0, 1.0, 0.75, rect.xmin, rect.ymin, w, h, hist->data_luma, res, is_line, pos); } else if (hist->mode == HISTO_MODE_ALPHA) { histogram_draw_one( 1.0, 1.0, 1.0, 0.75, rect.xmin, rect.ymin, w, h, hist->data_a, res, is_line, pos); } else { if (hist->mode == HISTO_MODE_RGB || hist->mode == HISTO_MODE_R) { histogram_draw_one( 1.0, 0.0, 0.0, 0.75, rect.xmin, rect.ymin, w, h, hist->data_r, res, is_line, pos); } if (hist->mode == HISTO_MODE_RGB || hist->mode == HISTO_MODE_G) { histogram_draw_one( 0.0, 1.0, 0.0, 0.75, rect.xmin, rect.ymin, w, h, hist->data_g, res, is_line, pos); } if (hist->mode == HISTO_MODE_RGB || hist->mode == HISTO_MODE_B) { histogram_draw_one( 0.0, 0.0, 1.0, 0.75, rect.xmin, rect.ymin, w, h, hist->data_b, res, is_line, pos); } } immUnbindProgram(); /* outline */ draw_scope_end(&rect, scissor); } #undef HISTOGRAM_TOT_GRID_LINES static void waveform_draw_one(float *waveform, int nbr, const float col[3]) { GPUVertFormat format = {0}; uint pos_id = GPU_vertformat_attr_add(&format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); GPUVertBuf *vbo = GPU_vertbuf_create_with_format(&format); GPU_vertbuf_data_alloc(vbo, nbr); GPU_vertbuf_attr_fill(vbo, pos_id, waveform); /* TODO store the GPUBatch inside the scope */ GPUBatch *batch = GPU_batch_create_ex(GPU_PRIM_POINTS, vbo, NULL, GPU_BATCH_OWNS_VBO); GPU_batch_program_set_builtin(batch, GPU_SHADER_2D_UNIFORM_COLOR); GPU_batch_uniform_4f(batch, "color", col[0], col[1], col[2], 1.0f); GPU_batch_draw(batch); GPU_batch_discard(batch); } void ui_draw_but_WAVEFORM(ARegion *UNUSED(ar), uiBut *but, const uiWidgetColors *UNUSED(wcol), const rcti *recti) { Scopes *scopes = (Scopes *)but->poin; int scissor[4]; float colors[3][3]; float colorsycc[3][3] = {{1, 0, 1}, {1, 1, 0}, {0, 1, 1}}; /* colors pre multiplied by alpha for speed up */ float colors_alpha[3][3], colorsycc_alpha[3][3]; float min, max; if (scopes == NULL) { return; } rctf rect = { .xmin = (float)recti->xmin + 1, .xmax = (float)recti->xmax - 1, .ymin = (float)recti->ymin + 1, .ymax = (float)recti->ymax - 1, }; if (scopes->wavefrm_yfac < 0.5f) { scopes->wavefrm_yfac = 0.98f; } float w = BLI_rctf_size_x(&rect) - 7; float h = BLI_rctf_size_y(&rect) * scopes->wavefrm_yfac; float yofs = rect.ymin + (BLI_rctf_size_y(&rect) - h) * 0.5f; float w3 = w / 3.0f; /* log scale for alpha */ float alpha = scopes->wavefrm_alpha * scopes->wavefrm_alpha; unit_m3(colors); for (int c = 0; c < 3; c++) { for (int i = 0; i < 3; i++) { colors_alpha[c][i] = colors[c][i] * alpha; colorsycc_alpha[c][i] = colorsycc[c][i] * alpha; } } /* Flush text cache before changing scissors. */ BLF_batch_draw_flush(); GPU_blend(true); GPU_blend_set_func_separate( GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA); float color[4]; UI_GetThemeColor4fv(TH_PREVIEW_BACK, color); UI_draw_roundbox_corner_set(UI_CNR_ALL); UI_draw_roundbox_4fv( true, rect.xmin - 1, rect.ymin - 1, rect.xmax + 1, rect.ymax + 1, 3.0f, color); /* need scissor test, waveform can draw outside of boundary */ GPU_scissor_get_i(scissor); GPU_scissor((rect.xmin - 1), (rect.ymin - 1), (rect.xmax + 1) - (rect.xmin - 1), (rect.ymax + 1) - (rect.ymin - 1)); /* draw scale numbers first before binding any shader */ for (int i = 0; i < 6; i++) { char str[4]; BLI_snprintf(str, sizeof(str), "%-3d", i * 20); str[3] = '\0'; BLF_color4f(BLF_default(), 1.0f, 1.0f, 1.0f, 0.08f); BLF_draw_default(rect.xmin + 1, yofs - 5 + (i * 0.2f) * h, 0, str, sizeof(str) - 1); } /* Flush text cache before drawing things on top. */ BLF_batch_draw_flush(); GPU_blend(true); GPU_blend_set_func_separate( GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA); GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor4f(1.0f, 1.0f, 1.0f, 0.08f); /* draw grid lines here */ immBegin(GPU_PRIM_LINES, 12); for (int i = 0; i < 6; i++) { immVertex2f(pos, rect.xmin + 22, yofs + (i * 0.2f) * h); immVertex2f(pos, rect.xmax + 1, yofs + (i * 0.2f) * h); } immEnd(); /* 3 vertical separation */ if (scopes->wavefrm_mode != SCOPES_WAVEFRM_LUMA) { immBegin(GPU_PRIM_LINES, 4); for (int i = 1; i < 3; i++) { immVertex2f(pos, rect.xmin + i * w3, rect.ymin); immVertex2f(pos, rect.xmin + i * w3, rect.ymax); } immEnd(); } /* separate min max zone on the right */ immBegin(GPU_PRIM_LINES, 2); immVertex2f(pos, rect.xmin + w, rect.ymin); immVertex2f(pos, rect.xmin + w, rect.ymax); immEnd(); /* 16-235-240 level in case of ITU-R BT601/709 */ immUniformColor4f(1.0f, 0.4f, 0.0f, 0.2f); if (ELEM(scopes->wavefrm_mode, SCOPES_WAVEFRM_YCC_601, SCOPES_WAVEFRM_YCC_709)) { immBegin(GPU_PRIM_LINES, 8); immVertex2f(pos, rect.xmin + 22, yofs + h * 16.0f / 255.0f); immVertex2f(pos, rect.xmax + 1, yofs + h * 16.0f / 255.0f); immVertex2f(pos, rect.xmin + 22, yofs + h * 235.0f / 255.0f); immVertex2f(pos, rect.xmin + w3, yofs + h * 235.0f / 255.0f); immVertex2f(pos, rect.xmin + 3 * w3, yofs + h * 235.0f / 255.0f); immVertex2f(pos, rect.xmax + 1, yofs + h * 235.0f / 255.0f); immVertex2f(pos, rect.xmin + w3, yofs + h * 240.0f / 255.0f); immVertex2f(pos, rect.xmax + 1, yofs + h * 240.0f / 255.0f); immEnd(); } /* 7.5 IRE black point level for NTSC */ if (scopes->wavefrm_mode == SCOPES_WAVEFRM_LUMA) { immBegin(GPU_PRIM_LINES, 2); immVertex2f(pos, rect.xmin, yofs + h * 0.075f); immVertex2f(pos, rect.xmax + 1, yofs + h * 0.075f); immEnd(); } if (scopes->ok && scopes->waveform_1 != NULL) { glBlendFunc(GL_ONE, GL_ONE); GPU_point_size(1.0); /* LUMA (1 channel) */ if (scopes->wavefrm_mode == SCOPES_WAVEFRM_LUMA) { float col[3] = {alpha, alpha, alpha}; GPU_matrix_push(); GPU_matrix_translate_2f(rect.xmin, yofs); GPU_matrix_scale_2f(w, h); waveform_draw_one(scopes->waveform_1, scopes->waveform_tot, col); GPU_matrix_pop(); /* min max */ immUniformColor3f(0.5f, 0.5f, 0.5f); min = yofs + scopes->minmax[0][0] * h; max = yofs + scopes->minmax[0][1] * h; CLAMP(min, rect.ymin, rect.ymax); CLAMP(max, rect.ymin, rect.ymax); immBegin(GPU_PRIM_LINES, 2); immVertex2f(pos, rect.xmax - 3, min); immVertex2f(pos, rect.xmax - 3, max); immEnd(); } /* RGB (3 channel) */ else if (scopes->wavefrm_mode == SCOPES_WAVEFRM_RGB) { GPU_matrix_push(); GPU_matrix_translate_2f(rect.xmin, yofs); GPU_matrix_scale_2f(w, h); waveform_draw_one(scopes->waveform_1, scopes->waveform_tot, colors_alpha[0]); waveform_draw_one(scopes->waveform_2, scopes->waveform_tot, colors_alpha[1]); waveform_draw_one(scopes->waveform_3, scopes->waveform_tot, colors_alpha[2]); GPU_matrix_pop(); } /* PARADE / YCC (3 channels) */ else if (ELEM(scopes->wavefrm_mode, SCOPES_WAVEFRM_RGB_PARADE, SCOPES_WAVEFRM_YCC_601, SCOPES_WAVEFRM_YCC_709, SCOPES_WAVEFRM_YCC_JPEG)) { int rgb = (scopes->wavefrm_mode == SCOPES_WAVEFRM_RGB_PARADE); GPU_matrix_push(); GPU_matrix_translate_2f(rect.xmin, yofs); GPU_matrix_scale_2f(w3, h); waveform_draw_one( scopes->waveform_1, scopes->waveform_tot, (rgb) ? colors_alpha[0] : colorsycc_alpha[0]); GPU_matrix_translate_2f(1.0f, 0.0f); waveform_draw_one( scopes->waveform_2, scopes->waveform_tot, (rgb) ? colors_alpha[1] : colorsycc_alpha[1]); GPU_matrix_translate_2f(1.0f, 0.0f); waveform_draw_one( scopes->waveform_3, scopes->waveform_tot, (rgb) ? colors_alpha[2] : colorsycc_alpha[2]); GPU_matrix_pop(); } /* min max */ if (scopes->wavefrm_mode != SCOPES_WAVEFRM_LUMA) { for (int c = 0; c < 3; c++) { if (ELEM(scopes->wavefrm_mode, SCOPES_WAVEFRM_RGB_PARADE, SCOPES_WAVEFRM_RGB)) { immUniformColor3f(colors[c][0] * 0.75f, colors[c][1] * 0.75f, colors[c][2] * 0.75f); } else { immUniformColor3f( colorsycc[c][0] * 0.75f, colorsycc[c][1] * 0.75f, colorsycc[c][2] * 0.75f); } min = yofs + scopes->minmax[c][0] * h; max = yofs + scopes->minmax[c][1] * h; CLAMP(min, rect.ymin, rect.ymax); CLAMP(max, rect.ymin, rect.ymax); immBegin(GPU_PRIM_LINES, 2); immVertex2f(pos, rect.xmin + w + 2 + c * 2, min); immVertex2f(pos, rect.xmin + w + 2 + c * 2, max); immEnd(); } } } immUnbindProgram(); /* outline */ draw_scope_end(&rect, scissor); GPU_blend(false); } static float polar_to_x(float center, float diam, float ampli, float angle) { return center + diam * ampli * cosf(angle); } static float polar_to_y(float center, float diam, float ampli, float angle) { return center + diam * ampli * sinf(angle); } static void vectorscope_draw_target( uint pos, float centerx, float centery, float diam, const float colf[3]) { float y, u, v; float tangle = 0.0f, tampli; float dangle, dampli, dangle2, dampli2; rgb_to_yuv(colf[0], colf[1], colf[2], &y, &u, &v, BLI_YUV_ITU_BT709); if (u > 0 && v >= 0) { tangle = atanf(v / u); } else if (u > 0 && v < 0) { tangle = atanf(v / u) + 2.0f * (float)M_PI; } else if (u < 0) { tangle = atanf(v / u) + (float)M_PI; } else if (u == 0 && v > 0.0f) { tangle = M_PI_2; } else if (u == 0 && v < 0.0f) { tangle = -M_PI_2; } tampli = sqrtf(u * u + v * v); /* small target vary by 2.5 degree and 2.5 IRE unit */ immUniformColor4f(1.0f, 1.0f, 1.0f, 0.12f); dangle = DEG2RADF(2.5f); dampli = 2.5f / 200.0f; immBegin(GPU_PRIM_LINE_LOOP, 4); immVertex2f(pos, polar_to_x(centerx, diam, tampli + dampli, tangle + dangle), polar_to_y(centery, diam, tampli + dampli, tangle + dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli - dampli, tangle + dangle), polar_to_y(centery, diam, tampli - dampli, tangle + dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli - dampli, tangle - dangle), polar_to_y(centery, diam, tampli - dampli, tangle - dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli + dampli, tangle - dangle), polar_to_y(centery, diam, tampli + dampli, tangle - dangle)); immEnd(); /* big target vary by 10 degree and 20% amplitude */ immUniformColor4f(1.0f, 1.0f, 1.0f, 0.12f); dangle = DEG2RADF(10.0f); dampli = 0.2f * tampli; dangle2 = DEG2RADF(5.0f); dampli2 = 0.5f * dampli; immBegin(GPU_PRIM_LINE_STRIP, 3); immVertex2f(pos, polar_to_x(centerx, diam, tampli + dampli - dampli2, tangle + dangle), polar_to_y(centery, diam, tampli + dampli - dampli2, tangle + dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli + dampli, tangle + dangle), polar_to_y(centery, diam, tampli + dampli, tangle + dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli + dampli, tangle + dangle - dangle2), polar_to_y(centery, diam, tampli + dampli, tangle + dangle - dangle2)); immEnd(); immBegin(GPU_PRIM_LINE_STRIP, 3); immVertex2f(pos, polar_to_x(centerx, diam, tampli - dampli + dampli2, tangle + dangle), polar_to_y(centery, diam, tampli - dampli + dampli2, tangle + dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli - dampli, tangle + dangle), polar_to_y(centery, diam, tampli - dampli, tangle + dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli - dampli, tangle + dangle - dangle2), polar_to_y(centery, diam, tampli - dampli, tangle + dangle - dangle2)); immEnd(); immBegin(GPU_PRIM_LINE_STRIP, 3); immVertex2f(pos, polar_to_x(centerx, diam, tampli - dampli + dampli2, tangle - dangle), polar_to_y(centery, diam, tampli - dampli + dampli2, tangle - dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli - dampli, tangle - dangle), polar_to_y(centery, diam, tampli - dampli, tangle - dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli - dampli, tangle - dangle + dangle2), polar_to_y(centery, diam, tampli - dampli, tangle - dangle + dangle2)); immEnd(); immBegin(GPU_PRIM_LINE_STRIP, 3); immVertex2f(pos, polar_to_x(centerx, diam, tampli + dampli - dampli2, tangle - dangle), polar_to_y(centery, diam, tampli + dampli - dampli2, tangle - dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli + dampli, tangle - dangle), polar_to_y(centery, diam, tampli + dampli, tangle - dangle)); immVertex2f(pos, polar_to_x(centerx, diam, tampli + dampli, tangle - dangle + dangle2), polar_to_y(centery, diam, tampli + dampli, tangle - dangle + dangle2)); immEnd(); } void ui_draw_but_VECTORSCOPE(ARegion *UNUSED(ar), uiBut *but, const uiWidgetColors *UNUSED(wcol), const rcti *recti) { const float skin_rad = DEG2RADF(123.0f); /* angle in radians of the skin tone line */ Scopes *scopes = (Scopes *)but->poin; const float colors[6][3] = { {0.75, 0.0, 0.0}, {0.75, 0.75, 0.0}, {0.0, 0.75, 0.0}, {0.0, 0.75, 0.75}, {0.0, 0.0, 0.75}, {0.75, 0.0, 0.75}, }; rctf rect = { .xmin = (float)recti->xmin + 1, .xmax = (float)recti->xmax - 1, .ymin = (float)recti->ymin + 1, .ymax = (float)recti->ymax - 1, }; float w = BLI_rctf_size_x(&rect); float h = BLI_rctf_size_y(&rect); float centerx = rect.xmin + w * 0.5f; float centery = rect.ymin + h * 0.5f; float diam = (w < h) ? w : h; float alpha = scopes->vecscope_alpha * scopes->vecscope_alpha * scopes->vecscope_alpha; GPU_blend(true); GPU_blend_set_func_separate( GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA); float color[4]; UI_GetThemeColor4fv(TH_PREVIEW_BACK, color); UI_draw_roundbox_corner_set(UI_CNR_ALL); UI_draw_roundbox_4fv( true, rect.xmin - 1, rect.ymin - 1, rect.xmax + 1, rect.ymax + 1, 3.0f, color); /* need scissor test, hvectorscope can draw outside of boundary */ int scissor[4]; GPU_scissor_get_i(scissor); GPU_scissor((rect.xmin - 1), (rect.ymin - 1), (rect.xmax + 1) - (rect.xmin - 1), (rect.ymax + 1) - (rect.ymin - 1)); GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor4f(1.0f, 1.0f, 1.0f, 0.08f); /* draw grid elements */ /* cross */ immBegin(GPU_PRIM_LINES, 4); immVertex2f(pos, centerx - (diam * 0.5f) - 5, centery); immVertex2f(pos, centerx + (diam * 0.5f) + 5, centery); immVertex2f(pos, centerx, centery - (diam * 0.5f) - 5); immVertex2f(pos, centerx, centery + (diam * 0.5f) + 5); immEnd(); /* circles */ for (int j = 0; j < 5; j++) { const int increment = 15; immBegin(GPU_PRIM_LINE_LOOP, (int)(360 / increment)); for (int i = 0; i <= 360 - increment; i += increment) { const float a = DEG2RADF((float)i); const float r = (j + 1) * 0.1f; immVertex2f(pos, polar_to_x(centerx, diam, r, a), polar_to_y(centery, diam, r, a)); } immEnd(); } /* skin tone line */ immUniformColor4f(1.0f, 0.4f, 0.0f, 0.2f); immBegin(GPU_PRIM_LINES, 2); immVertex2f( pos, polar_to_x(centerx, diam, 0.5f, skin_rad), polar_to_y(centery, diam, 0.5f, skin_rad)); immVertex2f( pos, polar_to_x(centerx, diam, 0.1f, skin_rad), polar_to_y(centery, diam, 0.1f, skin_rad)); immEnd(); /* saturation points */ for (int i = 0; i < 6; i++) { vectorscope_draw_target(pos, centerx, centery, diam, colors[i]); } if (scopes->ok && scopes->vecscope != NULL) { /* pixel point cloud */ float col[3] = {alpha, alpha, alpha}; glBlendFunc(GL_ONE, GL_ONE); GPU_point_size(1.0); GPU_matrix_push(); GPU_matrix_translate_2f(centerx, centery); GPU_matrix_scale_1f(diam); waveform_draw_one(scopes->vecscope, scopes->waveform_tot, col); GPU_matrix_pop(); } immUnbindProgram(); /* outline */ draw_scope_end(&rect, scissor); GPU_blend(false); } static void ui_draw_colorband_handle_tri_hlight( uint pos, float x1, float y1, float halfwidth, float height) { GPU_line_smooth(true); immBegin(GPU_PRIM_LINE_STRIP, 3); immVertex2f(pos, x1 + halfwidth, y1); immVertex2f(pos, x1, y1 + height); immVertex2f(pos, x1 - halfwidth, y1); immEnd(); GPU_line_smooth(false); } static void ui_draw_colorband_handle_tri( uint pos, float x1, float y1, float halfwidth, float height, bool fill) { if (fill) { GPU_polygon_smooth(true); } else { GPU_line_smooth(true); } immBegin(fill ? GPU_PRIM_TRIS : GPU_PRIM_LINE_LOOP, 3); immVertex2f(pos, x1 + halfwidth, y1); immVertex2f(pos, x1, y1 + height); immVertex2f(pos, x1 - halfwidth, y1); immEnd(); if (fill) { GPU_polygon_smooth(false); } else { GPU_line_smooth(false); } } static void ui_draw_colorband_handle_box( uint pos, float x1, float y1, float x2, float y2, bool fill) { immBegin(fill ? GPU_PRIM_TRI_FAN : GPU_PRIM_LINE_LOOP, 4); immVertex2f(pos, x1, y1); immVertex2f(pos, x1, y2); immVertex2f(pos, x2, y2); immVertex2f(pos, x2, y1); immEnd(); } static void ui_draw_colorband_handle(uint shdr_pos, const rcti *rect, float x, const float rgb[3], struct ColorManagedDisplay *display, bool active) { const float sizey = BLI_rcti_size_y(rect); const float min_width = 3.0f; float colf[3] = {UNPACK3(rgb)}; float half_width = floorf(sizey / 3.5f); float height = half_width * 1.4f; float y1 = rect->ymin + (sizey * 0.16f); float y2 = rect->ymax; /* align to pixels */ x = floorf(x + 0.5f); y1 = floorf(y1 + 0.5f); if (active || half_width < min_width) { immUnbindProgram(); immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR); float viewport_size[4]; GPU_viewport_size_get_f(viewport_size); immUniform2f("viewport_size", viewport_size[2] / UI_DPI_FAC, viewport_size[3] / UI_DPI_FAC); immUniform1i("colors_len", 2); /* "advanced" mode */ immUniformArray4fv( "colors", (float *)(float[][4]){{0.8f, 0.8f, 0.8f, 1.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}, 2); immUniform1f("dash_width", active ? 4.0f : 2.0f); immUniform1f("dash_factor", 0.5f); immBegin(GPU_PRIM_LINES, 2); immVertex2f(shdr_pos, x, y1); immVertex2f(shdr_pos, x, y2); immEnd(); immUnbindProgram(); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); /* hide handles when zoomed out too far */ if (half_width < min_width) { return; } } /* shift handle down */ y1 -= half_width; immUniformColor3ub(0, 0, 0); ui_draw_colorband_handle_box( shdr_pos, x - half_width, y1 - 1, x + half_width, y1 + height, false); /* draw all triangles blended */ GPU_blend(true); ui_draw_colorband_handle_tri(shdr_pos, x, y1 + height, half_width, half_width, true); if (active) { immUniformColor3ub(196, 196, 196); } else { immUniformColor3ub(96, 96, 96); } ui_draw_colorband_handle_tri(shdr_pos, x, y1 + height, half_width, half_width, true); if (active) { immUniformColor3ub(255, 255, 255); } else { immUniformColor3ub(128, 128, 128); } ui_draw_colorband_handle_tri_hlight( shdr_pos, x, y1 + height - 1, (half_width - 1), (half_width - 1)); immUniformColor3ub(0, 0, 0); ui_draw_colorband_handle_tri_hlight(shdr_pos, x, y1 + height, half_width, half_width); GPU_blend(false); immUniformColor3ub(128, 128, 128); ui_draw_colorband_handle_box( shdr_pos, x - (half_width - 1), y1, x + (half_width - 1), y1 + height, true); if (display) { IMB_colormanagement_scene_linear_to_display_v3(colf, display); } immUniformColor3fv(colf); ui_draw_colorband_handle_box( shdr_pos, x - (half_width - 2), y1 + 1, x + (half_width - 2), y1 + height - 2, true); } void ui_draw_but_COLORBAND(uiBut *but, const uiWidgetColors *UNUSED(wcol), const rcti *rect) { struct ColorManagedDisplay *display = ui_block_cm_display_get(but->block); uint pos_id, col_id; ColorBand *coba = (ColorBand *)(but->editcoba ? but->editcoba : but->poin); if (coba == NULL) { return; } float x1 = rect->xmin; float sizex = rect->xmax - x1; float sizey = BLI_rcti_size_y(rect); float sizey_solid = sizey * 0.25f; float y1 = rect->ymin; /* exit early if too narrow */ if (sizex <= 0) { return; } GPUVertFormat *format = immVertexFormat(); pos_id = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_CHECKER); /* Drawing the checkerboard. */ const float checker_dark = UI_ALPHA_CHECKER_DARK / 255.0f; const float checker_light = UI_ALPHA_CHECKER_LIGHT / 255.0f; immUniform4f("color1", checker_dark, checker_dark, checker_dark, 1.0f); immUniform4f("color2", checker_light, checker_light, checker_light, 1.0f); immUniform1i("size", 8); immRectf(pos_id, x1, y1, x1 + sizex, rect->ymax); immUnbindProgram(); /* New format */ format = immVertexFormat(); pos_id = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); col_id = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 4, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR); /* layer: color ramp */ GPU_blend(true); CBData *cbd = coba->data; float v1[2], v2[2]; float colf[4] = {0, 0, 0, 0}; /* initialize in case the colorband isn't valid */ v1[1] = y1 + sizey_solid; v2[1] = rect->ymax; immBegin(GPU_PRIM_TRI_STRIP, (sizex + 1) * 2); for (int a = 0; a <= sizex; a++) { float pos = ((float)a) / sizex; BKE_colorband_evaluate(coba, pos, colf); if (display) { IMB_colormanagement_scene_linear_to_display_v3(colf, display); } v1[0] = v2[0] = x1 + a; immAttr4fv(col_id, colf); immVertex2fv(pos_id, v1); immVertex2fv(pos_id, v2); } immEnd(); /* layer: color ramp without alpha for reference when manipulating ramp properties */ v1[1] = y1; v2[1] = y1 + sizey_solid; immBegin(GPU_PRIM_TRI_STRIP, (sizex + 1) * 2); for (int a = 0; a <= sizex; a++) { float pos = ((float)a) / sizex; BKE_colorband_evaluate(coba, pos, colf); if (display) { IMB_colormanagement_scene_linear_to_display_v3(colf, display); } v1[0] = v2[0] = x1 + a; immAttr4f(col_id, colf[0], colf[1], colf[2], 1.0f); immVertex2fv(pos_id, v1); immVertex2fv(pos_id, v2); } immEnd(); immUnbindProgram(); GPU_blend(false); /* New format */ format = immVertexFormat(); pos_id = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); /* layer: box outline */ immUniformColor4f(0.0f, 0.0f, 0.0f, 1.0f); imm_draw_box_wire_2d(pos_id, x1, y1, x1 + sizex, rect->ymax); /* layer: box outline */ GPU_blend(true); immUniformColor4f(0.0f, 0.0f, 0.0f, 0.5f); immBegin(GPU_PRIM_LINES, 2); immVertex2f(pos_id, x1, y1); immVertex2f(pos_id, x1 + sizex, y1); immEnd(); immUniformColor4f(1.0f, 1.0f, 1.0f, 0.25f); immBegin(GPU_PRIM_LINES, 2); immVertex2f(pos_id, x1, y1 - 1); immVertex2f(pos_id, x1 + sizex, y1 - 1); immEnd(); GPU_blend(false); /* layer: draw handles */ for (int a = 0; a < coba->tot; a++, cbd++) { if (a != coba->cur) { float pos = x1 + cbd->pos * (sizex - 1) + 1; ui_draw_colorband_handle(pos_id, rect, pos, &cbd->r, display, false); } } /* layer: active handle */ if (coba->tot != 0) { cbd = &coba->data[coba->cur]; float pos = x1 + cbd->pos * (sizex - 1) + 1; ui_draw_colorband_handle(pos_id, rect, pos, &cbd->r, display, true); } immUnbindProgram(); } void ui_draw_but_UNITVEC(uiBut *but, const uiWidgetColors *wcol, const rcti *rect) { /* sphere color */ float diffuse[3] = {1.0f, 1.0f, 1.0f}; float light[3]; float size; /* backdrop */ UI_draw_roundbox_corner_set(UI_CNR_ALL); UI_draw_roundbox_3ubAlpha( true, rect->xmin, rect->ymin, rect->xmax, rect->ymax, 5.0f, wcol->inner, 255); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); /* setup lights */ ui_but_v3_get(but, light); /* transform to button */ GPU_matrix_push(); if (BLI_rcti_size_x(rect) < BLI_rcti_size_y(rect)) { size = 0.5f * BLI_rcti_size_x(rect); } else { size = 0.5f * BLI_rcti_size_y(rect); } GPU_matrix_translate_2f(rect->xmin + 0.5f * BLI_rcti_size_x(rect), rect->ymin + 0.5f * BLI_rcti_size_y(rect)); GPU_matrix_scale_1f(size); GPUBatch *sphere = GPU_batch_preset_sphere(2); GPU_batch_program_set_builtin(sphere, GPU_SHADER_SIMPLE_LIGHTING); GPU_batch_uniform_4f(sphere, "color", diffuse[0], diffuse[1], diffuse[2], 1.0f); GPU_batch_uniform_3fv(sphere, "light", light); GPU_batch_draw(sphere); /* restore */ glDisable(GL_CULL_FACE); /* AA circle */ GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor3ubv(wcol->inner); GPU_blend(true); GPU_line_smooth(true); imm_draw_circle_wire_2d(pos, 0.0f, 0.0f, 1.0f, 32); GPU_blend(false); GPU_line_smooth(false); /* matrix after circle */ GPU_matrix_pop(); immUnbindProgram(); } static void ui_draw_but_curve_grid( uint pos, const rcti *rect, float zoomx, float zoomy, float offsx, float offsy, float step) { float dx = step * zoomx; float fx = rect->xmin + zoomx * (-offsx); if (fx > rect->xmin) { fx -= dx * (floorf(fx - rect->xmin)); } float dy = step * zoomy; float fy = rect->ymin + zoomy * (-offsy); if (fy > rect->ymin) { fy -= dy * (floorf(fy - rect->ymin)); } float line_count = (floorf((rect->xmax - fx) / dx) + 1.0f + floorf((rect->ymax - fy) / dy) + 1.0f); immBegin(GPU_PRIM_LINES, (int)line_count * 2); while (fx <= rect->xmax) { immVertex2f(pos, fx, rect->ymin); immVertex2f(pos, fx, rect->ymax); fx += dx; } while (fy <= rect->ymax) { immVertex2f(pos, rect->xmin, fy); immVertex2f(pos, rect->xmax, fy); fy += dy; } /* Note: Assertion fails with here when the view is moved farther below the center. * Missing two points from the number given with immBegin. */ immEnd(); } static void gl_shaded_color_get(const uchar color[3], int shade, uchar r_color[3]) { r_color[0] = color[0] - shade > 0 ? color[0] - shade : 0; r_color[1] = color[1] - shade > 0 ? color[1] - shade : 0; r_color[2] = color[2] - shade > 0 ? color[2] - shade : 0; } static void gl_shaded_color_get_fl(const uchar *color, int shade, float r_color[3]) { uchar color_shaded[3]; gl_shaded_color_get(color, shade, color_shaded); rgb_uchar_to_float(r_color, color_shaded); } static void gl_shaded_color(const uchar *color, int shade) { uchar color_shaded[3]; gl_shaded_color_get(color, shade, color_shaded); immUniformColor3ubv(color_shaded); } void ui_draw_but_CURVE(ARegion *ar, uiBut *but, const uiWidgetColors *wcol, const rcti *rect) { CurveMapping *cumap; if (but->editcumap) { cumap = but->editcumap; } else { cumap = (CurveMapping *)but->poin; } float clip_size_x = BLI_rctf_size_x(&cumap->curr); float clip_size_y = BLI_rctf_size_y(&cumap->curr); /* zero-sized curve */ if (clip_size_x == 0.0f || clip_size_y == 0.0f) { return; } /* calculate offset and zoom */ float zoomx = (BLI_rcti_size_x(rect) - 2.0f) / clip_size_x; float zoomy = (BLI_rcti_size_y(rect) - 2.0f) / clip_size_y; float offsx = cumap->curr.xmin - (1.0f / zoomx); float offsy = cumap->curr.ymin - (1.0f / zoomy); /* exit early if too narrow */ if (zoomx == 0.0f) { return; } CurveMap *cuma = &cumap->cm[cumap->cur]; /* need scissor test, curve can draw outside of boundary */ int scissor[4]; GPU_scissor_get_i(scissor); rcti scissor_new = { .xmin = rect->xmin, .ymin = rect->ymin, .xmax = rect->xmax, .ymax = rect->ymax, }; rcti scissor_region = {0, ar->winx, 0, ar->winy}; BLI_rcti_isect(&scissor_new, &scissor_region, &scissor_new); GPU_scissor(scissor_new.xmin, scissor_new.ymin, BLI_rcti_size_x(&scissor_new), BLI_rcti_size_y(&scissor_new)); /* Do this first to not mess imm context */ if (but->a1 == UI_GRAD_H) { /* magic trigger for curve backgrounds */ float col[3] = {0.0f, 0.0f, 0.0f}; /* dummy arg */ rcti grid = { .xmin = rect->xmin + zoomx * (-offsx), .xmax = grid.xmin + zoomx, .ymin = rect->ymin + zoomy * (-offsy), .ymax = grid.ymin + zoomy, }; ui_draw_gradient(&grid, col, UI_GRAD_H, 1.0f); } GPU_line_width(1.0f); GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); /* backdrop */ float color_backdrop[4] = {0, 0, 0, 1}; if (but->a1 == UI_GRAD_H) { /* grid, hsv uses different grid */ GPU_blend(true); GPU_blend_set_func_separate( GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA); ARRAY_SET_ITEMS(color_backdrop, 0, 0, 0, 48.0 / 255.0); immUniformColor4fv(color_backdrop); ui_draw_but_curve_grid(pos, rect, zoomx, zoomy, offsx, offsy, 0.1666666f); GPU_blend(false); } else { if (cumap->flag & CUMA_DO_CLIP) { gl_shaded_color_get_fl(wcol->inner, -20, color_backdrop); immUniformColor3fv(color_backdrop); immRectf(pos, rect->xmin, rect->ymin, rect->xmax, rect->ymax); immUniformColor3ubv(wcol->inner); immRectf(pos, rect->xmin + zoomx * (cumap->clipr.xmin - offsx), rect->ymin + zoomy * (cumap->clipr.ymin - offsy), rect->xmin + zoomx * (cumap->clipr.xmax - offsx), rect->ymin + zoomy * (cumap->clipr.ymax - offsy)); } else { rgb_uchar_to_float(color_backdrop, wcol->inner); immUniformColor3fv(color_backdrop); immRectf(pos, rect->xmin, rect->ymin, rect->xmax, rect->ymax); } /* grid, every 0.25 step */ gl_shaded_color(wcol->inner, -16); ui_draw_but_curve_grid(pos, rect, zoomx, zoomy, offsx, offsy, 0.25f); /* grid, every 1.0 step */ gl_shaded_color(wcol->inner, -24); ui_draw_but_curve_grid(pos, rect, zoomx, zoomy, offsx, offsy, 1.0f); /* axes */ gl_shaded_color(wcol->inner, -50); immBegin(GPU_PRIM_LINES, 4); immVertex2f(pos, rect->xmin, rect->ymin + zoomy * (-offsy)); immVertex2f(pos, rect->xmax, rect->ymin + zoomy * (-offsy)); immVertex2f(pos, rect->xmin + zoomx * (-offsx), rect->ymin); immVertex2f(pos, rect->xmin + zoomx * (-offsx), rect->ymax); immEnd(); } /* cfra option */ /* XXX 2.48 */ #if 0 if (cumap->flag & CUMA_DRAW_CFRA) { immUniformColor3ub(0x60, 0xc0, 0x40); immBegin(GPU_PRIM_LINES, 2); immVertex2f(pos, rect->xmin + zoomx * (cumap->sample[0] - offsx), rect->ymin); immVertex2f(pos, rect->xmin + zoomx * (cumap->sample[0] - offsx), rect->ymax); immEnd(); } #endif /* sample option */ if (cumap->flag & CUMA_DRAW_SAMPLE) { immBegin(GPU_PRIM_LINES, 2); /* will draw one of the following 3 lines */ if (but->a1 == UI_GRAD_H) { float tsample[3]; float hsv[3]; linearrgb_to_srgb_v3_v3(tsample, cumap->sample); rgb_to_hsv_v(tsample, hsv); immUniformColor3ub(240, 240, 240); immVertex2f(pos, rect->xmin + zoomx * (hsv[0] - offsx), rect->ymin); immVertex2f(pos, rect->xmin + zoomx * (hsv[0] - offsx), rect->ymax); } else if (cumap->cur == 3) { float lum = IMB_colormanagement_get_luminance(cumap->sample); immUniformColor3ub(240, 240, 240); immVertex2f(pos, rect->xmin + zoomx * (lum - offsx), rect->ymin); immVertex2f(pos, rect->xmin + zoomx * (lum - offsx), rect->ymax); } else { if (cumap->cur == 0) { immUniformColor3ub(240, 100, 100); } else if (cumap->cur == 1) { immUniformColor3ub(100, 240, 100); } else { immUniformColor3ub(100, 100, 240); } immVertex2f(pos, rect->xmin + zoomx * (cumap->sample[cumap->cur] - offsx), rect->ymin); immVertex2f(pos, rect->xmin + zoomx * (cumap->sample[cumap->cur] - offsx), rect->ymax); } immEnd(); } immUnbindProgram(); if (cuma->table == NULL) { BKE_curvemapping_changed(cumap, false); } CurveMapPoint *cmp = cuma->table; rctf line_range; /* First curve point. */ if ((cumap->flag & CUMA_EXTEND_EXTRAPOLATE) == 0) { line_range.xmin = rect->xmin; line_range.ymin = rect->ymin + zoomy * (cmp[0].y - offsy); } else { line_range.xmin = rect->xmin + zoomx * (cmp[0].x - offsx + cuma->ext_in[0]); line_range.ymin = rect->ymin + zoomy * (cmp[0].y - offsy + cuma->ext_in[1]); } /* Last curve point. */ if ((cumap->flag & CUMA_EXTEND_EXTRAPOLATE) == 0) { line_range.xmax = rect->xmax; line_range.ymax = rect->ymin + zoomy * (cmp[CM_TABLE].y - offsy); } else { line_range.xmax = rect->xmin + zoomx * (cmp[CM_TABLE].x - offsx - cuma->ext_out[0]); line_range.ymax = rect->ymin + zoomy * (cmp[CM_TABLE].y - offsy - cuma->ext_out[1]); } immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); GPU_blend(true); /* Curve filled. */ immUniformColor3ubvAlpha(wcol->item, 128); GPU_polygon_smooth(true); immBegin(GPU_PRIM_TRI_STRIP, (CM_TABLE * 2 + 2) + 4); immVertex2f(pos, line_range.xmin, rect->ymin); immVertex2f(pos, line_range.xmin, line_range.ymin); for (int a = 0; a <= CM_TABLE; a++) { float fx = rect->xmin + zoomx * (cmp[a].x - offsx); float fy = rect->ymin + zoomy * (cmp[a].y - offsy); immVertex2f(pos, fx, rect->ymin); immVertex2f(pos, fx, fy); } immVertex2f(pos, line_range.xmax, rect->ymin); immVertex2f(pos, line_range.xmax, line_range.ymax); immEnd(); GPU_polygon_smooth(false); /* Curve line. */ GPU_line_width(1.0f); immUniformColor3ubvAlpha(wcol->item, 255); GPU_line_smooth(true); immBegin(GPU_PRIM_LINE_STRIP, (CM_TABLE + 1) + 2); immVertex2f(pos, line_range.xmin, line_range.ymin); for (int a = 0; a <= CM_TABLE; a++) { float fx = rect->xmin + zoomx * (cmp[a].x - offsx); float fy = rect->ymin + zoomy * (cmp[a].y - offsy); immVertex2f(pos, fx, fy); } immVertex2f(pos, line_range.xmax, line_range.ymax); immEnd(); /* Reset state for fill & line. */ GPU_line_smooth(false); GPU_blend(false); immUnbindProgram(); /* The points, use aspect to make them visible on edges. */ format = immVertexFormat(); pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); uint col = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 4, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR); /* Calculate vertex colors based on text theme. */ float color_vert[4], color_vert_select[4]; UI_GetThemeColor4fv(TH_TEXT_HI, color_vert); UI_GetThemeColor4fv(TH_TEXT, color_vert_select); if (len_squared_v3v3(color_vert, color_vert_select) < 0.1f) { interp_v3_v3v3(color_vert, color_vert_select, color_backdrop, 0.75f); } if (len_squared_v3(color_vert) > len_squared_v3(color_vert_select)) { /* Ensure brightest text color is used for selection. */ swap_v3_v3(color_vert, color_vert_select); } cmp = cuma->curve; GPU_point_size(max_ff(1.0f, min_ff(UI_DPI_FAC / but->block->aspect * 4.0f, 4.0f))); immBegin(GPU_PRIM_POINTS, cuma->totpoint); for (int a = 0; a < cuma->totpoint; a++) { float fx = rect->xmin + zoomx * (cmp[a].x - offsx); float fy = rect->ymin + zoomy * (cmp[a].y - offsy); immAttr4fv(col, (cmp[a].flag & CUMA_SELECT) ? color_vert_select : color_vert); immVertex2f(pos, fx, fy); } immEnd(); immUnbindProgram(); /* restore scissortest */ GPU_scissor(scissor[0], scissor[1], scissor[2], scissor[3]); /* outline */ format = immVertexFormat(); pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor3ubv(wcol->outline); imm_draw_box_wire_2d(pos, rect->xmin, rect->ymin, rect->xmax, rect->ymax); immUnbindProgram(); } /** Used to draw a curve profile widget. Somewhat similar to ui_draw_but_CURVE */ void ui_draw_but_CURVEPROFILE(ARegion *ar, uiBut *but, const uiWidgetColors *wcol, const rcti *rect) { uint i; float fx, fy; CurveProfile *profile; if (but->editprofile) { profile = but->editprofile; } else { profile = (CurveProfile *)but->poin; } /* Calculate offset and zoom */ float zoomx = (BLI_rcti_size_x(rect) - 2.0f) / BLI_rctf_size_x(&profile->view_rect); float zoomy = (BLI_rcti_size_y(rect) - 2.0f) / BLI_rctf_size_y(&profile->view_rect); float offsx = profile->view_rect.xmin - (1.0f / zoomx); float offsy = profile->view_rect.ymin - (1.0f / zoomy); /* Exit early if too narrow */ if (zoomx == 0.0f) { return; } /* Test needed because path can draw outside of boundary */ int scissor[4]; GPU_scissor_get_i(scissor); rcti scissor_new = { .xmin = rect->xmin, .ymin = rect->ymin, .xmax = rect->xmax, .ymax = rect->ymax, }; rcti scissor_region = {0, ar->winx, 0, ar->winy}; BLI_rcti_isect(&scissor_new, &scissor_region, &scissor_new); GPU_scissor(scissor_new.xmin, scissor_new.ymin, BLI_rcti_size_x(&scissor_new), BLI_rcti_size_y(&scissor_new)); GPU_line_width(1.0f); GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); /* Backdrop */ float color_backdrop[4] = {0, 0, 0, 1}; if (profile->flag & PROF_USE_CLIP) { gl_shaded_color_get_fl((uchar *)wcol->inner, -20, color_backdrop); immUniformColor3fv(color_backdrop); immRectf(pos, rect->xmin, rect->ymin, rect->xmax, rect->ymax); immUniformColor3ubv((uchar *)wcol->inner); immRectf(pos, rect->xmin + zoomx * (profile->clip_rect.xmin - offsx), rect->ymin + zoomy * (profile->clip_rect.ymin - offsy), rect->xmin + zoomx * (profile->clip_rect.xmax - offsx), rect->ymin + zoomy * (profile->clip_rect.ymax - offsy)); } else { rgb_uchar_to_float(color_backdrop, (uchar *)wcol->inner); immUniformColor3fv(color_backdrop); immRectf(pos, rect->xmin, rect->ymin, rect->xmax, rect->ymax); } /* 0.25 step grid */ gl_shaded_color((uchar *)wcol->inner, -16); ui_draw_but_curve_grid(pos, rect, zoomx, zoomy, offsx, offsy, 0.25f); /* 1.0 step grid */ gl_shaded_color((uchar *)wcol->inner, -24); ui_draw_but_curve_grid(pos, rect, zoomx, zoomy, offsx, offsy, 1.0f); /* Draw the path's fill */ if (profile->table == NULL) { BKE_curveprofile_update(profile, false); } CurveProfilePoint *pts = profile->table; /* Also add the last points on the right and bottom edges to close off the fill polygon */ bool add_left_tri = profile->view_rect.xmin < 0.0f; bool add_bottom_tri = profile->view_rect.ymin < 0.0f; uint tot_points = (uint)PROF_N_TABLE(profile->path_len) + 1 + add_left_tri + add_bottom_tri; uint tot_triangles = tot_points - 2; /* Create array of the positions of the table's points */ float(*table_coords)[2] = MEM_mallocN(sizeof(*table_coords) * tot_points, "table x coords"); for (i = 0; i < (uint)PROF_N_TABLE(profile->path_len); i++) { /* Only add the points from the table here */ table_coords[i][0] = pts[i].x; table_coords[i][1] = pts[i].y; } if (add_left_tri && add_bottom_tri) { /* Add left side, bottom left corner, and bottom side points */ table_coords[tot_points - 3][0] = profile->view_rect.xmin; table_coords[tot_points - 3][1] = 1.0f; table_coords[tot_points - 2][0] = profile->view_rect.xmin; table_coords[tot_points - 2][1] = profile->view_rect.ymin; table_coords[tot_points - 1][0] = 1.0f; table_coords[tot_points - 1][1] = profile->view_rect.ymin; } else if (add_left_tri) { /* Add the left side and bottom left corner points */ table_coords[tot_points - 2][0] = profile->view_rect.xmin; table_coords[tot_points - 2][1] = 1.0f; table_coords[tot_points - 1][0] = profile->view_rect.xmin; table_coords[tot_points - 1][1] = 0.0f; } else if (add_bottom_tri) { /* Add the bottom side and bottom left corner points */ table_coords[tot_points - 2][0] = 0.0f; table_coords[tot_points - 2][1] = profile->view_rect.ymin; table_coords[tot_points - 1][0] = 1.0f; table_coords[tot_points - 1][1] = profile->view_rect.ymin; } else { /* Just add the bottom corner point. Side points would be redundant anyway */ table_coords[tot_points - 1][0] = 0.0f; table_coords[tot_points - 1][1] = 0.0f; } /* Calculate the table point indices of the triangles for the profile's fill */ uint(*tri_indices)[3] = MEM_mallocN(sizeof(*tri_indices) * tot_triangles, "return tri indices"); BLI_polyfill_calc(table_coords, tot_points, -1, tri_indices); /* Draw the triangles for the profile fill */ immUniformColor3ubvAlpha((const uchar *)wcol->item, 128); GPU_blend(true); GPU_polygon_smooth(false); immBegin(GPU_PRIM_TRIS, 3 * tot_triangles); for (i = 0; i < tot_triangles; i++) { for (uint j = 0; j < 3; j++) { uint *tri = tri_indices[i]; fx = rect->xmin + zoomx * (table_coords[tri[j]][0] - offsx); fy = rect->ymin + zoomy * (table_coords[tri[j]][1] - offsy); immVertex2f(pos, fx, fy); } } immEnd(); MEM_freeN(tri_indices); /* Draw the profile's path so the edge stands out a bit */ tot_points -= (add_left_tri + add_left_tri); GPU_line_width(1.0f); immUniformColor3ubvAlpha((const uchar *)wcol->item, 255); GPU_line_smooth(true); immBegin(GPU_PRIM_LINE_STRIP, tot_points - 1); for (i = 0; i < tot_points - 1; i++) { fx = rect->xmin + zoomx * (table_coords[i][0] - offsx); fy = rect->ymin + zoomy * (table_coords[i][1] - offsy); immVertex2f(pos, fx, fy); } immEnd(); immUnbindProgram(); MEM_freeN(table_coords); /* New GPU instructions for control points and sampled points. */ format = immVertexFormat(); pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); uint col = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 4, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR); /* Calculate vertex colors based on text theme. */ float color_vert[4], color_vert_select[4], color_sample[4]; UI_GetThemeColor4fv(TH_TEXT_HI, color_vert); UI_GetThemeColor4fv(TH_TEXT, color_vert_select); color_sample[0] = (float)wcol->item[0] / 255.0f; color_sample[1] = (float)wcol->item[1] / 255.0f; color_sample[2] = (float)wcol->item[2] / 255.0f; color_sample[3] = (float)wcol->item[3] / 255.0f; if (len_squared_v3v3(color_vert, color_vert_select) < 0.1f) { interp_v3_v3v3(color_vert, color_vert_select, color_backdrop, 0.75f); } if (len_squared_v3(color_vert) > len_squared_v3(color_vert_select)) { /* Ensure brightest text color is used for selection. */ swap_v3_v3(color_vert, color_vert_select); } /* Draw the control points. */ pts = profile->path; tot_points = (uint)profile->path_len; GPU_line_smooth(false); GPU_blend(false); GPU_point_size(max_ff(3.0f, min_ff(UI_DPI_FAC / but->block->aspect * 5.0f, 5.0f))); immBegin(GPU_PRIM_POINTS, tot_points); for (i = 0; i < tot_points; i++) { fx = rect->xmin + zoomx * (pts[i].x - offsx); fy = rect->ymin + zoomy * (pts[i].y - offsy); immAttr4fv(col, (pts[i].flag & PROF_SELECT) ? color_vert_select : color_vert); immVertex2f(pos, fx, fy); } immEnd(); /* Draw the sampled points in addition to the control points if they have been created */ pts = profile->segments; tot_points = (uint)profile->segments_len; if (tot_points > 0 && pts) { GPU_point_size(max_ff(2.0f, min_ff(UI_DPI_FAC / but->block->aspect * 3.0f, 3.0f))); immBegin(GPU_PRIM_POINTS, tot_points); for (i = 0; i < tot_points; i++) { fx = rect->xmin + zoomx * (pts[i].x - offsx); fy = rect->ymin + zoomy * (pts[i].y - offsy); immAttr4fv(col, color_sample); immVertex2f(pos, fx, fy); } immEnd(); } immUnbindProgram(); /* restore scissortest */ GPU_scissor(scissor[0], scissor[1], scissor[2], scissor[3]); /* Outline */ format = immVertexFormat(); pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); immUniformColor3ubv((const uchar *)wcol->outline); imm_draw_box_wire_2d(pos, rect->xmin, rect->ymin, rect->xmax, rect->ymax); immUnbindProgram(); } void ui_draw_but_TRACKPREVIEW(ARegion *UNUSED(ar), uiBut *but, const uiWidgetColors *UNUSED(wcol), const rcti *recti) { bool ok = false; MovieClipScopes *scopes = (MovieClipScopes *)but->poin; rctf rect = { .xmin = (float)recti->xmin + 1, .xmax = (float)recti->xmax - 1, .ymin = (float)recti->ymin + 1, .ymax = (float)recti->ymax - 1, }; int width = BLI_rctf_size_x(&rect) + 1; int height = BLI_rctf_size_y(&rect); GPU_blend(true); GPU_blend_set_func_separate( GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA); /* need scissor test, preview image can draw outside of boundary */ int scissor[4]; GPU_scissor_get_i(scissor); GPU_scissor((rect.xmin - 1), (rect.ymin - 1), (rect.xmax + 1) - (rect.xmin - 1), (rect.ymax + 1) - (rect.ymin - 1)); if (scopes->track_disabled) { float color[4] = {0.7f, 0.3f, 0.3f, 0.3f}; UI_draw_roundbox_corner_set(UI_CNR_ALL); UI_draw_roundbox_4fv( true, rect.xmin - 1, rect.ymin, rect.xmax + 1, rect.ymax + 1, 3.0f, color); ok = true; } else if ((scopes->track_search) && ((!scopes->track_preview) || (scopes->track_preview->x != width || scopes->track_preview->y != height))) { if (scopes->track_preview) { IMB_freeImBuf(scopes->track_preview); } ImBuf *tmpibuf = BKE_tracking_sample_pattern(scopes->frame_width, scopes->frame_height, scopes->track_search, scopes->track, &scopes->undist_marker, true, scopes->use_track_mask, width, height, scopes->track_pos); if (tmpibuf) { if (tmpibuf->rect_float) { IMB_rect_from_float(tmpibuf); } if (tmpibuf->rect) { scopes->track_preview = tmpibuf; } else { IMB_freeImBuf(tmpibuf); } } } if (!ok && scopes->track_preview) { GPU_matrix_push(); /* draw content of pattern area */ GPU_scissor(rect.xmin, rect.ymin, scissor[2], scissor[3]); if (width > 0 && height > 0) { ImBuf *drawibuf = scopes->track_preview; float col_sel[4], col_outline[4]; if (scopes->use_track_mask) { float color[4] = {0.0f, 0.0f, 0.0f, 0.3f}; UI_draw_roundbox_corner_set(UI_CNR_ALL); UI_draw_roundbox_4fv( true, rect.xmin - 1, rect.ymin, rect.xmax + 1, rect.ymax + 1, 3.0f, color); } IMMDrawPixelsTexState state = immDrawPixelsTexSetup(GPU_SHADER_2D_IMAGE_COLOR); immDrawPixelsTex(&state, rect.xmin, rect.ymin + 1, drawibuf->x, drawibuf->y, GL_RGBA, GL_UNSIGNED_BYTE, GL_LINEAR, drawibuf->rect, 1.0f, 1.0f, NULL); /* draw cross for pixel position */ GPU_matrix_translate_2f(rect.xmin + scopes->track_pos[0], rect.ymin + scopes->track_pos[1]); GPU_scissor(rect.xmin, rect.ymin, BLI_rctf_size_x(&rect), BLI_rctf_size_y(&rect)); GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); uint col = GPU_vertformat_attr_add(format, "color", GPU_COMP_F32, 4, GPU_FETCH_FLOAT); immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR); UI_GetThemeColor4fv(TH_SEL_MARKER, col_sel); UI_GetThemeColor4fv(TH_MARKER_OUTLINE, col_outline); /* Do stipple cross with geometry */ immBegin(GPU_PRIM_LINES, 7 * 2 * 2); float pos_sel[8] = {-10.0f, -7.0f, -4.0f, -1.0f, 2.0f, 5.0f, 8.0f, 11.0f}; for (int axe = 0; axe < 2; axe++) { for (int i = 0; i < 7; i++) { float x1 = pos_sel[i] * (1 - axe); float y1 = pos_sel[i] * axe; float x2 = pos_sel[i + 1] * (1 - axe); float y2 = pos_sel[i + 1] * axe; if (i % 2 == 1) { immAttr4fv(col, col_sel); } else { immAttr4fv(col, col_outline); } immVertex2f(pos, x1, y1); immVertex2f(pos, x2, y2); } } immEnd(); immUnbindProgram(); } GPU_matrix_pop(); ok = true; } if (!ok) { float color[4] = {0.0f, 0.0f, 0.0f, 0.3f}; UI_draw_roundbox_corner_set(UI_CNR_ALL); UI_draw_roundbox_4fv( true, rect.xmin - 1, rect.ymin, rect.xmax + 1, rect.ymax + 1, 3.0f, color); } /* outline */ draw_scope_end(&rect, scissor); GPU_blend(false); } /* ****************************************************** */ /* TODO: high quality UI drop shadows using GLSL shader and single draw call * would replace / modify the following 3 functions - merwin */ static void ui_shadowbox(uint pos, uint color, float minx, float miny, float maxx, float maxy, float shadsize, uchar alpha) { /** * <pre> * v1-_ * | -_v2 * | | * | | * | | * v7_______v3____v4 * \ | / * \ | _v5 * v8______v6_- * </pre> */ const float v1[2] = {maxx, maxy - 0.3f * shadsize}; const float v2[2] = {maxx + shadsize, maxy - 0.75f * shadsize}; const float v3[2] = {maxx, miny}; const float v4[2] = {maxx + shadsize, miny}; const float v5[2] = {maxx + 0.7f * shadsize, miny - 0.7f * shadsize}; const float v6[2] = {maxx, miny - shadsize}; const float v7[2] = {minx + 0.3f * shadsize, miny}; const float v8[2] = {minx + 0.5f * shadsize, miny - shadsize}; /* right quad */ immAttr4ub(color, 0, 0, 0, alpha); immVertex2fv(pos, v3); immVertex2fv(pos, v1); immAttr4ub(color, 0, 0, 0, 0); immVertex2fv(pos, v2); immVertex2fv(pos, v2); immVertex2fv(pos, v4); immAttr4ub(color, 0, 0, 0, alpha); immVertex2fv(pos, v3); /* corner shape */ /* immAttr4ub(color, 0, 0, 0, alpha); */ /* Not needed, done above in previous tri */ immVertex2fv(pos, v3); immAttr4ub(color, 0, 0, 0, 0); immVertex2fv(pos, v4); immVertex2fv(pos, v5); immVertex2fv(pos, v5); immVertex2fv(pos, v6); immAttr4ub(color, 0, 0, 0, alpha); immVertex2fv(pos, v3); /* bottom quad */ /* immAttr4ub(color, 0, 0, 0, alpha); */ /* Not needed, done above in previous tri */ immVertex2fv(pos, v3); immAttr4ub(color, 0, 0, 0, 0); immVertex2fv(pos, v6); immVertex2fv(pos, v8); immVertex2fv(pos, v8); immAttr4ub(color, 0, 0, 0, alpha); immVertex2fv(pos, v7); immVertex2fv(pos, v3); } void UI_draw_box_shadow(uchar alpha, float minx, float miny, float maxx, float maxy) { GPU_blend(true); GPUVertFormat *format = immVertexFormat(); uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); uint color = GPU_vertformat_attr_add( format, "color", GPU_COMP_U8, 4, GPU_FETCH_INT_TO_FLOAT_UNIT); immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR); immBegin(GPU_PRIM_TRIS, 54); /* accumulated outline boxes to make shade not linear, is more pleasant */ ui_shadowbox(pos, color, minx, miny, maxx, maxy, 11.0, (20 * alpha) >> 8); ui_shadowbox(pos, color, minx, miny, maxx, maxy, 7.0, (40 * alpha) >> 8); ui_shadowbox(pos, color, minx, miny, maxx, maxy, 5.0, (80 * alpha) >> 8); immEnd(); immUnbindProgram(); GPU_blend(false); } void ui_draw_dropshadow( const rctf *rct, float radius, float aspect, float alpha, int UNUSED(select)) { float rad; if (radius > (BLI_rctf_size_y(rct) - 10.0f) * 0.5f) { rad = (BLI_rctf_size_y(rct) - 10.0f) * 0.5f; } else { rad = radius; } int a, i = 12; #if 0 if (select) { a = i * aspect; /* same as below */ } else #endif { a = i * aspect; } GPU_blend(true); const float dalpha = alpha * 2.0f / 255.0f; float calpha = dalpha; float visibility = 1.0f; for (; i--;) { /* alpha ranges from 2 to 20 or so */ #if 0 /* Old Method (pre 2.8) */ float color[4] = {0.0f, 0.0f, 0.0f, calpha}; UI_draw_roundbox_4fv( true, rct->xmin - a, rct->ymin - a, rct->xmax + a, rct->ymax - 10.0f + a, rad + a, color); #endif /* Compute final visibility to match old method result. */ /* TODO we could just find a better fit function inside the shader instead of this. */ visibility = visibility * (1.0f - calpha); calpha += dalpha; } uiWidgetBaseParameters widget_params = { .recti.xmin = rct->xmin, .recti.ymin = rct->ymin, .recti.xmax = rct->xmax, .recti.ymax = rct->ymax - 10.0f, .rect.xmin = rct->xmin - a, .rect.ymin = rct->ymin - a, .rect.xmax = rct->xmax + a, .rect.ymax = rct->ymax - 10.0f + a, .radi = rad, .rad = rad + a, .round_corners[0] = (roundboxtype & UI_CNR_BOTTOM_LEFT) ? 1.0f : 0.0f, .round_corners[1] = (roundboxtype & UI_CNR_BOTTOM_RIGHT) ? 1.0f : 0.0f, .round_corners[2] = (roundboxtype & UI_CNR_TOP_RIGHT) ? 1.0f : 0.0f, .round_corners[3] = (roundboxtype & UI_CNR_TOP_LEFT) ? 1.0f : 0.0f, .alpha_discard = 1.0f, }; GPUBatch *batch = ui_batch_roundbox_shadow_get(); GPU_batch_program_set_builtin(batch, GPU_SHADER_2D_WIDGET_SHADOW); GPU_batch_uniform_4fv_array(batch, "parameters", 4, (float *)&widget_params); GPU_batch_uniform_1f(batch, "alpha", 1.0f - visibility); GPU_batch_draw(batch); /* outline emphasis */ GPU_line_smooth(true); float color[4] = {0.0f, 0.0f, 0.0f, 0.4f}; UI_draw_roundbox_4fv(false, rct->xmin - 0.5f, rct->ymin - 0.5f, rct->xmax + 0.5f, rct->ymax + 0.5f, radius + 0.5f, color); GPU_line_smooth(false); GPU_blend(false); }
629851.c
/* * Copyright (c) Ian F. Darwin 1986-1995. * Software written by Ian F. Darwin and others; * maintained 1995-present by Christos Zoulas and others. * * 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 immediately at the beginning of the file, without modification, * this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * fsmagic - magic based on filesystem info - directory, special files, etc. */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: fsmagic.c,v 1.75 2014/12/04 15:56:46 christos Exp $") #endif /* lint */ #include "magic.h" #include <string.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <stdlib.h> /* Since major is a function on SVR4, we cannot use `ifndef major'. */ #ifdef MAJOR_IN_MKDEV # include <sys/mkdev.h> # define HAVE_MAJOR #endif #ifdef MAJOR_IN_SYSMACROS # include <sys/sysmacros.h> # define HAVE_MAJOR #endif #ifdef major /* Might be defined in sys/types.h. */ # define HAVE_MAJOR #endif #ifdef WIN32 # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif #ifndef HAVE_MAJOR # define major(dev) (((dev) >> 8) & 0xff) # define minor(dev) ((dev) & 0xff) #endif #undef HAVE_MAJOR #ifdef S_IFLNK private int bad_link(struct magic_set *ms, int err, char *buf) { int mime = ms->flags & MAGIC_MIME; if ((mime & MAGIC_MIME_TYPE) && file_printf(ms, "inode/symlink") == -1) return -1; else if (!mime) { if (ms->flags & MAGIC_ERROR) { file_error(ms, err, "broken symbolic link to %s", buf); return -1; } if (file_printf(ms, "broken symbolic link to %s", buf) == -1) return -1; } return 1; } #endif private int handle_mime(struct magic_set *ms, int mime, const char *str) { if ((mime & MAGIC_MIME_TYPE)) { if (file_printf(ms, "inode/%s", str) == -1) return -1; if ((mime & MAGIC_MIME_ENCODING) && file_printf(ms, "; charset=") == -1) return -1; } if ((mime & MAGIC_MIME_ENCODING) && file_printf(ms, "binary") == -1) return -1; return 0; } protected int file_fsmagic(struct magic_set *ms, const char *fn, struct stat *sb) { int ret, did = 0; int mime = ms->flags & MAGIC_MIME; #ifdef S_IFLNK char buf[BUFSIZ+4]; ssize_t nch; struct stat tstatbuf; #endif if (ms->flags & MAGIC_APPLE) return 0; if (fn == NULL) return 0; #define COMMA (did++ ? ", " : "") /* * Fstat is cheaper but fails for files you don't have read perms on. * On 4.2BSD and similar systems, use lstat() to identify symlinks. */ #ifdef S_IFLNK if ((ms->flags & MAGIC_SYMLINK) == 0) ret = lstat(fn, sb); else #endif ret = stat(fn, sb); /* don't merge into if; see "ret =" above */ #ifdef WIN32 { HANDLE hFile = CreateFile((LPCSTR)fn, 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hFile != INVALID_HANDLE_VALUE) { /* * Stat failed, but we can still open it - assume it's * a block device, if nothing else. */ if (ret) { sb->st_mode = S_IFBLK; ret = 0; } switch (GetFileType(hFile)) { case FILE_TYPE_CHAR: sb->st_mode |= S_IFCHR; sb->st_mode &= ~S_IFREG; break; case FILE_TYPE_PIPE: sb->st_mode |= S_IFIFO; sb->st_mode &= ~S_IFREG; break; } CloseHandle(hFile); } } #endif if (ret) { if (ms->flags & MAGIC_ERROR) { file_error(ms, errno, "cannot stat `%s'", fn); return -1; } if (file_printf(ms, "cannot open `%s' (%s)", fn, strerror(errno)) == -1) return -1; return 0; } ret = 1; if (!mime) { #ifdef S_ISUID if (sb->st_mode & S_ISUID) if (file_printf(ms, "%ssetuid", COMMA) == -1) return -1; #endif #ifdef S_ISGID if (sb->st_mode & S_ISGID) if (file_printf(ms, "%ssetgid", COMMA) == -1) return -1; #endif #ifdef S_ISVTX if (sb->st_mode & S_ISVTX) if (file_printf(ms, "%ssticky", COMMA) == -1) return -1; #endif } switch (sb->st_mode & S_IFMT) { case S_IFDIR: if (mime) { if (handle_mime(ms, mime, "directory") == -1) return -1; } else if (file_printf(ms, "%sdirectory", COMMA) == -1) return -1; break; #ifdef S_IFCHR case S_IFCHR: /* * If -s has been specified, treat character special files * like ordinary files. Otherwise, just report that they * are block special files and go on to the next file. */ if ((ms->flags & MAGIC_DEVICES) != 0) { ret = 0; break; } if (mime) { if (handle_mime(ms, mime, "chardevice") == -1) return -1; } else { #ifdef HAVE_STRUCT_STAT_ST_RDEV # ifdef dv_unit if (file_printf(ms, "%scharacter special (%d/%d/%d)", COMMA, major(sb->st_rdev), dv_unit(sb->st_rdev), dv_subunit(sb->st_rdev)) == -1) return -1; # else if (file_printf(ms, "%scharacter special (%ld/%ld)", COMMA, (long)major(sb->st_rdev), (long)minor(sb->st_rdev)) == -1) return -1; # endif #else if (file_printf(ms, "%scharacter special", COMMA) == -1) return -1; #endif } break; #endif #ifdef S_IFBLK case S_IFBLK: /* * If -s has been specified, treat block special files * like ordinary files. Otherwise, just report that they * are block special files and go on to the next file. */ if ((ms->flags & MAGIC_DEVICES) != 0) { ret = 0; break; } if (mime) { if (handle_mime(ms, mime, "blockdevice") == -1) return -1; } else { #ifdef HAVE_STRUCT_STAT_ST_RDEV # ifdef dv_unit if (file_printf(ms, "%sblock special (%d/%d/%d)", COMMA, major(sb->st_rdev), dv_unit(sb->st_rdev), dv_subunit(sb->st_rdev)) == -1) return -1; # else if (file_printf(ms, "%sblock special (%ld/%ld)", COMMA, (long)major(sb->st_rdev), (long)minor(sb->st_rdev)) == -1) return -1; # endif #else if (file_printf(ms, "%sblock special", COMMA) == -1) return -1; #endif } break; #endif /* TODO add code to handle V7 MUX and Blit MUX files */ #ifdef S_IFIFO case S_IFIFO: if((ms->flags & MAGIC_DEVICES) != 0) break; if (mime) { if (handle_mime(ms, mime, "fifo") == -1) return -1; } else if (file_printf(ms, "%sfifo (named pipe)", COMMA) == -1) return -1; break; #endif #ifdef S_IFDOOR case S_IFDOOR: if (mime) { if (handle_mime(ms, mime, "door") == -1) return -1; } else if (file_printf(ms, "%sdoor", COMMA) == -1) return -1; break; #endif #ifdef S_IFLNK case S_IFLNK: if ((nch = readlink(fn, buf, BUFSIZ-1)) <= 0) { if (ms->flags & MAGIC_ERROR) { file_error(ms, errno, "unreadable symlink `%s'", fn); return -1; } if (mime) { if (handle_mime(ms, mime, "symlink") == -1) return -1; } else if (file_printf(ms, "%sunreadable symlink `%s' (%s)", COMMA, fn, strerror(errno)) == -1) return -1; break; } buf[nch] = '\0'; /* readlink(2) does not do this */ /* If broken symlink, say so and quit early. */ if (*buf == '/') { if (stat(buf, &tstatbuf) < 0) return bad_link(ms, errno, buf); } else { char *tmp; char buf2[BUFSIZ+BUFSIZ+4]; if ((tmp = strrchr(fn, '/')) == NULL) { tmp = buf; /* in current directory anyway */ } else { if (tmp - fn + 1 > BUFSIZ) { if (ms->flags & MAGIC_ERROR) { file_error(ms, 0, "path too long: `%s'", buf); return -1; } if (mime) { if (handle_mime(ms, mime, "x-path-too-long") == -1) return -1; } else if (file_printf(ms, "%spath too long: `%s'", COMMA, fn) == -1) return -1; break; } /* take dir part */ (void)strlcpy(buf2, fn, sizeof buf2); buf2[tmp - fn + 1] = '\0'; /* plus (rel) link */ (void)strlcat(buf2, buf, sizeof buf2); tmp = buf2; } if (stat(tmp, &tstatbuf) < 0) return bad_link(ms, errno, buf); } /* Otherwise, handle it. */ if ((ms->flags & MAGIC_SYMLINK) != 0) { const char *p; ms->flags &= MAGIC_SYMLINK; p = magic_file(ms, buf); ms->flags |= MAGIC_SYMLINK; if (p == NULL) return -1; } else { /* just print what it points to */ if (mime) { if (handle_mime(ms, mime, "symlink") == -1) return -1; } else if (file_printf(ms, "%ssymbolic link to %s", COMMA, buf) == -1) return -1; } break; #endif #ifdef S_IFSOCK #ifndef __COHERENT__ case S_IFSOCK: if (mime) { if (handle_mime(ms, mime, "socket") == -1) return -1; } else if (file_printf(ms, "%ssocket", COMMA) == -1) return -1; break; #endif #endif case S_IFREG: /* * regular file, check next possibility * * If stat() tells us the file has zero length, report here that * the file is empty, so we can skip all the work of opening and * reading the file. * But if the -s option has been given, we skip this * optimization, since on some systems, stat() reports zero * size for raw disk partitions. (If the block special device * really has zero length, the fact that it is empty will be * detected and reported correctly when we read the file.) */ if ((ms->flags & MAGIC_DEVICES) == 0 && sb->st_size == 0) { if (mime) { if (handle_mime(ms, mime, "x-empty") == -1) return -1; } else if (file_printf(ms, "%sempty", COMMA) == -1) return -1; break; } ret = 0; break; default: file_error(ms, 0, "invalid mode 0%o", sb->st_mode); return -1; /*NOTREACHED*/ } if (!mime && did && ret == 0) { if (file_printf(ms, " ") == -1) return -1; } return ret; }
720824.c
#include "copy.h" #define BUILD_NEON_INTRINSICS #define static #define _op_copy_c_dp_neon _op_copy_c_dp_neon_intrinsics #include "op_copy_color_neon.c" #undef _op_copy_c_dp_neon
426707.c
#include <stdint.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <arpa/inet.h> #include <sys/socket.h> const struct in6_addr in6addr_any = {0}; const struct in6_addr in6addr_loopback = {.__u6_addr32 = {0, 0, 0, __builtin_bswap32(1)}}; // Adapted from libctru static int _inetAtonDetail(int *outBase, size_t *outNumBytes, const char *cp, struct in_addr *inp) { int base; uint32_t val; int c; char bytes[4]; size_t num_bytes = 0; c = *cp; for(;;) { if(!isdigit(c)) return 0; val = 0; base = 10; if(c == '0') { c = *++cp; if(c == 'x' || c == 'X') { base = 16; c = *++cp; } else base = 8; } for(;;) { if(isdigit(c)) { if(base == 8 && c >= '8') return 0; val *= base; val += c - '0'; c = *++cp; } else if(base == 16 && isxdigit(c)) { val *= base; val += c + 10 - (islower(c) ? 'a' : 'A'); c = *++cp; } else break; } if(c == '.') { if(num_bytes > 3) return 0; if(val > 0xFF) return 0; bytes[num_bytes++] = val; c = *++cp; } else break; } if(c != 0) { *outNumBytes = num_bytes; *outBase = base; return 0; } switch(num_bytes) { case 0: break; case 1: if(val > 0xFFFFFF) return 0; val |= bytes[0] << 24; break; case 2: if(val > 0xFFFF) return 0; val |= bytes[0] << 24; val |= bytes[1] << 16; break; case 3: if(val > 0xFF) return 0; val |= bytes[0] << 24; val |= bytes[1] << 16; val |= bytes[2] << 8; break; } if(inp) inp->s_addr = htonl(val); *outNumBytes = num_bytes; *outBase = base; return 1; } // Adapted from libctru static const char *inet_ntop4(const void *src, char *dst, socklen_t size) { const uint8_t *ip = src; char *p; size_t i; unsigned int n; if(size < INET_ADDRSTRLEN) { errno = ENOSPC; return NULL; } for(p = dst, i = 0; i < 4; ++i) { if(i > 0) *p++ = '.'; n = ip[i]; if(n >= 100) { *p++ = n/100 + '0'; n %= 100; } if(n >= 10 || ip[i] >= 100) { *p++ = n/10 + '0'; n %= 10; } *p++ = n + '0'; } *p = 0; return dst; } static int inet_pton4(const char *src, void *dst) { int base; size_t numBytes; int ret = _inetAtonDetail(&base, &numBytes, src, (struct in_addr *)dst); return (ret == 1 && base == 10 && numBytes == 3) ? 1 : 0; } /* Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ #define INADDRSZ 4 #define IN6ADDRSZ 16 #define INT16SZ 2 /* const char * * inet_ntop6(src, dst, size) * convert IPv6 binary address into presentation (printable) format * author: * Paul Vixie, 1996. */ static const char * inet_ntop6(src, dst, size) const u_char *src; char *dst; size_t size; { /* * Note that int32_t and int16_t need only be "at least" large enough * to contain a value of the specified size. On some systems, like * Crays, there is no such thing as an integer variable with 16 bits. * Keep this in mind if you think this function should have been coded * to use pointer overlays. All the world's not a VAX. */ char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; struct { int base, len; } best = {0}, cur = {0}; u_int words[IN6ADDRSZ / INT16SZ]; int i; /* * Preprocess: * Copy the input (bytewise) array into a wordwise array. * Find the longest run of 0x00's in src[] for :: shorthanding. */ memset(words, 0, sizeof words); for (i = 0; i < IN6ADDRSZ; i++) words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); best.base = -1; cur.base = -1; for (i = 0; i < (IN6ADDRSZ / INT16SZ); i++) { if (words[i] == 0) { if (cur.base == -1) cur.base = i, cur.len = 1; else cur.len++; } else { if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) best = cur; cur.base = -1; } } } if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) best = cur; } if (best.base != -1 && best.len < 2) best.base = -1; /* * Format the result. */ tp = tmp; for (i = 0; i < (IN6ADDRSZ / INT16SZ); i++) { /* Are we inside the best run of 0x00's? */ if (best.base != -1 && i >= best.base && i < (best.base + best.len)) { if (i == best.base) *tp++ = ':'; continue; } /* Are we following an initial run of 0x00s or any real hex? */ if (i != 0) *tp++ = ':'; /* Is this address an encapsulated IPv4? */ if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) { if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp))) return (NULL); tp += strlen(tp); break; } //TuxSH: //sprintf(tp, "%x", words[i]); { char hexbuf[8]; char *e = hexbuf + 7; u_int word = words[i]; while(word > 0) { static const char digits[] = "0123456789abcdef"; *e-- = digits[word & 0xF]; word >>= 4; } memcpy(tp, e + 1, hexbuf + 8 - (e + 1)); } } /* Was it a trailing run of 0x00's? */ if (best.base != -1 && (best.base + best.len) == (IN6ADDRSZ / INT16SZ)) *tp++ = ':'; *tp++ = '\0'; /* * Check for overflow, copy, and we're done. */ if ((tp - tmp) > size) { errno = ENOSPC; return (NULL); } strcpy(dst, tmp); return (dst); } /* int * inet_pton6(src, dst) * convert presentation level address to network order binary form. * return: * 1 if `src' is a valid [RFC1884 2.2] address, else 0. * notice: * (1) does not touch `dst' unless it's returning 1. * (2) :: in a full address is silently ignored. * credit: * inspired by Mark Andrews. * author: * Paul Vixie, 1996. */ static int inet_pton6(src, dst) const char *src; u_char *dst; { static const char xdigits_l[] = "0123456789abcdef", xdigits_u[] = "0123456789ABCDEF"; u_char tmp[IN6ADDRSZ], *tp, *endp, *colonp; const char *xdigits, *curtok; int ch, saw_xdigit; u_int val; memset((tp = tmp), 0, IN6ADDRSZ); endp = tp + IN6ADDRSZ; colonp = NULL; /* Leading :: requires some special handling. */ if (*src == ':') if (*++src != ':') return (0); curtok = src; saw_xdigit = 0; val = 0; while ((ch = *src++) != '\0') { const char *pch; if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) pch = strchr((xdigits = xdigits_u), ch); if (pch != NULL) { val <<= 4; val |= (pch - xdigits); if (val > 0xffff) return (0); saw_xdigit = 1; continue; } if (ch == ':') { curtok = src; if (!saw_xdigit) { if (colonp) return (0); colonp = tp; continue; } if (tp + INT16SZ > endp) return (0); *tp++ = (u_char) (val >> 8) & 0xff; *tp++ = (u_char) val & 0xff; saw_xdigit = 0; val = 0; continue; } if (ch == '.' && ((tp + INADDRSZ) <= endp) && inet_pton4(curtok, tp) > 0) { tp += INADDRSZ; saw_xdigit = 0; break; /* '\0' was seen by inet_pton4(). */ } return (0); } if (saw_xdigit) { if (tp + INT16SZ > endp) return (0); *tp++ = (u_char) (val >> 8) & 0xff; *tp++ = (u_char) val & 0xff; } if (colonp != NULL) { /* * Since some memmove()'s erroneously fail to handle * overlapping regions, we'll do the shift by hand. */ const int n = tp - colonp; int i; for (i = 1; i <= n; i++) { endp[- i] = colonp[n - i]; colonp[n - i] = 0; } tp = endp; } if (tp != endp) return (0); /* bcopy(tmp, dst, IN6ADDRSZ); */ memcpy(dst, tmp, IN6ADDRSZ); return (1); } const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { switch(af) { case AF_INET: return inet_ntop4(src, dst, size); case AF_INET6: return inet_ntop6(src, dst, size); default: errno = EAFNOSUPPORT; return NULL; } } int inet_pton(int af, const char *src, void *dst) { switch(af) { case AF_INET: return inet_pton4(src, dst); case AF_INET6: return inet_pton6(src, dst); default: errno = EAFNOSUPPORT; return -1; } } char *inet_ntoa(struct in_addr in) { static __thread char buffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &in.s_addr, buffer, INET_ADDRSTRLEN); return buffer; } int inet_aton(const char *cp, struct in_addr *inp) { int base; size_t numBytes; return _inetAtonDetail(&base, &numBytes, cp, inp); } in_addr_t inet_addr(const char *cp) { struct in_addr addr = { .s_addr = INADDR_BROADCAST }; inet_aton(cp, &addr); return addr.s_addr; }
188490.c
/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "common.h" #include "console.h" #include "gpio.h" #include "hooks.h" #include "registers.h" #include "task.h" #include "util.h" #include "gpio_list.h" void button_event(enum gpio_signal signal) { int val = gpio_get_level(signal); ccprintf("Button %d = %d\n", signal, gpio_get_level(signal)); gpio_set_level(GPIO_LED_4, val); } /* Initialize board. */ static void board_init(void) { gpio_enable_interrupt(GPIO_SW_N); gpio_enable_interrupt(GPIO_SW_S); gpio_enable_interrupt(GPIO_SW_W); gpio_enable_interrupt(GPIO_SW_E); } DECLARE_HOOK(HOOK_INIT, board_init, HOOK_PRIO_DEFAULT);
401041.c
#include "asReflectIOBinary.h" #include "asReflectImpliment.h" ASEXPORT size_t asReflectGetBinarySize(const asReflectContainer* pReflectData, uint32_t srcCount) { uint32_t actualMemberCount = asReflectContainerMemberCount(pReflectData); return sizeof(asReflectContainer) + /*Reflect Data*/ (sizeof(asReflectEntry) * actualMemberCount) + /*Entries*/ sizeof(uint32_t) + /*Data Size*/ (size_t)pReflectData->binarySize * srcCount; /*Data Blob*/ } ASEXPORT asResults asReflectSaveToBinary( unsigned char* pDest, const size_t destSize, const asReflectContainer* pReflectData, const unsigned char* pSrc, const uint32_t srcCount) { /*Destination has space?*/ if (destSize < asReflectGetBinarySize(pReflectData, srcCount)) { return AS_FAILURE_OUT_OF_BOUNDS; } /*Save Reflection Container*/ asReflectContainer containerFinal = *pReflectData; containerFinal.data = NULL; containerFinal.entryCount = asReflectContainerMemberCount(pReflectData); memcpy(&pDest[0], &containerFinal, sizeof(asReflectContainer)); /*Save Reflection Entries*/ memcpy(&pDest[sizeof(asReflectContainer)], pReflectData->data, sizeof(asReflectEntry) * containerFinal.entryCount); /*Save Source Data Count*/ memcpy(&pDest[sizeof(asReflectContainer) + sizeof(asReflectEntry) * containerFinal.entryCount], &srcCount, sizeof(uint32_t)); /*Save Source Data*/ uint32_t finalSize = (uint32_t)pReflectData->binarySize * srcCount; memcpy(&pDest[sizeof(asReflectContainer) + (sizeof(asReflectEntry) * containerFinal.entryCount) + sizeof(uint32_t)], pSrc, finalSize); return AS_SUCCESS; } ASEXPORT asResults asReflectLoadFromBinary( unsigned char* pDest, const size_t destSize, const uint32_t destCount, const asReflectContainer* pReflectData, const unsigned char* pSrc, const size_t srcSize, uint32_t* pSrcCount, struct asReflectContainer** ppOutSrcReflectData) { if (!pSrc) { return AS_FAILURE_INVALID_PARAM; } /*Load Container*/ if (srcSize < sizeof(asReflectContainer)) { return AS_FAILURE_OUT_OF_BOUNDS; } asReflectContainer* pSrcReflectData = &pSrc[0]; /*Fix Entries Pointer*/ pSrcReflectData->data = (asReflectEntry*)&pSrc[sizeof(asReflectContainer)]; /*Get source count*/ uint32_t srcCount; memcpy(&srcCount, &pSrc[sizeof(asReflectContainer) + (sizeof(asReflectEntry) * pSrcReflectData->entryCount)], sizeof(uint32_t)); if (pSrcCount) { *pSrcCount = srcCount; } /*Get Size*/ const size_t entryCount = asReflectContainerMemberCount(pReflectData); /*Reflection Data Bounds Check*/ if (srcSize < sizeof(asReflectContainer) + (sizeof(asReflectEntry) * pSrcReflectData->entryCount) + sizeof(uint32_t)) { return AS_FAILURE_OUT_OF_BOUNDS; } if (ppOutSrcReflectData) { *ppOutSrcReflectData = &pSrcReflectData; } /*Return if Nothing to Load (just get the count)*/ if (!pDest) { return AS_SUCCESS; } /*Compare Names*/ if (strncmp(pSrcReflectData->name, pReflectData->name, 48)) { return AS_FAILURE_PARSE_ERROR; } /*Find base of Source blob*/ unsigned char* srcBlob = &pSrc[sizeof(asReflectContainer) + (sizeof(asReflectEntry) * pSrcReflectData->entryCount) + sizeof(uint32_t)]; /*Choose lesser count*/ const uint32_t countToLoad = srcCount > destCount ? destCount : srcCount; /*For each Source Entry*/ const uint32_t actualDestEntryCount = asReflectContainerMemberCount(pReflectData); for (int i = 0; i < entryCount; i++) { /*For each Destination Entry*/ for (int j = 0; j < actualDestEntryCount; j++) { /*Find Match in Destination*/ if(strncmp(&pSrcReflectData->data[i].typeName, &pReflectData->data[j].typeName, 30) == 0 && strncmp(&pSrcReflectData->data[i].varName, &pReflectData->data[j].varName, 30) == 0) { /*Chose lesser size*/ const size_t copySize = pSrcReflectData->data[i].dataSize > pReflectData->data[j].dataSize ? pReflectData->data[j].dataSize : pSrcReflectData->data[i].dataSize; /*Load each in array*/ const size_t srcStride = pSrcReflectData->binarySize; const size_t destStride = pSrcReflectData->binarySize; const asReflectEntry* srcBuffer = pSrcReflectData->data; const asReflectEntry* destBuffer = pReflectData->data; for (int k = 0; k < countToLoad; k++) { memcpy(&pDest[(destStride * k) + destBuffer[j].dataOffset], &srcBlob[(srcStride * k) + srcBuffer[i].dataOffset], copySize); } break; } } } return AS_SUCCESS; }
994439.c
/* linux/drivers/mtd/nand/s3c2410.c * * Copyright © 2004-2008 Simtec Electronics * http://armlinux.simtec.co.uk/ * Ben Dooks <[email protected]> * * Samsung S3C2410/S3C2440/S3C2412 NAND driver * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define pr_fmt(fmt) "nand-s3c2410: " fmt #ifdef CONFIG_MTD_NAND_S3C2410_DEBUG #define DEBUG #endif #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/io.h> #include <linux/ioport.h> #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/cpufreq.h> #include <linux/mtd/mtd.h> #include <linux/mtd/nand.h> #include <linux/mtd/nand_ecc.h> #include <linux/mtd/partitions.h> #include <linux/platform_data/mtd-nand-s3c2410.h> #define S3C2410_NFREG(x) (x) #define S3C2410_NFCONF S3C2410_NFREG(0x00) #define S3C2410_NFCMD S3C2410_NFREG(0x04) #define S3C2410_NFADDR S3C2410_NFREG(0x08) #define S3C2410_NFDATA S3C2410_NFREG(0x0C) #define S3C2410_NFSTAT S3C2410_NFREG(0x10) #define S3C2410_NFECC S3C2410_NFREG(0x14) #define S3C2440_NFCONT S3C2410_NFREG(0x04) #define S3C2440_NFCMD S3C2410_NFREG(0x08) #define S3C2440_NFADDR S3C2410_NFREG(0x0C) #define S3C2440_NFDATA S3C2410_NFREG(0x10) #define S3C2440_NFSTAT S3C2410_NFREG(0x20) #define S3C2440_NFMECC0 S3C2410_NFREG(0x2C) #define S3C2412_NFSTAT S3C2410_NFREG(0x28) #define S3C2412_NFMECC0 S3C2410_NFREG(0x34) #define S3C2410_NFCONF_EN (1<<15) #define S3C2410_NFCONF_INITECC (1<<12) #define S3C2410_NFCONF_nFCE (1<<11) #define S3C2410_NFCONF_TACLS(x) ((x)<<8) #define S3C2410_NFCONF_TWRPH0(x) ((x)<<4) #define S3C2410_NFCONF_TWRPH1(x) ((x)<<0) #define S3C2410_NFSTAT_BUSY (1<<0) #define S3C2440_NFCONF_TACLS(x) ((x)<<12) #define S3C2440_NFCONF_TWRPH0(x) ((x)<<8) #define S3C2440_NFCONF_TWRPH1(x) ((x)<<4) #define S3C2440_NFCONT_INITECC (1<<4) #define S3C2440_NFCONT_nFCE (1<<1) #define S3C2440_NFCONT_ENABLE (1<<0) #define S3C2440_NFSTAT_READY (1<<0) #define S3C2412_NFCONF_NANDBOOT (1<<31) #define S3C2412_NFCONT_INIT_MAIN_ECC (1<<5) #define S3C2412_NFCONT_nFCE0 (1<<1) #define S3C2412_NFSTAT_READY (1<<0) /* new oob placement block for use with hardware ecc generation */ static struct nand_ecclayout nand_hw_eccoob = { .eccbytes = 3, .eccpos = {0, 1, 2}, .oobfree = {{8, 8}} }; /* controller and mtd information */ struct s3c2410_nand_info; /** * struct s3c2410_nand_mtd - driver MTD structure * @mtd: The MTD instance to pass to the MTD layer. * @chip: The NAND chip information. * @set: The platform information supplied for this set of NAND chips. * @info: Link back to the hardware information. * @scan_res: The result from calling nand_scan_ident(). */ struct s3c2410_nand_mtd { struct mtd_info mtd; struct nand_chip chip; struct s3c2410_nand_set *set; struct s3c2410_nand_info *info; int scan_res; }; enum s3c_cpu_type { TYPE_S3C2410, TYPE_S3C2412, TYPE_S3C2440, }; enum s3c_nand_clk_state { CLOCK_DISABLE = 0, CLOCK_ENABLE, CLOCK_SUSPEND, }; /* overview of the s3c2410 nand state */ /** * struct s3c2410_nand_info - NAND controller state. * @mtds: An array of MTD instances on this controoler. * @platform: The platform data for this board. * @device: The platform device we bound to. * @clk: The clock resource for this controller. * @regs: The area mapped for the hardware registers. * @sel_reg: Pointer to the register controlling the NAND selection. * @sel_bit: The bit in @sel_reg to select the NAND chip. * @mtd_count: The number of MTDs created from this controller. * @save_sel: The contents of @sel_reg to be saved over suspend. * @clk_rate: The clock rate from @clk. * @clk_state: The current clock state. * @cpu_type: The exact type of this controller. */ struct s3c2410_nand_info { /* mtd info */ struct nand_hw_control controller; struct s3c2410_nand_mtd *mtds; struct s3c2410_platform_nand *platform; /* device info */ struct device *device; struct clk *clk; void __iomem *regs; void __iomem *sel_reg; int sel_bit; int mtd_count; unsigned long save_sel; unsigned long clk_rate; enum s3c_nand_clk_state clk_state; enum s3c_cpu_type cpu_type; #ifdef CONFIG_CPU_FREQ struct notifier_block freq_transition; #endif }; /* conversion functions */ static struct s3c2410_nand_mtd *s3c2410_nand_mtd_toours(struct mtd_info *mtd) { return container_of(mtd, struct s3c2410_nand_mtd, mtd); } static struct s3c2410_nand_info *s3c2410_nand_mtd_toinfo(struct mtd_info *mtd) { return s3c2410_nand_mtd_toours(mtd)->info; } static struct s3c2410_nand_info *to_nand_info(struct platform_device *dev) { return platform_get_drvdata(dev); } static struct s3c2410_platform_nand *to_nand_plat(struct platform_device *dev) { return dev_get_platdata(&dev->dev); } static inline int allow_clk_suspend(struct s3c2410_nand_info *info) { #ifdef CONFIG_MTD_NAND_S3C2410_CLKSTOP return 1; #else return 0; #endif } /** * s3c2410_nand_clk_set_state - Enable, disable or suspend NAND clock. * @info: The controller instance. * @new_state: State to which clock should be set. */ static void s3c2410_nand_clk_set_state(struct s3c2410_nand_info *info, enum s3c_nand_clk_state new_state) { if (!allow_clk_suspend(info) && new_state == CLOCK_SUSPEND) return; if (info->clk_state == CLOCK_ENABLE) { if (new_state != CLOCK_ENABLE) clk_disable_unprepare(info->clk); } else { if (new_state == CLOCK_ENABLE) clk_prepare_enable(info->clk); } info->clk_state = new_state; } /* timing calculations */ #define NS_IN_KHZ 1000000 /** * s3c_nand_calc_rate - calculate timing data. * @wanted: The cycle time in nanoseconds. * @clk: The clock rate in kHz. * @max: The maximum divider value. * * Calculate the timing value from the given parameters. */ static int s3c_nand_calc_rate(int wanted, unsigned long clk, int max) { int result; result = DIV_ROUND_UP((wanted * clk), NS_IN_KHZ); pr_debug("result %d from %ld, %d\n", result, clk, wanted); if (result > max) { pr_err("%d ns is too big for current clock rate %ld\n", wanted, clk); return -1; } if (result < 1) result = 1; return result; } #define to_ns(ticks, clk) (((ticks) * NS_IN_KHZ) / (unsigned int)(clk)) /* controller setup */ /** * s3c2410_nand_setrate - setup controller timing information. * @info: The controller instance. * * Given the information supplied by the platform, calculate and set * the necessary timing registers in the hardware to generate the * necessary timing cycles to the hardware. */ static int s3c2410_nand_setrate(struct s3c2410_nand_info *info) { struct s3c2410_platform_nand *plat = info->platform; int tacls_max = (info->cpu_type == TYPE_S3C2412) ? 8 : 4; int tacls, twrph0, twrph1; unsigned long clkrate = clk_get_rate(info->clk); unsigned long uninitialized_var(set), cfg, uninitialized_var(mask); unsigned long flags; /* calculate the timing information for the controller */ info->clk_rate = clkrate; clkrate /= 1000; /* turn clock into kHz for ease of use */ if (plat != NULL) { tacls = s3c_nand_calc_rate(plat->tacls, clkrate, tacls_max); twrph0 = s3c_nand_calc_rate(plat->twrph0, clkrate, 8); twrph1 = s3c_nand_calc_rate(plat->twrph1, clkrate, 8); } else { /* default timings */ tacls = tacls_max; twrph0 = 8; twrph1 = 8; } if (tacls < 0 || twrph0 < 0 || twrph1 < 0) { dev_err(info->device, "cannot get suitable timings\n"); return -EINVAL; } dev_info(info->device, "Tacls=%d, %dns Twrph0=%d %dns, Twrph1=%d %dns\n", tacls, to_ns(tacls, clkrate), twrph0, to_ns(twrph0, clkrate), twrph1, to_ns(twrph1, clkrate)); switch (info->cpu_type) { case TYPE_S3C2410: mask = (S3C2410_NFCONF_TACLS(3) | S3C2410_NFCONF_TWRPH0(7) | S3C2410_NFCONF_TWRPH1(7)); set = S3C2410_NFCONF_EN; set |= S3C2410_NFCONF_TACLS(tacls - 1); set |= S3C2410_NFCONF_TWRPH0(twrph0 - 1); set |= S3C2410_NFCONF_TWRPH1(twrph1 - 1); break; case TYPE_S3C2440: case TYPE_S3C2412: mask = (S3C2440_NFCONF_TACLS(tacls_max - 1) | S3C2440_NFCONF_TWRPH0(7) | S3C2440_NFCONF_TWRPH1(7)); set = S3C2440_NFCONF_TACLS(tacls - 1); set |= S3C2440_NFCONF_TWRPH0(twrph0 - 1); set |= S3C2440_NFCONF_TWRPH1(twrph1 - 1); break; default: BUG(); } local_irq_save(flags); cfg = readl(info->regs + S3C2410_NFCONF); cfg &= ~mask; cfg |= set; writel(cfg, info->regs + S3C2410_NFCONF); local_irq_restore(flags); dev_dbg(info->device, "NF_CONF is 0x%lx\n", cfg); return 0; } /** * s3c2410_nand_inithw - basic hardware initialisation * @info: The hardware state. * * Do the basic initialisation of the hardware, using s3c2410_nand_setrate() * to setup the hardware access speeds and set the controller to be enabled. */ static int s3c2410_nand_inithw(struct s3c2410_nand_info *info) { int ret; ret = s3c2410_nand_setrate(info); if (ret < 0) return ret; switch (info->cpu_type) { case TYPE_S3C2410: default: break; case TYPE_S3C2440: case TYPE_S3C2412: /* enable the controller and de-assert nFCE */ writel(S3C2440_NFCONT_ENABLE, info->regs + S3C2440_NFCONT); } return 0; } /** * s3c2410_nand_select_chip - select the given nand chip * @mtd: The MTD instance for this chip. * @chip: The chip number. * * This is called by the MTD layer to either select a given chip for the * @mtd instance, or to indicate that the access has finished and the * chip can be de-selected. * * The routine ensures that the nFCE line is correctly setup, and any * platform specific selection code is called to route nFCE to the specific * chip. */ static void s3c2410_nand_select_chip(struct mtd_info *mtd, int chip) { struct s3c2410_nand_info *info; struct s3c2410_nand_mtd *nmtd; struct nand_chip *this = mtd->priv; unsigned long cur; nmtd = this->priv; info = nmtd->info; if (chip != -1) s3c2410_nand_clk_set_state(info, CLOCK_ENABLE); cur = readl(info->sel_reg); if (chip == -1) { cur |= info->sel_bit; } else { if (nmtd->set != NULL && chip > nmtd->set->nr_chips) { dev_err(info->device, "invalid chip %d\n", chip); return; } if (info->platform != NULL) { if (info->platform->select_chip != NULL) (info->platform->select_chip) (nmtd->set, chip); } cur &= ~info->sel_bit; } writel(cur, info->sel_reg); if (chip == -1) s3c2410_nand_clk_set_state(info, CLOCK_SUSPEND); } /* s3c2410_nand_hwcontrol * * Issue command and address cycles to the chip */ static void s3c2410_nand_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int ctrl) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); if (cmd == NAND_CMD_NONE) return; if (ctrl & NAND_CLE) writeb(cmd, info->regs + S3C2410_NFCMD); else writeb(cmd, info->regs + S3C2410_NFADDR); } /* command and control functions */ static void s3c2440_nand_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int ctrl) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); if (cmd == NAND_CMD_NONE) return; if (ctrl & NAND_CLE) writeb(cmd, info->regs + S3C2440_NFCMD); else writeb(cmd, info->regs + S3C2440_NFADDR); } /* s3c2410_nand_devready() * * returns 0 if the nand is busy, 1 if it is ready */ static int s3c2410_nand_devready(struct mtd_info *mtd) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); return readb(info->regs + S3C2410_NFSTAT) & S3C2410_NFSTAT_BUSY; } static int s3c2440_nand_devready(struct mtd_info *mtd) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); return readb(info->regs + S3C2440_NFSTAT) & S3C2440_NFSTAT_READY; } static int s3c2412_nand_devready(struct mtd_info *mtd) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); return readb(info->regs + S3C2412_NFSTAT) & S3C2412_NFSTAT_READY; } /* ECC handling functions */ #ifdef CONFIG_MTD_NAND_S3C2410_HWECC static int s3c2410_nand_correct_data(struct mtd_info *mtd, u_char *dat, u_char *read_ecc, u_char *calc_ecc) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); unsigned int diff0, diff1, diff2; unsigned int bit, byte; pr_debug("%s(%p,%p,%p,%p)\n", __func__, mtd, dat, read_ecc, calc_ecc); diff0 = read_ecc[0] ^ calc_ecc[0]; diff1 = read_ecc[1] ^ calc_ecc[1]; diff2 = read_ecc[2] ^ calc_ecc[2]; pr_debug("%s: rd %*phN calc %*phN diff %02x%02x%02x\n", __func__, 3, read_ecc, 3, calc_ecc, diff0, diff1, diff2); if (diff0 == 0 && diff1 == 0 && diff2 == 0) return 0; /* ECC is ok */ /* sometimes people do not think about using the ECC, so check * to see if we have an 0xff,0xff,0xff read ECC and then ignore * the error, on the assumption that this is an un-eccd page. */ if (read_ecc[0] == 0xff && read_ecc[1] == 0xff && read_ecc[2] == 0xff && info->platform->ignore_unset_ecc) return 0; /* Can we correct this ECC (ie, one row and column change). * Note, this is similar to the 256 error code on smartmedia */ if (((diff0 ^ (diff0 >> 1)) & 0x55) == 0x55 && ((diff1 ^ (diff1 >> 1)) & 0x55) == 0x55 && ((diff2 ^ (diff2 >> 1)) & 0x55) == 0x55) { /* calculate the bit position of the error */ bit = ((diff2 >> 3) & 1) | ((diff2 >> 4) & 2) | ((diff2 >> 5) & 4); /* calculate the byte position of the error */ byte = ((diff2 << 7) & 0x100) | ((diff1 << 0) & 0x80) | ((diff1 << 1) & 0x40) | ((diff1 << 2) & 0x20) | ((diff1 << 3) & 0x10) | ((diff0 >> 4) & 0x08) | ((diff0 >> 3) & 0x04) | ((diff0 >> 2) & 0x02) | ((diff0 >> 1) & 0x01); dev_dbg(info->device, "correcting error bit %d, byte %d\n", bit, byte); dat[byte] ^= (1 << bit); return 1; } /* if there is only one bit difference in the ECC, then * one of only a row or column parity has changed, which * means the error is most probably in the ECC itself */ diff0 |= (diff1 << 8); diff0 |= (diff2 << 16); if ((diff0 & ~(1<<fls(diff0))) == 0) return 1; return -1; } /* ECC functions * * These allow the s3c2410 and s3c2440 to use the controller's ECC * generator block to ECC the data as it passes through] */ static void s3c2410_nand_enable_hwecc(struct mtd_info *mtd, int mode) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); unsigned long ctrl; ctrl = readl(info->regs + S3C2410_NFCONF); ctrl |= S3C2410_NFCONF_INITECC; writel(ctrl, info->regs + S3C2410_NFCONF); } static void s3c2412_nand_enable_hwecc(struct mtd_info *mtd, int mode) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); unsigned long ctrl; ctrl = readl(info->regs + S3C2440_NFCONT); writel(ctrl | S3C2412_NFCONT_INIT_MAIN_ECC, info->regs + S3C2440_NFCONT); } static void s3c2440_nand_enable_hwecc(struct mtd_info *mtd, int mode) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); unsigned long ctrl; ctrl = readl(info->regs + S3C2440_NFCONT); writel(ctrl | S3C2440_NFCONT_INITECC, info->regs + S3C2440_NFCONT); } static int s3c2410_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); ecc_code[0] = readb(info->regs + S3C2410_NFECC + 0); ecc_code[1] = readb(info->regs + S3C2410_NFECC + 1); ecc_code[2] = readb(info->regs + S3C2410_NFECC + 2); pr_debug("%s: returning ecc %*phN\n", __func__, 3, ecc_code); return 0; } static int s3c2412_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); unsigned long ecc = readl(info->regs + S3C2412_NFMECC0); ecc_code[0] = ecc; ecc_code[1] = ecc >> 8; ecc_code[2] = ecc >> 16; pr_debug("%s: returning ecc %*phN\n", __func__, 3, ecc_code); return 0; } static int s3c2440_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); unsigned long ecc = readl(info->regs + S3C2440_NFMECC0); ecc_code[0] = ecc; ecc_code[1] = ecc >> 8; ecc_code[2] = ecc >> 16; pr_debug("%s: returning ecc %06lx\n", __func__, ecc & 0xffffff); return 0; } #endif /* over-ride the standard functions for a little more speed. We can * use read/write block to move the data buffers to/from the controller */ static void s3c2410_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len) { struct nand_chip *this = mtd->priv; readsb(this->IO_ADDR_R, buf, len); } static void s3c2440_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); readsl(info->regs + S3C2440_NFDATA, buf, len >> 2); /* cleanup if we've got less than a word to do */ if (len & 3) { buf += len & ~3; for (; len & 3; len--) *buf++ = readb(info->regs + S3C2440_NFDATA); } } static void s3c2410_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len) { struct nand_chip *this = mtd->priv; writesb(this->IO_ADDR_W, buf, len); } static void s3c2440_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len) { struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd); writesl(info->regs + S3C2440_NFDATA, buf, len >> 2); /* cleanup any fractional write */ if (len & 3) { buf += len & ~3; for (; len & 3; len--, buf++) writeb(*buf, info->regs + S3C2440_NFDATA); } } /* cpufreq driver support */ #ifdef CONFIG_CPU_FREQ static int s3c2410_nand_cpufreq_transition(struct notifier_block *nb, unsigned long val, void *data) { struct s3c2410_nand_info *info; unsigned long newclk; info = container_of(nb, struct s3c2410_nand_info, freq_transition); newclk = clk_get_rate(info->clk); if ((val == CPUFREQ_POSTCHANGE && newclk < info->clk_rate) || (val == CPUFREQ_PRECHANGE && newclk > info->clk_rate)) { s3c2410_nand_setrate(info); } return 0; } static inline int s3c2410_nand_cpufreq_register(struct s3c2410_nand_info *info) { info->freq_transition.notifier_call = s3c2410_nand_cpufreq_transition; return cpufreq_register_notifier(&info->freq_transition, CPUFREQ_TRANSITION_NOTIFIER); } static inline void s3c2410_nand_cpufreq_deregister(struct s3c2410_nand_info *info) { cpufreq_unregister_notifier(&info->freq_transition, CPUFREQ_TRANSITION_NOTIFIER); } #else static inline int s3c2410_nand_cpufreq_register(struct s3c2410_nand_info *info) { return 0; } static inline void s3c2410_nand_cpufreq_deregister(struct s3c2410_nand_info *info) { } #endif /* device management functions */ static int s3c24xx_nand_remove(struct platform_device *pdev) { struct s3c2410_nand_info *info = to_nand_info(pdev); if (info == NULL) return 0; s3c2410_nand_cpufreq_deregister(info); /* Release all our mtds and their partitions, then go through * freeing the resources used */ if (info->mtds != NULL) { struct s3c2410_nand_mtd *ptr = info->mtds; int mtdno; for (mtdno = 0; mtdno < info->mtd_count; mtdno++, ptr++) { pr_debug("releasing mtd %d (%p)\n", mtdno, ptr); nand_release(&ptr->mtd); } } /* free the common resources */ if (!IS_ERR(info->clk)) s3c2410_nand_clk_set_state(info, CLOCK_DISABLE); return 0; } static int s3c2410_nand_add_partition(struct s3c2410_nand_info *info, struct s3c2410_nand_mtd *mtd, struct s3c2410_nand_set *set) { if (set) { mtd->mtd.name = set->name; return mtd_device_parse_register(&mtd->mtd, NULL, NULL, set->partitions, set->nr_partitions); } return -ENODEV; } /** * s3c2410_nand_init_chip - initialise a single instance of an chip * @info: The base NAND controller the chip is on. * @nmtd: The new controller MTD instance to fill in. * @set: The information passed from the board specific platform data. * * Initialise the given @nmtd from the information in @info and @set. This * readies the structure for use with the MTD layer functions by ensuring * all pointers are setup and the necessary control routines selected. */ static void s3c2410_nand_init_chip(struct s3c2410_nand_info *info, struct s3c2410_nand_mtd *nmtd, struct s3c2410_nand_set *set) { struct nand_chip *chip = &nmtd->chip; void __iomem *regs = info->regs; chip->write_buf = s3c2410_nand_write_buf; chip->read_buf = s3c2410_nand_read_buf; chip->select_chip = s3c2410_nand_select_chip; chip->chip_delay = 50; chip->priv = nmtd; chip->options = set->options; chip->controller = &info->controller; switch (info->cpu_type) { case TYPE_S3C2410: chip->IO_ADDR_W = regs + S3C2410_NFDATA; info->sel_reg = regs + S3C2410_NFCONF; info->sel_bit = S3C2410_NFCONF_nFCE; chip->cmd_ctrl = s3c2410_nand_hwcontrol; chip->dev_ready = s3c2410_nand_devready; break; case TYPE_S3C2440: chip->IO_ADDR_W = regs + S3C2440_NFDATA; info->sel_reg = regs + S3C2440_NFCONT; info->sel_bit = S3C2440_NFCONT_nFCE; chip->cmd_ctrl = s3c2440_nand_hwcontrol; chip->dev_ready = s3c2440_nand_devready; chip->read_buf = s3c2440_nand_read_buf; chip->write_buf = s3c2440_nand_write_buf; break; case TYPE_S3C2412: chip->IO_ADDR_W = regs + S3C2440_NFDATA; info->sel_reg = regs + S3C2440_NFCONT; info->sel_bit = S3C2412_NFCONT_nFCE0; chip->cmd_ctrl = s3c2440_nand_hwcontrol; chip->dev_ready = s3c2412_nand_devready; if (readl(regs + S3C2410_NFCONF) & S3C2412_NFCONF_NANDBOOT) dev_info(info->device, "System booted from NAND\n"); break; } chip->IO_ADDR_R = chip->IO_ADDR_W; nmtd->info = info; nmtd->mtd.priv = chip; nmtd->mtd.owner = THIS_MODULE; nmtd->set = set; #ifdef CONFIG_MTD_NAND_S3C2410_HWECC chip->ecc.calculate = s3c2410_nand_calculate_ecc; chip->ecc.correct = s3c2410_nand_correct_data; chip->ecc.mode = NAND_ECC_HW; chip->ecc.strength = 1; switch (info->cpu_type) { case TYPE_S3C2410: chip->ecc.hwctl = s3c2410_nand_enable_hwecc; chip->ecc.calculate = s3c2410_nand_calculate_ecc; break; case TYPE_S3C2412: chip->ecc.hwctl = s3c2412_nand_enable_hwecc; chip->ecc.calculate = s3c2412_nand_calculate_ecc; break; case TYPE_S3C2440: chip->ecc.hwctl = s3c2440_nand_enable_hwecc; chip->ecc.calculate = s3c2440_nand_calculate_ecc; break; } #else chip->ecc.mode = NAND_ECC_SOFT; #endif if (set->ecc_layout != NULL) chip->ecc.layout = set->ecc_layout; if (set->disable_ecc) chip->ecc.mode = NAND_ECC_NONE; switch (chip->ecc.mode) { case NAND_ECC_NONE: dev_info(info->device, "NAND ECC disabled\n"); break; case NAND_ECC_SOFT: dev_info(info->device, "NAND soft ECC\n"); break; case NAND_ECC_HW: dev_info(info->device, "NAND hardware ECC\n"); break; default: dev_info(info->device, "NAND ECC UNKNOWN\n"); break; } /* If you use u-boot BBT creation code, specifying this flag will * let the kernel fish out the BBT from the NAND, and also skip the * full NAND scan that can take 1/2s or so. Little things... */ if (set->flash_bbt) { chip->bbt_options |= NAND_BBT_USE_FLASH; chip->options |= NAND_SKIP_BBTSCAN; } } /** * s3c2410_nand_update_chip - post probe update * @info: The controller instance. * @nmtd: The driver version of the MTD instance. * * This routine is called after the chip probe has successfully completed * and the relevant per-chip information updated. This call ensure that * we update the internal state accordingly. * * The internal state is currently limited to the ECC state information. */ static void s3c2410_nand_update_chip(struct s3c2410_nand_info *info, struct s3c2410_nand_mtd *nmtd) { struct nand_chip *chip = &nmtd->chip; dev_dbg(info->device, "chip %p => page shift %d\n", chip, chip->page_shift); if (chip->ecc.mode != NAND_ECC_HW) return; /* change the behaviour depending on whether we are using * the large or small page nand device */ if (chip->page_shift > 10) { chip->ecc.size = 256; chip->ecc.bytes = 3; } else { chip->ecc.size = 512; chip->ecc.bytes = 3; chip->ecc.layout = &nand_hw_eccoob; } } /* s3c24xx_nand_probe * * called by device layer when it finds a device matching * one our driver can handled. This code checks to see if * it can allocate all necessary resources then calls the * nand layer to look for devices */ static int s3c24xx_nand_probe(struct platform_device *pdev) { struct s3c2410_platform_nand *plat = to_nand_plat(pdev); enum s3c_cpu_type cpu_type; struct s3c2410_nand_info *info; struct s3c2410_nand_mtd *nmtd; struct s3c2410_nand_set *sets; struct resource *res; int err = 0; int size; int nr_sets; int setno; cpu_type = platform_get_device_id(pdev)->driver_data; pr_debug("s3c2410_nand_probe(%p)\n", pdev); info = devm_kzalloc(&pdev->dev, sizeof(*info), GFP_KERNEL); if (info == NULL) { err = -ENOMEM; goto exit_error; } platform_set_drvdata(pdev, info); spin_lock_init(&info->controller.lock); init_waitqueue_head(&info->controller.wq); /* get the clock source and enable it */ info->clk = devm_clk_get(&pdev->dev, "nand"); if (IS_ERR(info->clk)) { dev_err(&pdev->dev, "failed to get clock\n"); err = -ENOENT; goto exit_error; } s3c2410_nand_clk_set_state(info, CLOCK_ENABLE); /* allocate and map the resource */ /* currently we assume we have the one resource */ res = pdev->resource; size = resource_size(res); info->device = &pdev->dev; info->platform = plat; info->cpu_type = cpu_type; info->regs = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(info->regs)) { err = PTR_ERR(info->regs); goto exit_error; } dev_dbg(&pdev->dev, "mapped registers at %p\n", info->regs); /* initialise the hardware */ err = s3c2410_nand_inithw(info); if (err != 0) goto exit_error; sets = (plat != NULL) ? plat->sets : NULL; nr_sets = (plat != NULL) ? plat->nr_sets : 1; info->mtd_count = nr_sets; /* allocate our information */ size = nr_sets * sizeof(*info->mtds); info->mtds = devm_kzalloc(&pdev->dev, size, GFP_KERNEL); if (info->mtds == NULL) { err = -ENOMEM; goto exit_error; } /* initialise all possible chips */ nmtd = info->mtds; for (setno = 0; setno < nr_sets; setno++, nmtd++) { pr_debug("initialising set %d (%p, info %p)\n", setno, nmtd, info); s3c2410_nand_init_chip(info, nmtd, sets); nmtd->scan_res = nand_scan_ident(&nmtd->mtd, (sets) ? sets->nr_chips : 1, NULL); if (nmtd->scan_res == 0) { s3c2410_nand_update_chip(info, nmtd); nand_scan_tail(&nmtd->mtd); s3c2410_nand_add_partition(info, nmtd, sets); } if (sets != NULL) sets++; } err = s3c2410_nand_cpufreq_register(info); if (err < 0) { dev_err(&pdev->dev, "failed to init cpufreq support\n"); goto exit_error; } if (allow_clk_suspend(info)) { dev_info(&pdev->dev, "clock idle support enabled\n"); s3c2410_nand_clk_set_state(info, CLOCK_SUSPEND); } pr_debug("initialised ok\n"); return 0; exit_error: s3c24xx_nand_remove(pdev); if (err == 0) err = -EINVAL; return err; } /* PM Support */ #ifdef CONFIG_PM static int s3c24xx_nand_suspend(struct platform_device *dev, pm_message_t pm) { struct s3c2410_nand_info *info = platform_get_drvdata(dev); if (info) { info->save_sel = readl(info->sel_reg); /* For the moment, we must ensure nFCE is high during * the time we are suspended. This really should be * handled by suspending the MTDs we are using, but * that is currently not the case. */ writel(info->save_sel | info->sel_bit, info->sel_reg); s3c2410_nand_clk_set_state(info, CLOCK_DISABLE); } return 0; } static int s3c24xx_nand_resume(struct platform_device *dev) { struct s3c2410_nand_info *info = platform_get_drvdata(dev); unsigned long sel; if (info) { s3c2410_nand_clk_set_state(info, CLOCK_ENABLE); s3c2410_nand_inithw(info); /* Restore the state of the nFCE line. */ sel = readl(info->sel_reg); sel &= ~info->sel_bit; sel |= info->save_sel & info->sel_bit; writel(sel, info->sel_reg); s3c2410_nand_clk_set_state(info, CLOCK_SUSPEND); } return 0; } #else #define s3c24xx_nand_suspend NULL #define s3c24xx_nand_resume NULL #endif /* driver device registration */ static struct platform_device_id s3c24xx_driver_ids[] = { { .name = "s3c2410-nand", .driver_data = TYPE_S3C2410, }, { .name = "s3c2440-nand", .driver_data = TYPE_S3C2440, }, { .name = "s3c2412-nand", .driver_data = TYPE_S3C2412, }, { .name = "s3c6400-nand", .driver_data = TYPE_S3C2412, /* compatible with 2412 */ }, { } }; MODULE_DEVICE_TABLE(platform, s3c24xx_driver_ids); static struct platform_driver s3c24xx_nand_driver = { .probe = s3c24xx_nand_probe, .remove = s3c24xx_nand_remove, .suspend = s3c24xx_nand_suspend, .resume = s3c24xx_nand_resume, .id_table = s3c24xx_driver_ids, .driver = { .name = "s3c24xx-nand", }, }; module_platform_driver(s3c24xx_nand_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Ben Dooks <[email protected]>"); MODULE_DESCRIPTION("S3C24XX MTD NAND driver");
641213.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE457_Use_of_Uninitialized_Variable__int_64a.c Label Definition File: CWE457_Use_of_Uninitialized_Variable.c.label.xml Template File: sources-sinks-64a.tmpl.c */ /* * @description * CWE: 457 Use of Uninitialized Variable * BadSource: no_init Don't initialize data * GoodSource: Initialize data * Sinks: use * GoodSink: Initialize then use data * BadSink : Use data * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD /* bad function declaration */ void CWE457_Use_of_Uninitialized_Variable__int_64b_badSink(void * dataVoidPtr); void CWE457_Use_of_Uninitialized_Variable__int_64_bad() { int data; /* POTENTIAL FLAW: Don't initialize data */ ; /* empty statement needed for some flow variants */ CWE457_Use_of_Uninitialized_Variable__int_64b_badSink(&data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE457_Use_of_Uninitialized_Variable__int_64b_goodG2BSink(void * dataVoidPtr); static void goodG2B() { int data; /* FIX: Initialize data */ data = 5; CWE457_Use_of_Uninitialized_Variable__int_64b_goodG2BSink(&data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE457_Use_of_Uninitialized_Variable__int_64b_goodB2GSink(void * dataVoidPtr); static void goodB2G() { int data; /* POTENTIAL FLAW: Don't initialize data */ ; /* empty statement needed for some flow variants */ CWE457_Use_of_Uninitialized_Variable__int_64b_goodB2GSink(&data); } void CWE457_Use_of_Uninitialized_Variable__int_64_good() { goodG2B(); goodB2G(); } #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()..."); CWE457_Use_of_Uninitialized_Variable__int_64_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE457_Use_of_Uninitialized_Variable__int_64_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
666555.c
/* ** EPITECH PROJECT, 2020 ** player_animation.c ** File description: ** player animation */ #include "my.h" void walk_animation(my_t *run) { if (sfTime_asMilliseconds(sfClock_getElapsedTime (run->clock_player_walking)) > 80 * run->x) { run->rect_player_walking.left += 59; if (run->rect_player_walking.left >= 472) run->rect_player_walking.left = 0; if (!run->jump) sfSprite_setTextureRect(run->player_sprite, run->rect_player_walking); sfClock_restart(run->clock_player_walking); } } void jump_animation(my_t *run) { if (sfTime_asMilliseconds(sfClock_getElapsedTime (run->clock_player_jumping)) > 100) { run->rect_player_jumping.left += 48; if (run->rect_player_jumping.left >= 192) run->rect_player_jumping.left = 0; sfClock_restart(run->clock_player_jumping); } } void run_animation(my_t *run) { if (sfTime_asMilliseconds(sfClock_getElapsedTime (run->clock_player_running)) > 40) { run->rect_player_running.left += 60; if (run->rect_player_running.left >= 480) run->rect_player_running.left = 0; sfClock_restart(run->clock_player_running); } } void barrel_animation(my_t *run) { if (sfTime_asMilliseconds(sfClock_getElapsedTime (run->clock_barrel)) > 60) { run->rect_barrel.left += 96; if (run->rect_barrel.left >= 480) run->rect_barrel.left = 0; sfSprite_setTextureRect(run->barrel_sprite, run->rect_barrel); sfClock_restart(run->clock_barrel); } } void player_animation(my_t *run) { sfSprite_setPosition(run->player_sprite, run->player_position); sfRenderWindow_drawSprite(run->window, run->player_sprite, NULL); walk_animation(run); jump_animation(run); run_animation(run); barrel_animation(run); }
748266.c
/**************************************************************************** * * Copyright 2016 Samsung Electronics 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <tinyara/config.h> #include <netdb.h> #include <errno.h> #include <string.h> #include "lib_internal.h" #include "netdb/lib_netdb.h" #ifdef CONFIG_LIBC_NETDB int getnameinfo(const struct sockaddr *sa, size_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) { struct sockaddr_in *sin = (struct sockaddr_in *)sa; struct hostent *hp; char tmpserv[16]; if (serv != NULL) { snprintf(tmpserv, sizeof(tmpserv), "%d", ntohs(sin->sin_port)); if (strlcpy(serv, tmpserv, servlen) >= servlen) { return (EAI_MEMORY); } } if (host != NULL) { if (flags & NI_NUMERICHOST) { if (strlcpy(host, (const char *)inet_ntoa(sin->sin_addr), hostlen) >= hostlen) { return (EAI_MEMORY); } else { return (0); } } else { hp = gethostbyaddr((char *)&sin->sin_addr, sizeof(struct in_addr), AF_INET); if (hp == NULL) { return (NO_DATA); } if (strlcpy(host, hp->h_name, hostlen) >= hostlen) { return (EAI_MEMORY); } else { return (0); } } } return (0); } #endif /* CONFIG_LIBC_NETDB */
58702.c
/* * Copyright (C) 2014-2018 Fredrik Wikstrom <[email protected]> * * 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 <interfaces/zip.h> #include "../zip_vectors.h" /****** zip.library/zip_file_get_external_attributes ****************************************** * * NAME * zip_file_get_external_attributes -- Description * * SYNOPSIS * zip_int32_t zip_file_get_external_attributes(zip_t *za, zip_uint64_t idx, * zip_flags_t flags, zip_uint8_t * opsys, zip_uint32_t * attributes); * * FUNCTION * * INPUTS * za - * idx - * flags - * opsys - * attributes - * * RESULT * The result ... * * EXAMPLE * * NOTES * * BUGS * * SEE ALSO * ***************************************************************************** * */ zip_int32_t _main_zip_file_get_external_attributes(struct ZipIFace *Self, zip_t *za, zip_uint64_t idx, zip_flags_t flags, zip_uint8_t *opsys, zip_uint32_t *attributes) { return zip_file_get_external_attributes(za, idx, flags, opsys, (zip_uint32_t *)attributes); }
220079.c
/* * ESPRESSIF MIT License * * Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD> * * Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case, * it is 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> #include "esp_log.h" #include "board.h" #include "i2c_bus.h" #include "es7210.h" #define I2S_DSP_MODE 0 #define MCLK_DIV_FRE 256 /* ES7210 address*/ #define ES7210_ADDR ES7210_AD1_AD0_00 #define ES7210_MCLK_SOURCE FROM_CLOCK_DOUBLE_PIN /* In master mode, 0 : MCLK from pad 1 : MCLK from clock doubler */ #define FROM_PAD_PIN 0 #define FROM_CLOCK_DOUBLE_PIN 1 /* * Operate function of ADC */ audio_hal_func_t AUDIO_CODEC_ES7210_DEFAULT_HANDLE = { .audio_codec_initialize = es7210_adc_init, .audio_codec_deinitialize = es7210_adc_deinit, .audio_codec_ctrl = es7210_adc_ctrl_state, .audio_codec_config_iface = es7210_adc_config_i2s, .audio_codec_set_mute = es7210_set_mute, .audio_codec_set_volume = es7210_adc_set_volume, .audio_hal_lock = NULL, .handle = NULL, }; /* * Clock coefficient structer */ struct _coeff_div { uint32_t mclk; /* mclk frequency */ uint32_t lrck; /* lrck */ uint8_t ss_ds; uint8_t adc_div; /* adcclk divider */ uint8_t dll; /* dll_bypass */ uint8_t doubler; /* doubler enable */ uint8_t osr; /* adc osr */ uint8_t mclk_src; /* select mclk source */ uint32_t lrck_h; /* The high 4 bits of lrck */ uint32_t lrck_l; /* The low 8 bits of lrck */ }; static char *TAG = "ES7210"; static i2c_bus_handle_t i2c_handle; static es7210_input_mics_t mic_select = ES7210_INPUT_MIC1 | ES7210_INPUT_MIC2; /* Number of microphones */ /* Codec hifi mclk clock divider coefficients * MEMBER REG * mclk: 0x03 * lrck: standard * ss_ds: -- * adc_div: 0x02 * dll: 0x06 * doubler: 0x02 * osr: 0x07 * mclk_src: 0x03 * lrckh: 0x04 * lrckl: 0x05 */ static const struct _coeff_div coeff_div[] = { //mclk lrck ss_ds adc_div dll doubler osr mclk_src lrckh lrckl /* 8k */ {12288000, 8000 , 0x00, 0x03, 0x01, 0x00, 0x20, 0x00, 0x06, 0x00}, {16384000, 8000 , 0x00, 0x04, 0x01, 0x00, 0x20, 0x00, 0x08, 0x00}, {19200000, 8000 , 0x00, 0x1e, 0x00, 0x01, 0x28, 0x00, 0x09, 0x60}, {4096000, 8000 , 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00}, /* 11.025k */ {11289600, 11025, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x01, 0x00}, /* 12k */ {12288000, 12000, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x04, 0x00}, {19200000, 12000, 0x00, 0x14, 0x00, 0x01, 0x28, 0x00, 0x06, 0x40}, /* 16k */ {4096000, 16000, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00}, {19200000, 16000, 0x00, 0x0a, 0x00, 0x00, 0x1e, 0x00, 0x04, 0x80}, {16384000, 16000, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x04, 0x00}, {12288000, 16000, 0x00, 0x03, 0x01, 0x01, 0x20, 0x00, 0x03, 0x00}, /* 22.05k */ {11289600, 22050, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00}, /* 24k */ {12288000, 24000, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00}, {19200000, 24000, 0x00, 0x0a, 0x00, 0x01, 0x28, 0x00, 0x03, 0x20}, /* 32k */ {12288000, 32000, 0x00, 0x03, 0x00, 0x00, 0x20, 0x00, 0x01, 0x80}, {16384000, 32000, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00}, {19200000, 32000, 0x00, 0x05, 0x00, 0x00, 0x1e, 0x00, 0x02, 0x58}, /* 44.1k */ {11289600, 44100, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00}, /* 48k */ {12288000, 48000, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00}, {19200000, 48000, 0x00, 0x05, 0x00, 0x01, 0x28, 0x00, 0x01, 0x90}, /* 64k */ {16384000, 64000, 0x01, 0x01, 0x01, 0x00, 0x20, 0x00, 0x01, 0x00}, {19200000, 64000, 0x00, 0x05, 0x00, 0x01, 0x1e, 0x00, 0x01, 0x2c}, /* 88.2k */ {11289600, 88200, 0x01, 0x01, 0x01, 0x01, 0x20, 0x00, 0x00, 0x80}, /* 96k */ {12288000, 96000, 0x01, 0x01, 0x01, 0x01, 0x20, 0x00, 0x00, 0x80}, {19200000, 96000, 0x01, 0x05, 0x00, 0x01, 0x28, 0x00, 0x00, 0xc8}, }; static esp_err_t es7210_write_reg(uint8_t reg_addr, uint8_t data) { return i2c_bus_write_bytes(i2c_handle, ES7210_ADDR, &reg_addr, sizeof(reg_addr), &data, sizeof(data)); } static esp_err_t es7210_update_reg_bit(uint8_t reg_addr, uint8_t update_bits, uint8_t data) { uint8_t regv; regv = es7210_read_reg(reg_addr); regv = (regv & (~update_bits)) | (update_bits & data); return es7210_write_reg(reg_addr, regv); } static int i2c_init() { int ret = 0; i2c_config_t es_i2c_cfg = { .mode = I2C_MODE_MASTER, .sda_pullup_en = GPIO_PULLUP_ENABLE, .scl_pullup_en = GPIO_PULLUP_ENABLE, .master.clk_speed = 100000, }; ret = get_i2c_pins(I2C_NUM_0, &es_i2c_cfg); AUDIO_CHECK(TAG, !ret, return ESP_FAIL;, "getting i2c pins error"); i2c_handle = i2c_bus_create(I2C_NUM_0, &es_i2c_cfg); return ret; } static int get_coeff(uint32_t mclk, uint32_t lrck) { for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) { if (coeff_div[i].lrck == lrck && coeff_div[i].mclk == mclk) return i; } return -1; } int8_t get_es7210_mclk_src(void) { return ES7210_MCLK_SOURCE; } int es7210_read_reg(uint8_t reg_addr) { uint8_t data; i2c_bus_read_bytes(i2c_handle, ES7210_ADDR, &reg_addr, sizeof(reg_addr), &data, sizeof(data)); return (int)data; } esp_err_t es7210_config_sample(audio_hal_iface_samples_t sample) { uint8_t regv; int coeff; int sample_fre = 0; int mclk_fre = 0; esp_err_t ret = ESP_OK; switch (sample) { case AUDIO_HAL_08K_SAMPLES: sample_fre = 8000; break; case AUDIO_HAL_11K_SAMPLES: sample_fre = 11025; break; case AUDIO_HAL_16K_SAMPLES: sample_fre = 16000; break; case AUDIO_HAL_22K_SAMPLES: sample_fre = 22050; break; case AUDIO_HAL_24K_SAMPLES: sample_fre = 24000; break; case AUDIO_HAL_32K_SAMPLES: sample_fre = 32000; break; case AUDIO_HAL_44K_SAMPLES: sample_fre = 44100; break; case AUDIO_HAL_48K_SAMPLES: sample_fre = 48000; break; default: ESP_LOGE(TAG, "Unable to configure sample rate %dHz", sample_fre); break; } mclk_fre = sample_fre * MCLK_DIV_FRE; coeff = get_coeff(mclk_fre, sample_fre); if (coeff < 0) { ESP_LOGE(TAG, "Unable to configure sample rate %dHz with %dHz MCLK", sample_fre, mclk_fre); return ESP_FAIL; } /* Set clock parammeters */ if (coeff >= 0) { /* Set adc_div & doubler & dll */ regv = es7210_read_reg(ES7210_MAINCLK_REG02) & 0x00; regv |= coeff_div[coeff].adc_div; regv |= coeff_div[coeff].doubler << 6; regv |= coeff_div[coeff].dll << 7; ret |= es7210_write_reg(ES7210_MAINCLK_REG02, regv); /* Set osr */ regv = coeff_div[coeff].osr; ret |= es7210_write_reg(ES7210_OSR_REG07, regv); /* Set lrck */ regv = coeff_div[coeff].lrck_h; ret |= es7210_write_reg(ES7210_LRCK_DIVH_REG04, regv); regv = coeff_div[coeff].lrck_l; ret |= es7210_write_reg(ES7210_LRCK_DIVL_REG05, regv); } return ret; } esp_err_t es7210_mic_select(es7210_input_mics_t mic) { esp_err_t ret = ESP_OK; mic_select = mic; if (mic_select & (ES7210_INPUT_MIC1 | ES7210_INPUT_MIC2 | ES7210_INPUT_MIC3 | ES7210_INPUT_MIC4)) { for (int i = 0; i < 4; i++) { ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43 + i, 0x10, 0x00); } ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0xff); ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0xff); if (mic_select & ES7210_INPUT_MIC1) { ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC1"); ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x0b, 0x00); ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0x00); ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43, 0x10, 0x10); } if (mic_select & ES7210_INPUT_MIC2) { ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC2"); ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x0b, 0x00); ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0x00); ret |= es7210_update_reg_bit(ES7210_MIC2_GAIN_REG44, 0x10, 0x10); } if (mic_select & ES7210_INPUT_MIC3) { ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC3"); ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x15, 0x00); ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0x00); ret |= es7210_update_reg_bit(ES7210_MIC3_GAIN_REG45, 0x10, 0x10); } if (mic_select & ES7210_INPUT_MIC4) { ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC4"); ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x15, 0x00); ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0x00); ret |= es7210_update_reg_bit(ES7210_MIC4_GAIN_REG46, 0x10, 0x10); } } else { ESP_LOGE(TAG, "Microphone selection error"); return ESP_FAIL; } return ret; } esp_err_t es7210_adc_init(audio_hal_codec_config_t *codec_cfg) { esp_err_t ret = ESP_OK; i2c_init(); ret |= es7210_write_reg(ES7210_RESET_REG00, 0xff); ret |= es7210_write_reg(ES7210_RESET_REG00, 0x41); ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, 0x1f); ret |= es7210_write_reg(ES7210_TIME_CONTROL0_REG09, 0x30); /* Set chip state cycle */ ret |= es7210_write_reg(ES7210_TIME_CONTROL1_REG0A, 0x30); /* Set power on state cycle */ ret |= es7210_write_reg(ES7210_ADC12_HPF2_REG23, 0x2a); /* Quick setup */ ret |= es7210_write_reg(ES7210_ADC12_HPF1_REG22, 0x0a); ret |= es7210_write_reg(ES7210_ADC34_HPF2_REG20, 0x0a); ret |= es7210_write_reg(ES7210_ADC34_HPF1_REG21, 0x2a); /* Set master/slave audio interface */ audio_hal_codec_i2s_iface_t *i2s_cfg = & (codec_cfg->i2s_iface); switch (i2s_cfg->mode) { case AUDIO_HAL_MODE_MASTER: /* MASTER MODE */ ESP_LOGI(TAG, "ES7210 in Master mode"); ret |= es7210_update_reg_bit(ES7210_MODE_CONFIG_REG08, 0x01, 0x01); /* Select clock source for internal mclk */ switch (get_es7210_mclk_src()) { case FROM_PAD_PIN: ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x00); break; case FROM_CLOCK_DOUBLE_PIN: ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x80); break; default: ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x00); break; } break; case AUDIO_HAL_MODE_SLAVE: /* SLAVE MODE */ ESP_LOGI(TAG, "ES7210 in Slave mode"); ret |= es7210_update_reg_bit(ES7210_MODE_CONFIG_REG08, 0x01, 0x00); break; default: ret |= es7210_update_reg_bit(ES7210_MODE_CONFIG_REG08, 0x01, 0x00); } ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0x43); /* Select power off analog, vdda = 3.3V, close vx20ff, VMID select 5KΩ start */ ret |= es7210_write_reg(ES7210_MIC12_BIAS_REG41, 0x70); /* Select 2.87v */ ret |= es7210_write_reg(ES7210_MIC34_BIAS_REG42, 0x70); /* Select 2.87v */ ret |= es7210_write_reg(ES7210_OSR_REG07, 0x20); ret |= es7210_write_reg(ES7210_MAINCLK_REG02, 0xc1); /* Set the frequency division coefficient and use dll except clock doubler, and need to set 0xc1 to clear the state */ ret |= es7210_config_sample(i2s_cfg->samples); ret |= es7210_mic_select(mic_select); ret |= es7210_adc_set_gain(GAIN_30DB); return ESP_OK; } esp_err_t es7210_adc_deinit() { i2c_bus_delete(i2c_handle); return ESP_OK; } esp_err_t es7210_config_fmt(audio_hal_iface_format_t fmt) { esp_err_t ret = ESP_OK; uint8_t adc_iface = 0; adc_iface = es7210_read_reg(ES7210_SDP_INTERFACE1_REG11); adc_iface &= 0xfc; switch (fmt) { case AUDIO_HAL_I2S_NORMAL: ESP_LOGD(TAG, "ES7210 in I2S Format"); adc_iface |= 0x00; break; case AUDIO_HAL_I2S_LEFT: case AUDIO_HAL_I2S_RIGHT: ESP_LOGD(TAG, "ES7210 in LJ Format"); adc_iface |= 0x01; break; case AUDIO_HAL_I2S_DSP: if (I2S_DSP_MODE) { ESP_LOGD(TAG, "ES7210 in DSP-A Format"); adc_iface |= 0x13; } else { ESP_LOGD(TAG, "ES7210 in DSP-B Format"); adc_iface |= 0x03; } break; default: adc_iface &= 0xfc; break; } ret |= es7210_write_reg(ES7210_SDP_INTERFACE1_REG11, adc_iface); return ret; } esp_err_t es7210_set_bits(audio_hal_iface_bits_t bits) { esp_err_t ret = ESP_OK; uint8_t adc_iface = 0; adc_iface = es7210_read_reg(ES7210_SDP_INTERFACE1_REG11); adc_iface &= 0x1f; switch (bits) { case AUDIO_HAL_BIT_LENGTH_16BITS: adc_iface |= 0x60; break; case AUDIO_HAL_BIT_LENGTH_24BITS: adc_iface |= 0x00; break; case AUDIO_HAL_BIT_LENGTH_32BITS: adc_iface |= 0x80; break; default: adc_iface |= 0x60; break; } ret |= es7210_write_reg(ES7210_SDP_INTERFACE1_REG11, adc_iface); return ret; } esp_err_t es7210_adc_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface) { esp_err_t ret = ESP_OK; ret |= es7210_set_bits(iface->bits); ret |= es7210_config_fmt(iface->fmt); ret |= es7210_config_sample(iface->samples); return ret; } esp_err_t es7210_start(uint8_t clock_reg_value) { esp_err_t ret = ESP_OK; ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, clock_reg_value); ret |= es7210_write_reg(ES7210_POWER_DOWN_REG06, 0x00); ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0x43); ret |= es7210_write_reg(ES7210_MIC1_POWER_REG47, 0x00); ret |= es7210_write_reg(ES7210_MIC2_POWER_REG48, 0x00); ret |= es7210_write_reg(ES7210_MIC3_POWER_REG49, 0x00); ret |= es7210_write_reg(ES7210_MIC4_POWER_REG4A, 0x00); ret |= es7210_mic_select(mic_select); return ret; } esp_err_t es7210_stop(void) { esp_err_t ret = ESP_OK; ret |= es7210_write_reg(ES7210_MIC1_POWER_REG47, 0xff); ret |= es7210_write_reg(ES7210_MIC2_POWER_REG48, 0xff); ret |= es7210_write_reg(ES7210_MIC3_POWER_REG49, 0xff); ret |= es7210_write_reg(ES7210_MIC4_POWER_REG4A, 0xff); ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B,0xff); ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0xff); ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0xc0); ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, 0x7f); ret |= es7210_write_reg(ES7210_POWER_DOWN_REG06, 0x07); return ret; } esp_err_t es7210_adc_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state) { static uint8_t regv; esp_err_t ret = ESP_OK; ESP_LOGW(TAG, "ES7210 only supports ADC mode"); ret = es7210_read_reg(ES7210_CLOCK_OFF_REG01); if ((ret != 0x7f) && (ret != 0xff)) { regv = es7210_read_reg(ES7210_CLOCK_OFF_REG01); } if (ctrl_state == AUDIO_HAL_CTRL_START) { ESP_LOGI(TAG, "The ES7210_CLOCK_OFF_REG01 value before stop is %x",regv); ret |= es7210_start(regv); } else { ESP_LOGW(TAG, "The codec is about to stop"); regv = es7210_read_reg(ES7210_CLOCK_OFF_REG01); ret |= es7210_stop(); } return ret; } esp_err_t es7210_adc_set_gain(es7210_gain_value_t gain) { esp_err_t ret = ESP_OK; uint32_t max_gain_vaule = 14; if (gain < 0) { gain = 0; } else if (gain > max_gain_vaule) { gain = max_gain_vaule; } ESP_LOGD(TAG, "SET: gain:%d", gain); if (mic_select & ES7210_INPUT_MIC1) { ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43, 0x0f, gain); } if (mic_select & ES7210_INPUT_MIC2) { ret |= es7210_update_reg_bit(ES7210_MIC2_GAIN_REG44, 0x0f, gain); } if (mic_select & ES7210_INPUT_MIC3) { ret |= es7210_update_reg_bit(ES7210_MIC3_GAIN_REG45, 0x0f, gain); } if (mic_select & ES7210_INPUT_MIC4) { ret |= es7210_update_reg_bit(ES7210_MIC4_GAIN_REG46, 0x0f, gain); } return ret; } esp_err_t es7210_adc_get_gain(void) { int regv = 0; uint8_t gain_value; if (mic_select & ES7210_INPUT_MIC1) { regv = es7210_read_reg(ES7210_MIC1_GAIN_REG43); } else if (mic_select & ES7210_INPUT_MIC2) { regv = es7210_read_reg(ES7210_MIC2_GAIN_REG44); } else if (mic_select & ES7210_INPUT_MIC3) { regv = es7210_read_reg(ES7210_MIC3_GAIN_REG45); } else if (mic_select & ES7210_INPUT_MIC4) { regv = es7210_read_reg(ES7210_MIC4_GAIN_REG46); } else { ESP_LOGE(TAG, "No MIC selected"); return ESP_FAIL; } if (regv == ESP_FAIL) { return regv; } gain_value = (regv & 0x0f); /* Retain the last four bits for gain */ ESP_LOGI(TAG, "GET: gain_value:%d", gain_value); return gain_value; } esp_err_t es7210_adc_set_volume(int volume) { esp_err_t ret = ESP_OK; ESP_LOGD(TAG, "ADC can adjust gain"); return ret; } esp_err_t es7210_set_mute(bool enable) { ESP_LOGD(TAG, "ES7210 SetMute :%d", enable); return ESP_OK; } void es7210_read_all(void) { for (int i = 0; i <= 0x4E; i++) { uint8_t reg = es7210_read_reg(i); ets_printf("REG:%02x, %02x\n", reg, i); } }
508034.c
#include "../vidhrdw/terracre.c" /****************************************************************** Terra Cresta (preliminary) Nichibutsu 1985 68000 + Z80 driver by Carlos A. Lozano TODO: I'm playing samples with a DAC, but they could be ADPCM Carlos A. Lozano ([email protected]) MEMORY MAP 0x000000 - 0x01ffff ROM 0x020000 - 0x02006f VRAM (Sprites)??? 0x020070 - 0x021fff RAM 0x022000 - 0x022fff VRAM (Background)??? 0x024000 - 0x24000f Input Ports 0x026000 - 0x26000f Output Ports 0x028000 - 0x287fff VRAM (Tiles) VRAM(Background) 0x22000 - 32 bytes (16 tiles) 0x22040 - 32 bytes (16 tiles) 0x22080 - 32 bytes (16 tiles) 0x220c0 - 32 bytes (16 tiles) 0x22100 - 32 bytes (16 tiles) ... 0x22fc0 - 32 bytes (16 tiles) VRAM(Tiles) 0x28000-0x287ff (1024 tiles 8x8 tiles, 2 bytes every tile) VRAM(Sprites) 0x20000-0x201ff ******************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #include "cpu/m68000/m68000.h" unsigned char* terrac_ram; void terrac_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom); void terracre_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh); //void terracre_vh_screenrefresh(struct osd_bitmap *bitmap); int terrac_vh_start(void); void terrac_vh_stop(void); WRITE_HANDLER( terrac_videoram2_w ); READ_HANDLER( terrac_videoram2_r ); extern unsigned char *terrac_videoram; extern size_t terrac_videoram_size; extern unsigned char terrac_scrolly[]; WRITE_HANDLER( terracre_misc_w ) { switch (offset) { // case 0: /* ??? */ // break; case 2: /* Scroll Y */ COMBINE_WORD_MEM(terrac_scrolly,data); return; break; // case 4: /* ??? */ // break; // case 0xa: /* ??? */ // break; case 0xc: /* sound command */ soundlatch_w(offset,((data & 0x7f) << 1) | 1); return; break; // case 0xe: /* ??? */ // break; } //logerror("OUTPUT [%x] <- %08x\n", offset,data ); } static READ_HANDLER( terracre_ports_r ) { switch (offset) { case 0: /* Player controls */ return readinputport(0); case 2: /* Dipswitch 0xf000*/ return readinputport(1); case 4: /* Start buttons & Dipswitch */ return readinputport(2) << 8; case 6: /* Dipswitch???? */ return (readinputport(4) << 8) | readinputport(3); } return 0xffff; } static READ_HANDLER( soundlatch_clear_r ) { soundlatch_clear_w(0,0); return 0; } static struct MemoryReadAddress readmem[] = { { 0x000000, 0x01ffff, MRA_ROM }, { 0x020000, 0x0201ff, MRA_BANK1 }, { 0x020200, 0x021fff, MRA_BANK2 }, { 0x022000, 0x022fff, terrac_videoram2_r }, { 0x023000, 0x023fff, MRA_BANK3 }, { 0x024000, 0x024007, terracre_ports_r }, { 0x028000, 0x0287ff, MRA_BANK4 }, { -1 } /* end of table */ }; static struct MemoryWriteAddress writemem[] = { { 0x000000, 0x01ffff, MWA_ROM }, { 0x020000, 0x0201ff, MWA_BANK1, &spriteram, &spriteram_size }, { 0x020200, 0x021fff, MWA_BANK2, &terrac_ram }, { 0x022000, 0x022fff, terrac_videoram2_w, &terrac_videoram, &terrac_videoram_size }, { 0x023000, 0x023fff, MWA_BANK3 }, { 0x026000, 0x02600f, terracre_misc_w }, { 0x028000, 0x0287ff, MWA_BANK4, &videoram, &videoram_size }, { -1 } /* end of table */ }; static struct MemoryReadAddress sound_readmem[] = { { 0x0000, 0xbfff, MRA_ROM }, { 0xc000, 0xcfff, MRA_RAM }, { -1 } /* end of table */ }; static struct MemoryWriteAddress sound_writemem[] = { { 0x0000, 0xbfff, MWA_ROM }, { 0xc000, 0xcfff, MWA_RAM }, { -1 } /* end of table */ }; static struct IOReadPort sound_readport[] = { { 0x04, 0x04, soundlatch_clear_r }, { 0x06, 0x06, soundlatch_r }, { -1 } /* end of table */ }; static struct IOWritePort sound_writeport_3526[] = { { 0x00, 0x00, YM3526_control_port_0_w }, { 0x01, 0x01, YM3526_write_port_0_w }, { 0x02, 0x02, DAC_0_signed_data_w }, { 0x03, 0x03, DAC_1_signed_data_w }, { -1 } /* end of table */ }; static struct IOWritePort sound_writeport_2203[] = { { 0x00, 0x00, YM2203_control_port_0_w }, { 0x01, 0x01, YM2203_write_port_0_w }, { 0x02, 0x02, DAC_0_signed_data_w }, { 0x03, 0x03, DAC_1_signed_data_w }, { -1 } /* end of table */ }; INPUT_PORTS_START( terracre ) PORT_START /* Player 1 controls */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START /* Player 2 controls */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START /* Coin, Start, Test, Dipswitch */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_SERVICE( 0x20, IP_ACTIVE_LOW ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START /* Dipswitch */ PORT_DIPNAME( 0x03, 0x03, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x03, "3" ) PORT_DIPSETTING( 0x02, "4" ) PORT_DIPSETTING( 0x01, "5" ) PORT_DIPSETTING( 0x00, "6" ) PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "20000 60000" ) PORT_DIPSETTING( 0x08, "30000 70000" ) PORT_DIPSETTING( 0x04, "40000 80000" ) PORT_DIPSETTING( 0x00, "50000 90000" ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x10, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x20, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START /* Dipswitch */ PORT_DIPNAME( 0x03, 0x03, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x01, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x03, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x00, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x10, "Easy" ) PORT_DIPSETTING( 0x00, "Hard" ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_BITX( 0x40, 0x40, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END static struct GfxLayout charlayout = { 8,8, /* 8*8 characters */ 256, /* 256 characters */ 4, /* 4 bits per pixel */ { 0, 1, 2, 3 }, { 4, 0, 12, 8, 20, 16, 28, 24}, { 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32 }, 32*8 /* every char takes 32 consecutive bytes */ }; static struct GfxLayout backlayout = { 16,16, /* 16*16 chars */ 512, /* 512 characters */ 4, /* 4 bits per pixel */ { 0, 1, 2, 3 }, /* plane offset */ { 4, 0, 12, 8, 20, 16, 28, 24, 32+4, 32+0, 32+12, 32+8, 32+20, 32+16, 32+28, 32+24, }, { 0*64, 1*64, 2*64, 3*64, 4*64, 5*64, 6*64, 7*64, 8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64 }, 128*8 /* every char takes 128 consecutive bytes */ }; static struct GfxLayout spritelayout = { 16,16, /* 16*16 characters */ 512, /* 512 sprites */ 4, /* 4 bits per pixel */ { 0, 1, 2, 3 }, { 4, 0, 4+0x8000*8, 0+0x8000*8, 12, 8, 12+0x8000*8, 8+0x8000*8, 20, 16, 20+0x8000*8, 16+0x8000*8, 28, 24, 28+0x8000*8, 24+0x8000*8 }, { 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32 }, 64*8 /* every char takes 64 consecutive bytes */ }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { REGION_GFX1, 0, &charlayout, 0, 1 }, { REGION_GFX2, 0, &backlayout, 1*16, 16 }, { REGION_GFX3, 0, &spritelayout, 1*16+16*16, 256 }, { -1 } /* end of array */ }; static struct YM3526interface ym3526_interface = { 1, /* 1 chip (no more supported) */ 4000000, /* 4 MHz ? (hand tuned) */ { 255 } /* (not supported) */ }; static struct YM2203interface ym2203_interface = { 1, /* 1 chip */ 3000000, /* 3 MHz ???? */ { YM2203_VOL(40,20), YM2203_VOL(40,20) }, { 0 }, { 0 }, { 0 }, { 0 } }; static struct DACinterface dac_interface = { 2, /* 2 channels */ { 50, 50 } }; static struct MachineDriver machine_driver_ym3526 = { { { CPU_M68000, 8000000, /* 8 Mhz?? */ readmem,writemem,0,0, m68_level1_irq,1 }, { CPU_Z80 | CPU_AUDIO_CPU, 4000000, /* 4 MHz???? */ sound_readmem,sound_writemem,sound_readport,sound_writeport_3526, interrupt,128 /* ??? */ }, }, 60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */ 0, /* video hardware */ 32*8, 32*8, { 0*8, 32*8-1, 2*8, 30*8-1 }, gfxdecodeinfo, 256, 1*16+16*16+16*256, terrac_vh_convert_color_prom, VIDEO_TYPE_RASTER, 0, terrac_vh_start, terrac_vh_stop, terracre_vh_screenrefresh, /* sound hardware */ 0,0,0,0, { { SOUND_YM3526, &ym3526_interface }, { SOUND_DAC, &dac_interface } } }; static struct MachineDriver machine_driver_ym2203 = { { { CPU_M68000, 8000000, /* 8 Mhz?? */ readmem,writemem,0,0, m68_level1_irq,1 }, { CPU_Z80 | CPU_AUDIO_CPU, 4000000, /* 4 MHz???? */ sound_readmem,sound_writemem,sound_readport,sound_writeport_2203, interrupt,128 /* ??? */ }, }, 60, DEFAULT_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */ 0, /* video hardware */ 32*8, 32*8, { 0*8, 32*8-1, 2*8, 30*8-1 }, gfxdecodeinfo, 256, 1*16+16*16+16*256, terrac_vh_convert_color_prom, VIDEO_TYPE_RASTER, 0, terrac_vh_start, terrac_vh_stop, terracre_vh_screenrefresh, /* sound hardware */ 0,0,0,0, { { SOUND_YM2203, &ym2203_interface }, { SOUND_DAC, &dac_interface } } }; ROM_START( terracre ) ROM_REGION( 0x20000, REGION_CPU1 ) /* 128K for 68000 code */ ROM_LOAD_ODD ( "1a_4b.rom", 0x00000, 0x4000, 0x76f17479 ) ROM_LOAD_EVEN( "1a_4d.rom", 0x00000, 0x4000, 0x8119f06e ) ROM_LOAD_ODD ( "1a_6b.rom", 0x08000, 0x4000, 0xba4b5822 ) ROM_LOAD_EVEN( "1a_6d.rom", 0x08000, 0x4000, 0xca4852f6 ) ROM_LOAD_ODD ( "1a_7b.rom", 0x10000, 0x4000, 0xd0771bba ) ROM_LOAD_EVEN( "1a_7d.rom", 0x10000, 0x4000, 0x029d59d9 ) ROM_LOAD_ODD ( "1a_9b.rom", 0x18000, 0x4000, 0x69227b56 ) ROM_LOAD_EVEN( "1a_9d.rom", 0x18000, 0x4000, 0x5a672942 ) ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for sound cpu */ ROM_LOAD( "2a_15b.rom", 0x0000, 0x4000, 0x604c3b11 ) ROM_LOAD( "2a_17b.rom", 0x4000, 0x4000, 0xaffc898d ) ROM_LOAD( "2a_18b.rom", 0x8000, 0x4000, 0x302dc0ab ) ROM_REGION( 0x02000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "2a_16b.rom", 0x00000, 0x2000, 0x591a3804 ) /* tiles */ ROM_REGION( 0x10000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "1a_15f.rom", 0x00000, 0x8000, 0x984a597f ) /* Background */ ROM_LOAD( "1a_17f.rom", 0x08000, 0x8000, 0x30e297ff ) ROM_REGION( 0x10000, REGION_GFX3 | REGIONFLAG_DISPOSE ) ROM_LOAD( "2a_6e.rom", 0x00000, 0x4000, 0xbcf7740b ) /* Sprites */ ROM_LOAD( "2a_7e.rom", 0x04000, 0x4000, 0xa70b565c ) ROM_LOAD( "2a_6g.rom", 0x08000, 0x4000, 0x4a9ec3e6 ) ROM_LOAD( "2a_7g.rom", 0x0c000, 0x4000, 0x450749fc ) ROM_REGION( 0x0500, REGION_PROMS ) ROM_LOAD( "tc1a_10f.bin", 0x0000, 0x0100, 0xce07c544 ) /* red component */ ROM_LOAD( "tc1a_11f.bin", 0x0100, 0x0100, 0x566d323a ) /* green component */ ROM_LOAD( "tc1a_12f.bin", 0x0200, 0x0100, 0x7ea63946 ) /* blue component */ ROM_LOAD( "tc2a_2g.bin", 0x0300, 0x0100, 0x08609bad ) /* sprite lookup table */ ROM_LOAD( "tc2a_4e.bin", 0x0400, 0x0100, 0x2c43991f ) /* sprite palette bank */ ROM_END /**********************************************************/ /* Notes: All the roms are the same except the SOUND ROMs */ /**********************************************************/ ROM_START( terracrb ) ROM_REGION( 0x20000, REGION_CPU1 ) /* 128K for 68000 code */ ROM_LOAD_ODD ( "1a_4b.rom", 0x00000, 0x4000, 0x76f17479 ) ROM_LOAD_EVEN( "1a_4d.rom", 0x00000, 0x4000, 0x8119f06e ) ROM_LOAD_ODD ( "1a_6b.rom", 0x08000, 0x4000, 0xba4b5822 ) ROM_LOAD_EVEN( "1a_6d.rom", 0x08000, 0x4000, 0xca4852f6 ) ROM_LOAD_ODD ( "1a_7b.rom", 0x10000, 0x4000, 0xd0771bba ) ROM_LOAD_EVEN( "1a_7d.rom", 0x10000, 0x4000, 0x029d59d9 ) ROM_LOAD_ODD ( "1a_9b.rom", 0x18000, 0x4000, 0x69227b56 ) ROM_LOAD_EVEN( "1a_9d.rom", 0x18000, 0x4000, 0x5a672942 ) ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for sound cpu */ ROM_LOAD( "2a_15b.rom", 0x0000, 0x4000, 0x604c3b11 ) ROM_LOAD( "dg.12", 0x4000, 0x4000, 0x9e9b3808 ) ROM_LOAD( "2a_18b.rom", 0x8000, 0x4000, 0x302dc0ab ) ROM_REGION( 0x02000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "2a_16b.rom", 0x00000, 0x2000, 0x591a3804 ) /* tiles */ ROM_REGION( 0x10000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "1a_15f.rom", 0x00000, 0x8000, 0x984a597f ) /* Background */ ROM_LOAD( "1a_17f.rom", 0x08000, 0x8000, 0x30e297ff ) ROM_REGION( 0x10000, REGION_GFX3 | REGIONFLAG_DISPOSE ) ROM_LOAD( "2a_6e.rom", 0x00000, 0x4000, 0xbcf7740b ) /* Sprites */ ROM_LOAD( "2a_7e.rom", 0x04000, 0x4000, 0xa70b565c ) ROM_LOAD( "2a_6g.rom", 0x08000, 0x4000, 0x4a9ec3e6 ) ROM_LOAD( "2a_7g.rom", 0x0c000, 0x4000, 0x450749fc ) ROM_REGION( 0x0500, REGION_PROMS ) ROM_LOAD( "tc1a_10f.bin", 0x0000, 0x0100, 0xce07c544 ) /* red component */ ROM_LOAD( "tc1a_11f.bin", 0x0100, 0x0100, 0x566d323a ) /* green component */ ROM_LOAD( "tc1a_12f.bin", 0x0200, 0x0100, 0x7ea63946 ) /* blue component */ ROM_LOAD( "tc2a_2g.bin", 0x0300, 0x0100, 0x08609bad ) /* sprite lookup table */ ROM_LOAD( "tc2a_4e.bin", 0x0400, 0x0100, 0x2c43991f ) /* sprite palette bank */ ROM_END /**********************************************************/ /* Notes: All the roms are the same except the SOUND ROMs */ /**********************************************************/ ROM_START( terracra ) ROM_REGION( 0x20000, REGION_CPU1 ) /* 128K for 68000 code */ ROM_LOAD_ODD ( "1a_4b.rom", 0x00000, 0x4000, 0x76f17479 ) ROM_LOAD_EVEN( "1a_4d.rom", 0x00000, 0x4000, 0x8119f06e ) ROM_LOAD_ODD ( "1a_6b.rom", 0x08000, 0x4000, 0xba4b5822 ) ROM_LOAD_EVEN( "1a_6d.rom", 0x08000, 0x4000, 0xca4852f6 ) ROM_LOAD_ODD ( "1a_7b.rom", 0x10000, 0x4000, 0xd0771bba ) ROM_LOAD_EVEN( "1a_7d.rom", 0x10000, 0x4000, 0x029d59d9 ) ROM_LOAD_ODD ( "1a_9b.rom", 0x18000, 0x4000, 0x69227b56 ) ROM_LOAD_EVEN( "1a_9d.rom", 0x18000, 0x4000, 0x5a672942 ) ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k to sound cpu */ ROM_LOAD( "tc2a_15b.bin", 0x0000, 0x4000, 0x790ddfa9 ) ROM_LOAD( "tc2a_17b.bin", 0x4000, 0x4000, 0xd4531113 ) ROM_REGION( 0x02000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "2a_16b.rom", 0x00000, 0x2000, 0x591a3804 ) /* tiles */ ROM_REGION( 0x10000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "1a_15f.rom", 0x00000, 0x8000, 0x984a597f ) /* Background */ ROM_LOAD( "1a_17f.rom", 0x08000, 0x8000, 0x30e297ff ) ROM_REGION( 0x10000, REGION_GFX3 | REGIONFLAG_DISPOSE ) ROM_LOAD( "2a_6e.rom", 0x00000, 0x4000, 0xbcf7740b ) /* Sprites */ ROM_LOAD( "2a_7e.rom", 0x04000, 0x4000, 0xa70b565c ) ROM_LOAD( "2a_6g.rom", 0x08000, 0x4000, 0x4a9ec3e6 ) ROM_LOAD( "2a_7g.rom", 0x0c000, 0x4000, 0x450749fc ) ROM_REGION( 0x0500, REGION_PROMS ) ROM_LOAD( "tc1a_10f.bin", 0x0000, 0x0100, 0xce07c544 ) /* red component */ ROM_LOAD( "tc1a_11f.bin", 0x0100, 0x0100, 0x566d323a ) /* green component */ ROM_LOAD( "tc1a_12f.bin", 0x0200, 0x0100, 0x7ea63946 ) /* blue component */ ROM_LOAD( "tc2a_2g.bin", 0x0300, 0x0100, 0x08609bad ) /* sprite lookup table */ ROM_LOAD( "tc2a_4e.bin", 0x0400, 0x0100, 0x2c43991f ) /* sprite palette bank */ ROM_END GAME( 1985, terracre, 0, ym3526, terracre, 0, ROT270, "Nichibutsu", "Terra Cresta (YM3526 set 1)" ) GAME( 1985, terracrb, terracre, ym3526, terracre, 0, ROT270, "Nichibutsu", "Terra Cresta (YM3526 set 2)" ) GAME( 1985, terracra, terracre, ym2203, terracre, 0, ROT270, "Nichibutsu", "Terra Cresta (YM2203)" )
562725.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> int X_RESN = 1000; /* x resolution */ int Y_RESN = 1000; /* y resolution */ int MAX_ITER = 200; // ref: https://stackoverflow.com/questions/6749621/how-to-create-a-high-resolution-timer-in-linux-to-measure-program-performance // call this function to start a nanosecond-resolution timer struct timespec timer_start() { struct timespec start_time; clock_gettime(CLOCK_MONOTONIC, &start_time); return start_time; } // call this function to end a timer, returning nanoseconds elapsed as a long long long timer_end(struct timespec start_time){ struct timespec end_time; clock_gettime(CLOCK_MONOTONIC, &end_time); long long diffInNanos = (end_time.tv_sec - start_time.tv_sec) * (long long)1e9 + (end_time.tv_nsec - start_time.tv_nsec); return diffInNanos; } typedef struct complextype { double real, imag; } Compl; int main(int argc, char *argv[]) { int save = 0; int s = 0; for (int itA = 1; itA < argc; itA++) { char *arg = argv[itA]; if (s == 0) { if (strcmp(arg, "-s") == 0) save = 1; if (strcmp(arg, "-x") == 0) s = 1; if (strcmp(arg, "-y") == 0) s = 2; if (strcmp(arg, "-i") == 0) s = 3; if (strcmp(arg, "-xy") == 0) s = 4; } else { if (s == 1) X_RESN = atoi(arg); if (s == 2) Y_RESN = atoi(arg); if (s == 3) MAX_ITER = atoi(arg); if (s == 4) X_RESN = Y_RESN = atoi(arg); s = 0; } } if (s != 0) { fprintf(stderr, "Missing argument value!"); exit(1); } struct timespec vartime = timer_start(); /* Mandelbrot variables */ int *ks; ks = (int *)malloc((X_RESN*Y_RESN) * sizeof(int)); double *ds; ds = (double *)malloc((X_RESN*Y_RESN) * sizeof(double)); /* Calculate and draw points */ int i, j, k; double d; Compl z, c, t; #pragma acc parallel loop \ copyout(ks[0:X_RESN*Y_RESN], ds[0:X_RESN*Y_RESN]) \ private(k, d, c, z, t) for (int it = 0; it < X_RESN*Y_RESN; it++) { i = it / Y_RESN; j = it % Y_RESN; // mandelbrot set is defined in the region of x = [-2, +2] and y = [-2, +2] double u = ((double)i - (X_RESN / 2.0)) / (X_RESN / 4.0); double v = ((double)j - (Y_RESN / 2.0)) / (Y_RESN / 4.0); z.real = z.imag = 0.0; c.real = v; c.imag = u; k = 0; d = 0.0; double lengthsq; do { t = z; z.imag = 2.0 * t.real * t.imag + c.imag; z.real = t.real * t.real - t.imag * t.imag + c.real; lengthsq = z.real * z.real + z.imag * z.imag; d += pow(pow(z.imag - t.imag, 2.0) + pow(z.real - t.real, 2.0), 0.5); k++; } while (lengthsq < 4.0 && k < MAX_ITER); ks[it] = k; ds[it] = d; } free(ks); free(ds); long long time_elapsed_nanos = timer_end(vartime); double elapsed = time_elapsed_nanos*0.000000001; printf("%lf\n", elapsed); /* Program Finished */ return 0; }
15755.c
#include "critical.h" #if defined(FREERTOS_LIB) #include "FreeRTOS.h" void critical_enter( void ) { portENTER_CRITICAL(); } void critical_exit( void ) { portEXIT_CRITICAL(); } #elif defined(STM32F1)||defined(STM32F3)||defined(STM32F4) #include <libopencm3/cm3/cortex.h> static unsigned int ulNesting = 0; void critical_enter( void ) { if(ulNesting == 0) { cm_disable_interrupts(); } ulNesting++; } void critical_exit( void ) { ulNesting--; if(ulNesting == 0) { cm_enable_interrupts(); } } #endif
32013.c
/* * Directory id handling * * Copyright 2002 Alexandre Julliard for CodeWeavers * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include <stdarg.h> #include "windef.h" #include "winbase.h" #include "winreg.h" #include "winternl.h" #include "winerror.h" #include "wingdi.h" #include "winuser.h" #include "winnls.h" #include "setupapi.h" #include "shlobj.h" #include "setupapi_private.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(setupapi); #define MAX_SYSTEM_DIRID DIRID_PRINTPROCESSOR #define MIN_CSIDL_DIRID 0x4000 #define MAX_CSIDL_DIRID 0x403f struct user_dirid { int id; WCHAR *str; }; #ifdef __i386__ static const WCHAR printer_env[] = L"w32x86"; #elif defined __x86_64__ static const WCHAR printer_env[] = L"x64"; #elif defined __arm__ static const WCHAR printer_env[] = L"arm"; #elif defined __aarch64__ static const WCHAR printer_env[] = L"arm64"; #else #error not defined for this cpu #endif static int nb_user_dirids; /* number of user dirids in use */ static int alloc_user_dirids; /* number of allocated user dirids */ static struct user_dirid *user_dirids; static const WCHAR *printer_dirids[5]; /* 66000..66004 */ static const WCHAR *system_dirids[MAX_SYSTEM_DIRID+1]; static const WCHAR *csidl_dirids[MAX_CSIDL_DIRID-MIN_CSIDL_DIRID+1]; /* retrieve the string for unknown dirids */ static const WCHAR *get_unknown_dirid(void) { static WCHAR *unknown_dirid; if (!unknown_dirid) { UINT len = GetSystemDirectoryW( NULL, 0 ) + lstrlenW(L"\\unknown"); if (!(unknown_dirid = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return NULL; GetSystemDirectoryW( unknown_dirid, len ); lstrcatW( unknown_dirid, L"\\unknown" ); } return unknown_dirid; } static const WCHAR *get_csidl_dir(DWORD csidl); /* create the string for a system dirid */ static const WCHAR *create_system_dirid( int dirid ) { WCHAR buffer[MAX_PATH+32], *str; int len; switch(dirid) { case DIRID_NULL: return L""; case DIRID_WINDOWS: GetWindowsDirectoryW( buffer, MAX_PATH ); break; case DIRID_SYSTEM: GetSystemDirectoryW( buffer, MAX_PATH ); break; case DIRID_DRIVERS: GetSystemDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\drivers" ); break; case DIRID_INF: GetWindowsDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\inf" ); break; case DIRID_HELP: GetWindowsDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\help" ); break; case DIRID_FONTS: GetWindowsDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\fonts" ); break; case DIRID_VIEWERS: GetSystemDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\viewers" ); break; case DIRID_COLOR: GetSystemDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\spool\\drivers\\color" ); break; case DIRID_APPS: return L"C:\\"; /* FIXME */ case DIRID_SHARED: GetWindowsDirectoryW( buffer, MAX_PATH ); break; case DIRID_BOOT: return L"C:\\"; /* FIXME */ case DIRID_SYSTEM16: GetWindowsDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\system" ); break; case DIRID_SPOOL: GetSystemDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\spool" ); break; case DIRID_SPOOLDRIVERS: GetSystemDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\spool\\drivers" ); break; case DIRID_USERPROFILE: if (GetEnvironmentVariableW( L"USERPROFILE", buffer, MAX_PATH )) break; return get_csidl_dir(CSIDL_PROFILE); case DIRID_LOADER: return L"C:\\"; /* FIXME */ case DIRID_PRINTPROCESSOR: GetSystemDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\spool\\prtprocs\\" ); lstrcatW( buffer, printer_env ); break; default: FIXME( "unknown dirid %d\n", dirid ); return get_unknown_dirid(); } len = (lstrlenW(buffer) + 1) * sizeof(WCHAR); if ((str = HeapAlloc( GetProcessHeap(), 0, len ))) memcpy( str, buffer, len ); return str; } static const WCHAR *create_printer_dirid( DWORD dirid ) { WCHAR buffer[MAX_PATH+32], *str; int len; switch (dirid) { case 66000: /* printer driver */ GetSystemDirectoryW( buffer, MAX_PATH ); lstrcatW( buffer, L"\\spool\\drivers\\" ); lstrcatW( buffer, printer_env ); break; case 66001: /* print processor */ return create_system_dirid( DIRID_PRINTPROCESSOR ); case 66002: /* system directory (FIXME: only for native architecture) */ GetSystemDirectoryW( buffer, MAX_PATH ); break; case 66003: /* color directory */ return create_system_dirid( DIRID_COLOR ); case 66004: /* asp files directory */ default: FIXME( "unsupported dirid %ld\n", dirid ); return get_unknown_dirid(); } len = (lstrlenW(buffer) + 1) * sizeof(WCHAR); if ((str = HeapAlloc( GetProcessHeap(), 0, len ))) memcpy( str, buffer, len ); return str; } static const WCHAR *get_csidl_dir( DWORD csidl ) { WCHAR buffer[MAX_PATH], *str; int len; if (!SHGetSpecialFolderPathW( NULL, buffer, csidl, TRUE )) { FIXME( "CSIDL %lx not found\n", csidl ); return get_unknown_dirid(); } len = (lstrlenW(buffer) + 1) * sizeof(WCHAR); if ((str = HeapAlloc( GetProcessHeap(), 0, len ))) memcpy( str, buffer, len ); return str; } /* retrieve the string corresponding to a dirid, or NULL if none */ const WCHAR *DIRID_get_string( int dirid ) { int i; if (dirid == DIRID_ABSOLUTE || dirid == DIRID_ABSOLUTE_16BIT) dirid = DIRID_NULL; if (dirid >= 66000 && dirid <= 66004) { if (!printer_dirids[dirid - 66000]) printer_dirids[dirid - 66000] = create_printer_dirid( dirid ); return printer_dirids[dirid - 66000]; } else if (dirid >= DIRID_USER) { for (i = 0; i < nb_user_dirids; i++) if (user_dirids[i].id == dirid) return user_dirids[i].str; WARN("user id %d not found\n", dirid ); return NULL; } else if (dirid >= MIN_CSIDL_DIRID) { if (dirid > MAX_CSIDL_DIRID) return get_unknown_dirid(); dirid -= MIN_CSIDL_DIRID; if (!csidl_dirids[dirid]) csidl_dirids[dirid] = get_csidl_dir( dirid ); return csidl_dirids[dirid]; } else { if (dirid > MAX_SYSTEM_DIRID) return get_unknown_dirid(); if (!system_dirids[dirid]) system_dirids[dirid] = create_system_dirid( dirid ); return system_dirids[dirid]; } } /* store a user dirid string */ static BOOL store_user_dirid( HINF hinf, int id, WCHAR *str ) { int i; for (i = 0; i < nb_user_dirids; i++) if (user_dirids[i].id == id) break; if (i < nb_user_dirids) HeapFree( GetProcessHeap(), 0, user_dirids[i].str ); else { if (nb_user_dirids >= alloc_user_dirids) { int new_size = max( 32, alloc_user_dirids * 2 ); struct user_dirid *new; if (user_dirids) new = HeapReAlloc( GetProcessHeap(), 0, user_dirids, new_size * sizeof(*new) ); else new = HeapAlloc( GetProcessHeap(), 0, new_size * sizeof(*new) ); if (!new) return FALSE; user_dirids = new; alloc_user_dirids = new_size; } nb_user_dirids++; } user_dirids[i].id = id; user_dirids[i].str = str; TRACE("id %d -> %s\n", id, debugstr_w(str) ); return TRUE; } /*********************************************************************** * SetupSetDirectoryIdA (SETUPAPI.@) */ BOOL WINAPI SetupSetDirectoryIdA( HINF hinf, DWORD id, PCSTR dir ) { UNICODE_STRING dirW; int i; if (!id) /* clear everything */ { for (i = 0; i < nb_user_dirids; i++) HeapFree( GetProcessHeap(), 0, user_dirids[i].str ); nb_user_dirids = 0; return TRUE; } if (id < DIRID_USER) { SetLastError( ERROR_INVALID_PARAMETER ); return FALSE; } /* duplicate the string */ if (!RtlCreateUnicodeStringFromAsciiz( &dirW, dir )) { SetLastError( ERROR_NOT_ENOUGH_MEMORY ); return FALSE; } return store_user_dirid( hinf, id, dirW.Buffer ); } /*********************************************************************** * SetupSetDirectoryIdW (SETUPAPI.@) */ BOOL WINAPI SetupSetDirectoryIdW( HINF hinf, DWORD id, PCWSTR dir ) { int i, len; WCHAR *str; if (!id) /* clear everything */ { for (i = 0; i < nb_user_dirids; i++) HeapFree( GetProcessHeap(), 0, user_dirids[i].str ); nb_user_dirids = 0; return TRUE; } if (id < DIRID_USER) { SetLastError( ERROR_INVALID_PARAMETER ); return FALSE; } /* duplicate the string */ len = (lstrlenW(dir)+1) * sizeof(WCHAR); if (!(str = HeapAlloc( GetProcessHeap(), 0, len ))) return FALSE; memcpy( str, dir, len ); return store_user_dirid( hinf, id, str ); }
545063.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_loop_15.c Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml Template File: sources-sink-15.tmpl.c */ /* * @description * CWE: 121 Stack Based Buffer Overflow * BadSource: Point data to a buffer that does not have space for a NULL terminator * GoodSource: Point data to a buffer that includes space for a NULL terminator * Sink: loop * BadSink : Copy array to data using a loop * Flow Variant: 15 Control flow: switch(6) * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif /* MAINTENANCE NOTE: The length of this string should equal the 10 */ #define SRC_STRING L"AAAAAAAAAA" #ifndef OMITBAD void CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_loop_15_bad() { wchar_t * data; wchar_t * dataBadBuffer = (wchar_t *)ALLOCA((10)*sizeof(wchar_t)); wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA((10+1)*sizeof(wchar_t)); switch(6) { case 6: /* FLAW: Set a pointer to a buffer that does not leave room for a NULL terminator when performing * string copies in the sinks */ data = dataBadBuffer; data[0] = L'\0'; /* null terminate */ break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } { wchar_t source[10+1] = SRC_STRING; size_t i, sourceLen; sourceLen = wcslen(source); /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ for (i = 0; i < sourceLen + 1; i++) { data[i] = source[i]; } printWLine(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */ static void goodG2B1() { wchar_t * data; wchar_t * dataBadBuffer = (wchar_t *)ALLOCA((10)*sizeof(wchar_t)); wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA((10+1)*sizeof(wchar_t)); switch(5) { case 6: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; default: /* FIX: Set a pointer to a buffer that leaves room for a NULL terminator when performing * string copies in the sinks */ data = dataGoodBuffer; data[0] = L'\0'; /* null terminate */ break; } { wchar_t source[10+1] = SRC_STRING; size_t i, sourceLen; sourceLen = wcslen(source); /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ for (i = 0; i < sourceLen + 1; i++) { data[i] = source[i]; } printWLine(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */ static void goodG2B2() { wchar_t * data; wchar_t * dataBadBuffer = (wchar_t *)ALLOCA((10)*sizeof(wchar_t)); wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA((10+1)*sizeof(wchar_t)); switch(6) { case 6: /* FIX: Set a pointer to a buffer that leaves room for a NULL terminator when performing * string copies in the sinks */ data = dataGoodBuffer; data[0] = L'\0'; /* null terminate */ break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; } { wchar_t source[10+1] = SRC_STRING; size_t i, sourceLen; sourceLen = wcslen(source); /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ for (i = 0; i < sourceLen + 1; i++) { data[i] = source[i]; } printWLine(data); } } void CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_loop_15_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_loop_15_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE121_Stack_Based_Buffer_Overflow__CWE193_wchar_t_alloca_loop_15_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
705231.c
/** * FreeRDP: A Remote Desktop Protocol Implementation * Print Virtual Channel * * Copyright 2010-2011 Vic Lee * Copyright 2015 Thincast Technologies GmbH * Copyright 2015 DI (FH) Martin Haimberger <[email protected]> * Copyright 2016 Armin Novak <[email protected]> * Copyright 2016 David PHAM-VAN <[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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <winpr/crt.h> #include <winpr/string.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/stream.h> #include <winpr/interlocked.h> #include <freerdp/channels/rdpdr.h> #include "../printer.h" #ifdef WITH_CUPS #include "printer_cups.h" #endif #include "printer_main.h" #if defined(_WIN32) && !defined(_UWP) #include "printer_win.h" #endif #include <freerdp/channels/log.h> #define TAG CHANNELS_TAG("printer.client") typedef struct _PRINTER_DEVICE PRINTER_DEVICE; struct _PRINTER_DEVICE { DEVICE device; rdpPrinter* printer; WINPR_PSLIST_HEADER pIrpList; HANDLE event; HANDLE stopEvent; HANDLE thread; rdpContext* rdpcontext; }; /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp_create(PRINTER_DEVICE* printer_dev, IRP* irp) { rdpPrintJob* printjob = NULL; if (printer_dev->printer) printjob = printer_dev->printer->CreatePrintJob(printer_dev->printer, irp->devman->id_sequence++); if (printjob) { Stream_Write_UINT32(irp->output, printjob->id); /* FileId */ } else { Stream_Write_UINT32(irp->output, 0); /* FileId */ irp->IoStatus = STATUS_PRINT_QUEUE_FULL; } return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp_close(PRINTER_DEVICE* printer_dev, IRP* irp) { rdpPrintJob* printjob = NULL; if (printer_dev->printer) printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId); if (!printjob) { irp->IoStatus = STATUS_UNSUCCESSFUL; } else { printjob->Close(printjob); } Stream_Zero(irp->output, 4); /* Padding(4) */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp_write(PRINTER_DEVICE* printer_dev, IRP* irp) { UINT32 Length; UINT64 Offset; rdpPrintJob* printjob = NULL; UINT error = CHANNEL_RC_OK; Stream_Read_UINT32(irp->input, Length); Stream_Read_UINT64(irp->input, Offset); Stream_Seek(irp->input, 20); /* Padding */ if (printer_dev->printer) printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId); if (!printjob) { irp->IoStatus = STATUS_UNSUCCESSFUL; Length = 0; } else { error = printjob->Write(printjob, Stream_Pointer(irp->input), Length); } if (error) { WLog_ERR(TAG, "printjob->Write failed with error %"PRIu32"!", error); return error; } Stream_Write_UINT32(irp->output, Length); Stream_Write_UINT8(irp->output, 0); /* Padding */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp_device_control(PRINTER_DEVICE* printer_dev, IRP* irp) { Stream_Write_UINT32(irp->output, 0); /* OutputBufferLength */ return irp->Complete(irp); } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_process_irp(PRINTER_DEVICE* printer_dev, IRP* irp) { UINT error; switch (irp->MajorFunction) { case IRP_MJ_CREATE: if ((error = printer_process_irp_create(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp_create failed with error %"PRIu32"!", error); return error; } break; case IRP_MJ_CLOSE: if ((error = printer_process_irp_close(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp_close failed with error %"PRIu32"!", error); return error; } break; case IRP_MJ_WRITE: if ((error = printer_process_irp_write(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp_write failed with error %"PRIu32"!", error); return error; } break; case IRP_MJ_DEVICE_CONTROL: if ((error = printer_process_irp_device_control(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp_device_control failed with error %"PRIu32"!", error); return error; } break; default: irp->IoStatus = STATUS_NOT_SUPPORTED; return irp->Complete(irp); break; } return CHANNEL_RC_OK; } static DWORD WINAPI printer_thread_func(LPVOID arg) { IRP* irp; PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*) arg; HANDLE obj[] = {printer_dev->event, printer_dev->stopEvent}; UINT error = CHANNEL_RC_OK; while (1) { DWORD rc = WaitForMultipleObjects(2, obj, FALSE, INFINITE); if (rc == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForMultipleObjects failed with error %"PRIu32"!", error); break; } if (rc == WAIT_OBJECT_0 + 1) break; else if (rc != WAIT_OBJECT_0) continue; ResetEvent(printer_dev->event); irp = (IRP*) InterlockedPopEntrySList(printer_dev->pIrpList); if (irp == NULL) { WLog_ERR(TAG, "InterlockedPopEntrySList failed!"); error = ERROR_INTERNAL_ERROR; break; } if ((error = printer_process_irp(printer_dev, irp))) { WLog_ERR(TAG, "printer_process_irp failed with error %"PRIu32"!", error); break; } } if (error && printer_dev->rdpcontext) setChannelError(printer_dev->rdpcontext, error, "printer_thread_func reported an error"); ExitThread(error); return error; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_irp_request(DEVICE* device, IRP* irp) { PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*) device; InterlockedPushEntrySList(printer_dev->pIrpList, &(irp->ItemEntry)); SetEvent(printer_dev->event); return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT printer_free(DEVICE* device) { IRP* irp; PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*) device; UINT error; SetEvent(printer_dev->stopEvent); if (WaitForSingleObject(printer_dev->thread, INFINITE) == WAIT_FAILED) { error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %"PRIu32"", error); return error; } while ((irp = (IRP*) InterlockedPopEntrySList(printer_dev->pIrpList)) != NULL) irp->Discard(irp); CloseHandle(printer_dev->thread); CloseHandle(printer_dev->stopEvent); CloseHandle(printer_dev->event); _aligned_free(printer_dev->pIrpList); if (printer_dev->printer) printer_dev->printer->Free(printer_dev->printer); free(printer_dev->device.name); Stream_Free(printer_dev->device.data, TRUE); free(printer_dev); return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ UINT printer_register(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, rdpPrinter* printer) { char* port; UINT32 Flags; int DriverNameLen; WCHAR* DriverName = NULL; int PrintNameLen; WCHAR* PrintName = NULL; UINT32 CachedFieldsLen; BYTE* CachedPrinterConfigData; PRINTER_DEVICE* printer_dev; UINT error; port = malloc(10); if (!port) { WLog_ERR(TAG, "malloc failed!"); return CHANNEL_RC_NO_MEMORY; } sprintf_s(port, 10, "PRN%d", printer->id); printer_dev = (PRINTER_DEVICE*) calloc(1, sizeof(PRINTER_DEVICE)); if (!printer_dev) { WLog_ERR(TAG, "calloc failed!"); free(port); return CHANNEL_RC_NO_MEMORY; } printer_dev->device.type = RDPDR_DTYP_PRINT; printer_dev->device.name = port; printer_dev->device.IRPRequest = printer_irp_request; printer_dev->device.Free = printer_free; printer_dev->rdpcontext = pEntryPoints->rdpcontext; printer_dev->printer = printer; CachedFieldsLen = 0; CachedPrinterConfigData = NULL; Flags = 0; if (printer->is_default) Flags |= RDPDR_PRINTER_ANNOUNCE_FLAG_DEFAULTPRINTER; DriverNameLen = ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, &DriverName, 0) * 2; PrintNameLen = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &PrintName, 0) * 2; printer_dev->device.data = Stream_New(NULL, 28 + DriverNameLen + PrintNameLen + CachedFieldsLen); if (!printer_dev->device.data) { WLog_ERR(TAG, "calloc failed!"); error = CHANNEL_RC_NO_MEMORY; free(DriverName); free(PrintName); goto error_out; } Stream_Write_UINT32(printer_dev->device.data, Flags); Stream_Write_UINT32(printer_dev->device.data, 0); /* CodePage, reserved */ Stream_Write_UINT32(printer_dev->device.data, 0); /* PnPNameLen */ Stream_Write_UINT32(printer_dev->device.data, DriverNameLen + 2); Stream_Write_UINT32(printer_dev->device.data, PrintNameLen + 2); Stream_Write_UINT32(printer_dev->device.data, CachedFieldsLen); Stream_Write(printer_dev->device.data, DriverName, DriverNameLen); Stream_Write_UINT16(printer_dev->device.data, 0); Stream_Write(printer_dev->device.data, PrintName, PrintNameLen); Stream_Write_UINT16(printer_dev->device.data, 0); if (CachedFieldsLen > 0) { Stream_Write(printer_dev->device.data, CachedPrinterConfigData, CachedFieldsLen); } free(DriverName); free(PrintName); printer_dev->pIrpList = (WINPR_PSLIST_HEADER) _aligned_malloc(sizeof( WINPR_SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT); if (!printer_dev->pIrpList) { WLog_ERR(TAG, "_aligned_malloc failed!"); error = CHANNEL_RC_NO_MEMORY; goto error_out; } InitializeSListHead(printer_dev->pIrpList); if (!(printer_dev->event = CreateEvent(NULL, TRUE, FALSE, NULL))) { WLog_ERR(TAG, "CreateEvent failed!"); error = ERROR_INTERNAL_ERROR; goto error_out; } if (!(printer_dev->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) { WLog_ERR(TAG, "CreateEvent failed!"); error = ERROR_INTERNAL_ERROR; goto error_out; } if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*) printer_dev))) { WLog_ERR(TAG, "RegisterDevice failed with error %"PRIu32"!", error); goto error_out; } if (!(printer_dev->thread = CreateThread(NULL, 0, printer_thread_func, (void*) printer_dev, 0, NULL))) { WLog_ERR(TAG, "CreateThread failed!"); error = ERROR_INTERNAL_ERROR; goto error_out; } return CHANNEL_RC_OK; error_out: CloseHandle(printer_dev->stopEvent); CloseHandle(printer_dev->event); _aligned_free(printer_dev->pIrpList); Stream_Free(printer_dev->device.data, TRUE); free(printer_dev); free(port); return error; } #ifdef BUILTIN_CHANNELS #define DeviceServiceEntry printer_DeviceServiceEntry #else #define DeviceServiceEntry FREERDP_API DeviceServiceEntry #endif /** * Function description * * @return 0 on success, otherwise a Win32 error code */ UINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints) { int i; char* name; char* driver_name; rdpPrinter* printer; rdpPrinter** printers; RDPDR_PRINTER* device; rdpPrinterDriver* driver = NULL; UINT error; #ifdef WITH_CUPS driver = printer_cups_get_driver(); #endif #if defined(_WIN32) && !defined(_UWP) driver = printer_win_get_driver(); #endif if (!driver) { WLog_ERR(TAG, "Could not get a printer driver!"); return CHANNEL_RC_INITIALIZATION_ERROR; } device = (RDPDR_PRINTER*) pEntryPoints->device; name = device->Name; driver_name = device->DriverName; if (name && name[0]) { printer = driver->GetPrinter(driver, name, driver_name); if (!printer) { WLog_ERR(TAG, "Could not get printer %s!", name); return CHANNEL_RC_INITIALIZATION_ERROR; } if ((error = printer_register(pEntryPoints, printer))) { WLog_ERR(TAG, "printer_register failed with error %"PRIu32"!", error); return error; } } else { printers = driver->EnumPrinters(driver); for (i = 0; printers[i]; i++) { printer = printers[i]; if ((error = printer_register(pEntryPoints, printer))) { WLog_ERR(TAG, "printer_register failed with error %"PRIu32"!", error); free(printers); return error; } } free(printers); } return CHANNEL_RC_OK; }
816593.c
/**************************************************************************** * libs/libc/semaphore/sem_setprotocol.c * * Copyright (C) 2016-2017 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <assert.h> #include <errno.h> #include <nuttx/semaphore.h> #ifndef CONFIG_PRIORITY_INHERITANCE /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: nxsem_set_protocol * * Description: * Set semaphore protocol attribute. * * One particularly important use of this function is when a semaphore * is used for inter-task communication like: * * TASK A TASK B * nxsem_init(sem, 0, 0); * nxsem_wait(sem); * snxem_post(sem); * Awakens as holder * * In this case priority inheritance can interfere with the operation of * the semaphore. The problem is that when TASK A is restarted it is a * holder of the semaphore. However, it never calls nxsem_post(sem) so it * becomes *permanently* a holder of the semaphore and may have its * priority boosted when any other task tries to acquire the semaphore. * * The fix is to call nxsem_set_protocol(SEM_PRIO_NONE) immediately after * the sem_init() call so that there will be no priority inheritance * operations on this semaphore. * * Input Parameters: * sem - A pointer to the semaphore whose attributes are to be * modified * protocol - The new protocol to use * * Returned Value: * This function is exposed as a non-standard application interface. It * returns zero (OK) if successful. Otherwise, -1 (ERROR) is returned and * the errno value is set appropriately. * ****************************************************************************/ int nxsem_set_protocol(FAR sem_t *sem, int protocol) { DEBUGASSERT(sem != NULL); switch (protocol) { case SEM_PRIO_NONE: return OK; case SEM_PRIO_INHERIT: case SEM_PRIO_PROTECT: return -ENOSYS; break; default: break; } return -EINVAL; } /**************************************************************************** * Name: sem_setprotocol * * Description: * Set semaphore protocol attribute. * * One particularly important use of this function is when a semaphore * is used for inter-task communication like: * * TASK A TASK B * sem_init(sem, 0, 0); * sem_wait(sem); * sem_post(sem); * Awakens as holder * * In this case priority inheritance can interfere with the operation of * the semaphore. The problem is that when TASK A is restarted it is a * holder of the semaphore. However, it never calls sem_post(sem) so it * becomes *permanently* a holder of the semaphore and may have its * priority boosted when any other task tries to acquire the semaphore. * * The fix is to call sem_setprotocol(SEM_PRIO_NONE) immediately after * the sem_init() call so that there will be no priority inheritance * operations on this semaphore. * * Input Parameters: * sem - A pointer to the semaphore whose attributes are to be * modified * protocol - The new protocol to use * * Returned Value: * This function is exposed as a non-standard application interface. It * returns zero (OK) if successful. Otherwise, -1 (ERROR) is returned and * the errno value is set appropriately. * ****************************************************************************/ int sem_setprotocol(FAR sem_t *sem, int protocol) { int ret; ret = nxsem_set_protocol(sem, protocol); if (ret < 0) { set_errno(-ret); ret = ERROR; } return ret; } #endif /* !CONFIG_PRIORITY_INHERITANCE */
722577.c
// RUN: %clang_cc1 -Wparentheses -fsyntax-only -verify %s // RUN: %clang_cc1 -Wparentheses -fixit %s -o - | %clang_cc1 -Wparentheses -Werror - // Test the various warnings under -Wparentheses void if_assign(void) { int i; if (i = 4) {} // expected-warning {{assignment as a condition}} \ // expected-note{{use '==' to turn this assignment into an equality comparison}} \ // expected-note{{place parentheses around the assignment to silence this warning}} if ((i = 4)) {} } void bitwise_rel(unsigned i) { (void)(i & 0x2 == 0); // expected-warning {{& has lower precedence than ==}} \ // expected-note{{place parentheses around the & expression to evaluate it first}} \ // expected-note{{place parentheses around the == expression to silence this warning}} (void)(0 == i & 0x2); // expected-warning {{& has lower precedence than ==}} \ // expected-note{{place parentheses around the & expression to evaluate it first}} \ // expected-note{{place parentheses around the == expression to silence this warning}} (void)(i & 0xff < 30); // expected-warning {{& has lower precedence than <}} \ // expected-note{{place parentheses around the & expression to evaluate it first}} \ // expected-note{{place parentheses around the < expression to silence this warning}} (void)((i & 0x2) == 0); (void)(i & (0x2 == 0)); // Eager logical op (void)(i == 1 | i == 2 | i == 3); (void)(i != 1 & i != 2 & i != 3); (void)(i & i | i); // expected-warning {{'&' within '|'}} \ // expected-note {{place parentheses around the '&' expression to silence this warning}} (void)(i | i & i); // expected-warning {{'&' within '|'}} \ // expected-note {{place parentheses around the '&' expression to silence this warning}} (void)(i || i && i); // expected-warning {{'&&' within '||'}} \ // expected-note {{place parentheses around the '&&' expression to silence this warning}} (void)(i || i && "w00t"); // no warning. (void)("w00t" && i || i); // no warning. (void)(i || i && "w00t" || i); // expected-warning {{'&&' within '||'}} \ // expected-note {{place parentheses around the '&&' expression to silence this warning}} (void)(i || "w00t" && i || i); // expected-warning {{'&&' within '||'}} \ // expected-note {{place parentheses around the '&&' expression to silence this warning}} (void)(i && i || 0); // no warning. (void)(0 || i && i); // no warning. } _Bool someConditionFunc(); void conditional_op(int x, int y, _Bool b) { (void)(x + someConditionFunc() ? 1 : 2); // expected-warning {{operator '?:' has lower precedence than '+'}} \ // expected-note {{place parentheses around the '?:' expression to evaluate it first}} \ // expected-note {{place parentheses around the '+' expression to silence this warning}} (void)((x + someConditionFunc()) ? 1 : 2); // no warning (void)(x - b ? 1 : 2); // expected-warning {{operator '?:' has lower precedence than '-'}} \ // expected-note {{place parentheses around the '?:' expression to evaluate it first}} \ // expected-note {{place parentheses around the '-' expression to silence this warning}} (void)(x * (x == y) ? 1 : 2); // expected-warning {{operator '?:' has lower precedence than '*'}} \ // expected-note {{place parentheses around the '?:' expression to evaluate it first}} \ // expected-note {{place parentheses around the '*' expression to silence this warning}} (void)(x / !x ? 1 : 2); // expected-warning {{operator '?:' has lower precedence than '/'}} \ // expected-note {{place parentheses around the '?:' expression to evaluate it first}} \ // expected-note {{place parentheses around the '/' expression to silence this warning}} (void)(x % 2 ? 1 : 2); // no warning } // RUN: %clang_cc1 -fsyntax-only -Wparentheses -Werror -fdiagnostics-show-option %s 2>&1 | FileCheck %s // CHECK: error: using the result of an assignment as a condition without parentheses [-Werror,-Wparentheses]
385695.c
/* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "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 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 <debug.h> #include <platform/iomap.h> #include <platform/irqs.h> #include <platform/gpio.h> #include <dev/gpio.h> #include <reg.h> #include <target.h> #include <platform.h> #include <dload_util.h> #include <uart_dm.h> #include <mmc.h> #include <spmi.h> #include <board.h> #include <smem.h> #include <baseband.h> #include <dev/keys.h> #include <pm8x41.h> #include <crypto5_wrapper.h> #include <hsusb.h> #include <clock.h> #include <partition_parser.h> #include <scm.h> #include <platform/clock.h> #include <platform/gpio.h> #include <i2c_qup.h> #include <blsp_qup.h> #include <stdlib.h> enum hw_platform_subtype { HW_PLATFORM_SUBTYPE_CDP_INTERPOSER = 8, }; extern bool target_use_signed_kernel(void); static void set_sdc_power_ctrl(); static void gpio_config_debug_board(); static void gpio_config_aux_board(); static unsigned int target_id; static uint32_t pmic_ver; #if MMC_SDHCI_SUPPORT struct mmc_device *dev; #endif #define ON_SOM_3V3_POWER_EN 17 #define PMIC_ARB_CHANNEL_NUM 0 #define PMIC_ARB_OWNER_ID 0 #define WDOG_DEBUG_DISABLE_BIT 17 #define CE_INSTANCE 2 #define CE_EE 1 #define CE_FIFO_SIZE 64 #define CE_READ_PIPE 3 #define CE_WRITE_PIPE 2 #define CE_READ_PIPE_LOCK_GRP 0 #define CE_WRITE_PIPE_LOCK_GRP 0 #define CE_ARRAY_SIZE 20 #ifdef SSD_ENABLE #define SSD_CE_INSTANCE_1 1 #define SSD_PARTITION_SIZE 8192 #endif #define FASTBOOT_MODE 0x77665500 #define BOARD_SOC_VERSION1(soc_rev) (soc_rev >= 0x10000 && soc_rev < 0x20000) #if MMC_SDHCI_SUPPORT static uint32_t mmc_sdhci_base[] = { MSM_SDC1_SDHCI_BASE, MSM_SDC2_SDHCI_BASE, MSM_SDC3_SDHCI_BASE, MSM_SDC4_SDHCI_BASE }; #endif static uint32_t mmc_sdc_base[] = { MSM_SDC1_BASE, MSM_SDC2_BASE, MSM_SDC3_BASE, MSM_SDC4_BASE }; static uint32_t mmc_sdc_pwrctl_irq[] = { SDCC1_PWRCTL_IRQ, SDCC2_PWRCTL_IRQ, SDCC3_PWRCTL_IRQ, SDCC4_PWRCTL_IRQ }; void target_early_init(void) { gpio_tlmm_config(ON_SOM_3V3_POWER_EN, 0, GPIO_OUTPUT, GPIO_NO_PULL, GPIO_8MA, GPIO_DISABLE); gpio_set(ON_SOM_3V3_POWER_EN, 2); #if WITH_DEBUG_UART uart_dm_init(1, 0, BLSP1_UART1_BASE); #endif } /* Check for 8974 chip */ static int target_is_8974() { uint32_t platform = board_platform_id(); int ret = 0; switch(platform) { case APQ8074: case MSM8274: case MSM8674: case MSM8974: ret = 1; break; default: ret = 0; }; return ret; } /* Return 1 if vol_up pressed */ static int target_volume_up() { uint8_t status = 0; struct pm8x41_gpio gpio; /* CDP vol_up seems to be always grounded. So gpio status is read as 0, * whether key is pressed or not. * Ignore volume_up key on CDP for now. */ if (board_hardware_id() == HW_PLATFORM_SURF) return 0; /* Configure the GPIO */ gpio.direction = PM_GPIO_DIR_IN; gpio.function = 0; gpio.pull = PM_GPIO_PULL_UP_30; gpio.vin_sel = 2; pm8x41_gpio_config(5, &gpio); /* Wait for the pmic gpio config to take effect */ thread_sleep(1); /* Get status of P_GPIO_5 */ pm8x41_gpio_get(5, &status); return !status; /* active low */ } /* Return 1 if vol_down pressed */ uint32_t target_volume_down() { /* Volume down button is tied in with RESIN on MSM8974. */ if (target_is_8974() && (pmic_ver == PM8X41_VERSION_V2)) return pm8x41_v2_resin_status(); else return pm8x41_resin_status(); } static void target_keystatus() { keys_init(); if(target_volume_down()) keys_post_event(KEY_VOLUMEDOWN, 1); if(target_volume_up()) keys_post_event(KEY_VOLUMEUP, 1); } /* Set up params for h/w CE. */ void target_crypto_init_params() { struct crypto_init_params ce_params; /* Set up base addresses and instance. */ ce_params.crypto_instance = CE_INSTANCE; ce_params.crypto_base = MSM_CE2_BASE; ce_params.bam_base = MSM_CE2_BAM_BASE; /* Set up BAM config. */ ce_params.bam_ee = CE_EE; ce_params.pipes.read_pipe = CE_READ_PIPE; ce_params.pipes.write_pipe = CE_WRITE_PIPE; ce_params.pipes.read_pipe_grp = CE_READ_PIPE_LOCK_GRP; ce_params.pipes.write_pipe_grp = CE_WRITE_PIPE_LOCK_GRP; /* Assign buffer sizes. */ ce_params.num_ce = CE_ARRAY_SIZE; ce_params.read_fifo_size = CE_FIFO_SIZE; ce_params.write_fifo_size = CE_FIFO_SIZE; /* BAM is initialized by TZ for this platform. * Do not do it again as the initialization address space * is locked. */ ce_params.do_bam_init = 0; crypto_init_params(&ce_params); } crypto_engine_type board_ce_type(void) { return CRYPTO_ENGINE_TYPE_HW; } #if MMC_SDHCI_SUPPORT static void target_mmc_sdhci_init() { struct mmc_config_data config = {0}; uint32_t soc_ver = 0; soc_ver = board_soc_version(); /* * 8974 v1 fluid devices, have a hardware bug * which limits the bus width to 4 bit. */ switch(board_hardware_id()) { case HW_PLATFORM_FLUID: if (target_is_8974() && BOARD_SOC_VERSION1(soc_ver)) config.bus_width = DATA_BUS_WIDTH_4BIT; else config.bus_width = DATA_BUS_WIDTH_8BIT; break; default: config.bus_width = DATA_BUS_WIDTH_8BIT; }; /* Trying Slot 1*/ config.slot = 1; /* * For 8974 AC platform the software clock * plan recommends to use the following frequencies: * 200 MHz --> 192 MHZ * 400 MHZ --> 384 MHZ * only for emmc slot */ if (platform_is_8974ac()) config.max_clk_rate = MMC_CLK_192MHZ; else config.max_clk_rate = MMC_CLK_200MHZ; config.sdhc_base = mmc_sdhci_base[config.slot - 1]; config.pwrctl_base = mmc_sdc_base[config.slot - 1]; config.pwr_irq = mmc_sdc_pwrctl_irq[config.slot - 1]; if (!(dev = mmc_init(&config))) { /* Trying Slot 2 next */ config.slot = 2; config.max_clk_rate = MMC_CLK_200MHZ; config.sdhc_base = mmc_sdhci_base[config.slot - 1]; config.pwrctl_base = mmc_sdc_base[config.slot - 1]; config.pwr_irq = mmc_sdc_pwrctl_irq[config.slot - 1]; if (!(dev = mmc_init(&config))) { dprintf(CRITICAL, "mmc init failed!"); ASSERT(0); } } /* * MMC initialization is complete, read the partition table info */ if (partition_read_table()) { dprintf(CRITICAL, "Error reading the partition table info\n"); ASSERT(0); } } struct mmc_device *target_mmc_device() { return dev; } #else static void target_mmc_mci_init() { uint32_t base_addr; uint8_t slot; /* Trying Slot 1 */ slot = 1; base_addr = mmc_sdc_base[slot - 1]; if (mmc_boot_main(slot, base_addr)) { /* Trying Slot 2 next */ slot = 2; base_addr = mmc_sdc_base[slot - 1]; if (mmc_boot_main(slot, base_addr)) { dprintf(CRITICAL, "mmc init failed!"); ASSERT(0); } } } /* * Function to set the capabilities for the host */ void target_mmc_caps(struct mmc_host *host) { uint32_t soc_ver = 0; soc_ver = board_soc_version(); /* * 8974 v1 fluid devices, have a hardware bug * which limits the bus width to 4 bit. */ switch(board_hardware_id()) { case HW_PLATFORM_FLUID: if (target_is_8974() && BOARD_SOC_VERSION1(soc_ver)) host->caps.bus_width = MMC_BOOT_BUS_WIDTH_4_BIT; else host->caps.bus_width = MMC_BOOT_BUS_WIDTH_8_BIT; break; default: host->caps.bus_width = MMC_BOOT_BUS_WIDTH_8_BIT; }; host->caps.ddr_mode = 1; host->caps.hs200_mode = 1; host->caps.hs_clk_rate = MMC_CLK_96MHZ; } #endif #define VOLUME_DOWN_POLL_INTERVAL_MS (10) #define VOLUME_DOWN_SAMPLE_PERIOD_MS (2000) #define VOLUME_DOWN_SAMPLES \ (VOLUME_DOWN_SAMPLE_PERIOD_MS / VOLUME_DOWN_POLL_INTERVAL_MS) void target_init(void) { dprintf(INFO, "target_init()\n"); spmi_init(PMIC_ARB_CHANNEL_NUM, PMIC_ARB_OWNER_ID); /* Save PM8941 version info. */ pmic_ver = pm8x41_get_pmic_rev(); target_keystatus(); /* check user fastboot mode (volume-down switch) */ if (keys_get_state(KEY_VOLUMEDOWN)) { unsigned int i; for (i = 0; i < VOLUME_DOWN_SAMPLES; i++) { if(target_volume_down()) { keys_post_event(KEY_VOLUMEDOWN, 1); } else { keys_post_event(KEY_VOLUMEDOWN, 0); } if (keys_get_state(KEY_VOLUMEDOWN)) { thread_sleep(VOLUME_DOWN_POLL_INTERVAL_MS); continue; } break; } if (i == VOLUME_DOWN_SAMPLES) { dprintf(INFO, "user requested to fastboot using volume down key\n"); } } if (target_use_signed_kernel()) target_crypto_init_params(); /* Display splash screen if enabled */ #if DISPLAY_SPLASH_SCREEN dprintf(INFO, "Display Init: Start\n"); if (board_hardware_subtype() != HW_PLATFORM_SUBTYPE_CDP_INTERPOSER) { display_init(); } dprintf(INFO, "Display Init: Done\n"); #endif gpio_config_debug_board(); gpio_config_aux_board(); /* * Set drive strength & pull ctrl for * emmc */ set_sdc_power_ctrl(); #if MMC_SDHCI_SUPPORT target_mmc_sdhci_init(); #else target_mmc_mci_init(); #endif } unsigned board_machtype(void) { return target_id; } /* Do any target specific intialization needed before entering fastboot mode */ #ifdef SSD_ENABLE static void ssd_load_keystore_from_emmc() { uint64_t ptn = 0; int index = -1; uint32_t size = SSD_PARTITION_SIZE; int ret = -1; uint32_t *buffer = (uint32_t *)memalign(CACHE_LINE, ROUNDUP(SSD_PARTITION_SIZE, CACHE_LINE)); if (!buffer) { dprintf(CRITICAL, "Error Allocating memory for SSD buffer\n"); ASSERT(0); } index = partition_get_index("ssd"); ptn = partition_get_offset(index); if(ptn == 0){ dprintf(CRITICAL,"ERROR: ssd parition not found"); return; } if(mmc_read(ptn, buffer, size)){ dprintf(CRITICAL,"ERROR:Cannot read data\n"); return; } ret = scm_protect_keystore((uint32_t *)&buffer[0],size); if(ret != 0) dprintf(CRITICAL,"ERROR: scm_protect_keystore Failed"); free(buffer); } #endif void target_fastboot_init(void) { /* Set the BOOT_DONE flag in PM8921 */ pm8x41_set_boot_done(); #ifdef SSD_ENABLE clock_ce_enable(SSD_CE_INSTANCE_1); ssd_load_keystore_from_emmc(); #endif } /* Detect the target type */ void target_detect(struct board_data *board) { board->target = LINUX_MACHTYPE_UNKNOWN; } /* Detect the modem type */ void target_baseband_detect(struct board_data *board) { uint32_t platform; uint32_t platform_subtype; platform = board->platform; switch(platform) { case MSM8974: case MSM8274: case MSM8674: case MSM8274AA: case MSM8274AB: case MSM8274AC: case MSM8674AA: case MSM8674AB: case MSM8674AC: case MSM8974AA: case MSM8974AB: case MSM8974AC: case MSMSAMARIUM2: case MSMSAMARIUM9: board->baseband = BASEBAND_MSM; break; case APQ8074: case APQ8074AA: case APQ8074AB: case APQ8074AC: case MSMSAMARIUM0: board->baseband = BASEBAND_APQ; break; default: dprintf(CRITICAL, "Platform type: %u is not supported\n",platform); ASSERT(0); }; } unsigned target_baseband() { return board_baseband(); } void target_serialno(unsigned char *buf) { unsigned int serialno; if (target_is_emmc_boot()) { serialno = mmc_get_psn(); snprintf((char *)buf, 13, "%x", serialno); } } unsigned check_reboot_mode(void) { uint32_t restart_reason = 0; uint32_t soc_ver = 0; uint32_t restart_reason_addr; soc_ver = board_soc_version(); if (target_is_8974() && BOARD_SOC_VERSION1(soc_ver)) restart_reason_addr = RESTART_REASON_ADDR; else restart_reason_addr = RESTART_REASON_ADDR_V2; /* Read reboot reason and scrub it */ restart_reason = readl(restart_reason_addr); writel(0x00, restart_reason_addr); return restart_reason; } void reboot_device(unsigned reboot_reason) { uint32_t soc_ver = 0; uint8_t reset_type = 0; soc_ver = board_soc_version(); /* Write the reboot reason */ if (target_is_8974() && BOARD_SOC_VERSION1(soc_ver)) writel(reboot_reason, RESTART_REASON_ADDR); else writel(reboot_reason, RESTART_REASON_ADDR_V2); if(reboot_reason == FASTBOOT_MODE) reset_type = PON_PSHOLD_WARM_RESET; else reset_type = PON_PSHOLD_HARD_RESET; /* Configure PMIC for warm reset */ if (target_is_8974() && (pmic_ver == PM8X41_VERSION_V2)) pm8x41_v2_reset_configure(reset_type); else pm8x41_reset_configure(reset_type); /* Disable Watchdog Debug. * Required becuase of a H/W bug which causes the system to * reset partially even for non watchdog resets. */ writel(readl(GCC_WDOG_DEBUG) & ~(1 << WDOG_DEBUG_DISABLE_BIT), GCC_WDOG_DEBUG); dsb(); /* Wait until the write takes effect. */ while(readl(GCC_WDOG_DEBUG) & (1 << WDOG_DEBUG_DISABLE_BIT)); /* Drop PS_HOLD for MSM */ writel(0x00, MPM2_MPM_PS_HOLD); mdelay(5000); dprintf(CRITICAL, "Rebooting failed\n"); } int set_download_mode(enum dload_mode mode) { dload_util_write_cookie(mode == NORMAL_DLOAD ? DLOAD_MODE_ADDR_V2 : EMERGENCY_DLOAD_MODE_ADDR_V2, mode); return 0; } /* Check if MSM needs VBUS mimic for USB */ static int target_needs_vbus_mimic() { if (target_is_8974()) return 0; return 1; } /* Do target specific usb initialization */ void target_usb_init(void) { uint32_t val; dprintf(CRITICAL, "\nCheck--> board_hardware_id()= %d\n", board_hardware_id()); /* Enable secondary USB PHY on DragonBoard8074 */ if ((board_hardware_id() == HW_PLATFORM_DRAGON)||(board_hardware_id() == HW_PLATFORM_VARSOM)) { /* Route ChipIDea to use secondary USB HS port2 */ writel_relaxed(1, USB2_PHY_SEL); /* Enable access to secondary PHY by clamping the low * voltage interface between DVDD of the PHY and Vddcx * (set bit16 (USB2_PHY_HS2_DIG_CLAMP_N_2) = 1) */ writel_relaxed(readl_relaxed(USB_OTG_HS_PHY_SEC_CTRL) | 0x00010000, USB_OTG_HS_PHY_SEC_CTRL); /* Perform power-on-reset of the PHY. * Delay values are arbitrary */ writel_relaxed(readl_relaxed(USB_OTG_HS_PHY_SEC_CTRL)|1, USB_OTG_HS_PHY_SEC_CTRL); thread_sleep(10); writel_relaxed(readl_relaxed(USB_OTG_HS_PHY_SEC_CTRL) & 0xFFFFFFFE, USB_OTG_HS_PHY_SEC_CTRL); thread_sleep(10); /* Enable HSUSB PHY port for ULPI interface, * then configure related parameters within the PHY */ writel_relaxed(((readl_relaxed(USB_PORTSC) & 0xC0000000) | 0x8c000004), USB_PORTSC); } if (target_needs_vbus_mimic()) { /* Select and enable external configuration with USB PHY */ ulpi_write(ULPI_MISC_A_VBUSVLDEXTSEL | ULPI_MISC_A_VBUSVLDEXT, ULPI_MISC_A_SET); /* Enable sess_vld */ val = readl(USB_GENCONFIG_2) | GEN2_SESS_VLD_CTRL_EN; writel(val, USB_GENCONFIG_2); /* Enable external vbus configuration in the LINK */ val = readl(USB_USBCMD); val |= SESS_VLD_CTRL; writel(val, USB_USBCMD); } } uint8_t target_panel_auto_detect_enabled() { switch(board_hardware_id()) { case HW_PLATFORM_SURF: case HW_PLATFORM_MTP: case HW_PLATFORM_FLUID: return 1; break; default: return 0; break; } return 0; } uint8_t target_is_edp() { switch(board_hardware_id()) { case HW_PLATFORM_LIQUID: return 1; break; default: return 0; break; } return 0; } static uint8_t splash_override; /* Returns 1 if target supports continuous splash screen. */ int target_cont_splash_screen() { uint8_t splash_screen = 0; if(!splash_override) { switch(board_hardware_id()) { case HW_PLATFORM_SURF: case HW_PLATFORM_MTP: case HW_PLATFORM_FLUID: case HW_PLATFORM_DRAGON: case HW_PLATFORM_LIQUID: case HW_PLATFORM_VARSOM: dprintf(SPEW, "Target_cont_splash=1\n"); splash_screen = 1; break; default: dprintf(SPEW, "Target_cont_splash=0\n"); splash_screen = 0; } } return splash_screen; } void target_force_cont_splash_disable(uint8_t override) { splash_override = override; } unsigned target_pause_for_battery_charge(void) { uint8_t pon_reason = pm8x41_get_pon_reason(); /* This function will always return 0 to facilitate * automated testing/reboot with usb connected. * uncomment if this feature is needed */ /* if ((pon_reason == USB_CHG) || (pon_reason == DC_CHG)) return 1;*/ return 0; } void target_uninit(void) { #if MMC_SDHCI_SUPPORT mmc_put_card_to_sleep(dev); #else mmc_put_card_to_sleep(); #endif #ifdef SSD_ENABLE clock_ce_disable(SSD_CE_INSTANCE_1); #endif #if MMC_SDHCI_SUPPORT /* Disable HC mode before jumping to kernel */ sdhci_mode_disable(&dev->host); #endif } void shutdown_device() { dprintf(CRITICAL, "Going down for shutdown.\n"); /* Configure PMIC for shutdown. */ if (target_is_8974() && (pmic_ver == PM8X41_VERSION_V2)) pm8x41_v2_reset_configure(PON_PSHOLD_SHUTDOWN); else pm8x41_reset_configure(PON_PSHOLD_SHUTDOWN); /* Drop PS_HOLD for MSM */ writel(0x00, MPM2_MPM_PS_HOLD); mdelay(5000); dprintf(CRITICAL, "Shutdown failed\n"); } static void set_sdc_power_ctrl() { uint8_t tlmm_hdrv_clk = 0; uint32_t platform_id = 0; platform_id = board_platform_id(); switch(platform_id) { case MSM8274AA: case MSM8274AB: case MSM8674AA: case MSM8674AB: case MSM8974AA: case MSM8974AB: if (board_hardware_id() == HW_PLATFORM_MTP) tlmm_hdrv_clk = TLMM_CUR_VAL_10MA; else tlmm_hdrv_clk = TLMM_CUR_VAL_16MA; break; default: tlmm_hdrv_clk = TLMM_CUR_VAL_16MA; }; /* Drive strength configs for sdc pins */ struct tlmm_cfgs sdc1_hdrv_cfg[] = { { SDC1_CLK_HDRV_CTL_OFF, tlmm_hdrv_clk, TLMM_HDRV_MASK }, { SDC1_CMD_HDRV_CTL_OFF, TLMM_CUR_VAL_10MA, TLMM_HDRV_MASK }, { SDC1_DATA_HDRV_CTL_OFF, TLMM_CUR_VAL_10MA, TLMM_HDRV_MASK }, }; /* Pull configs for sdc pins */ struct tlmm_cfgs sdc1_pull_cfg[] = { { SDC1_CLK_PULL_CTL_OFF, TLMM_NO_PULL, TLMM_PULL_MASK }, { SDC1_CMD_PULL_CTL_OFF, TLMM_PULL_UP, TLMM_PULL_MASK }, { SDC1_DATA_PULL_CTL_OFF, TLMM_PULL_UP, TLMM_PULL_MASK }, }; struct tlmm_cfgs sdc1_rclk_cfg[] = { { SDC1_RCLK_PULL_CTL_OFF, TLMM_PULL_DOWN, TLMM_PULL_MASK }, }; /* Set the drive strength & pull control values */ tlmm_set_hdrive_ctrl(sdc1_hdrv_cfg, ARRAY_SIZE(sdc1_hdrv_cfg)); tlmm_set_pull_ctrl(sdc1_pull_cfg, ARRAY_SIZE(sdc1_pull_cfg)); /* RCLK is supported only with 8974 pro, set rclk to pull down * only for 8974 pro targets */ if (!platform_is_8974()) tlmm_set_pull_ctrl(sdc1_rclk_cfg, ARRAY_SIZE(sdc1_rclk_cfg)); } int emmc_recovery_init(void) { return _emmc_recovery_init(); } void target_usb_stop(void) { uint32_t platform = board_platform_id(); /* Disable VBUS mimicing in the controller. */ if (target_needs_vbus_mimic()) ulpi_write(ULPI_MISC_A_VBUSVLDEXTSEL | ULPI_MISC_A_VBUSVLDEXT, ULPI_MISC_A_CLEAR); } static void gpio_config_debug_board() { /* LED2 RED ON */ gpio_tlmm_config(30, /*func*/0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(30, 2); dprintf(INFO, "LED2 RED ON\n"); } static char ncp6925_config_dcdc_and_ldo_addr[] = { 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; static char ncp6925_config_dcdc_and_ldo_data[] = { 0xb0, 0xb0, 0x03, 0x34, 0x34, 0x1c, 0x1c }; static const int ncp6925_power_seq_delay = 2; static char ncp6925_power_sequence[] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f }; static const int ncp6925_power_sequence_delay[] = { 5, 5, 4, 4, 4, 4 }; static void cameras_power_config() { struct qup_i2c_dev* dev; int ret = 0; struct i2c_msg msg; char buf[2]; char* addresses = ncp6925_config_dcdc_and_ldo_addr; char* datas = ncp6925_config_dcdc_and_ldo_data; size_t size = sizeof(ncp6925_config_dcdc_and_ldo_addr); int i; dprintf(INFO, "%s:: open BLSP10 (b2/q3)\n", __FUNCTION__); // open port @ 100Khz (source clock 19.2Mhz) dev = qup_blsp_i2c_init(BLSP_ID_2, QUP_ID_3, 100000, 19200000); if (!dev) { dprintf(CRITICAL, "%s:: i2c failed to init\n", __FUNCTION__); return; } msg.addr = 0x50; msg.flags = I2C_M_WR; msg.len = 2; msg.buf = buf; for (i = 0; i < size; i++) { msg.buf[0] = addresses[i]; msg.buf[1] = datas[i]; ret = qup_i2c_xfer(dev, &msg, 1); dprintf(INFO, "%s:: power conf %d result: %d", __FUNCTION__, i, ret); } size = sizeof(ncp6925_power_sequence); datas = ncp6925_power_sequence; thread_sleep(ncp6925_power_seq_delay); for (i = 0; i < size; i++) { msg.buf[0] = 0x0b; msg.buf[1] = datas[i]; ret = qup_i2c_xfer(dev, &msg, 1); dprintf(INFO, "%s:: power seq %d result: %d", __FUNCTION__, i, ret); thread_sleep(ncp6925_power_sequence_delay[i]); } qup_i2c_deinit(dev); dprintf(INFO, "%s:: done\n", __FUNCTION__); } static void camA_pwdn_set(int enable) { if (enable) { gpio_tlmm_config(51, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, GPIO_ENABLE); gpio_set(51, 2); dprintf(INFO, "CAM A PWDN is HIGH\n"); return; } gpio_tlmm_config(51, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, GPIO_ENABLE); gpio_set(51, 0); dprintf(INFO, "CAM A PWDN is LOW\n"); } static void camB_pwdn_set(int enable) { if (enable) { gpio_tlmm_config(52, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, GPIO_ENABLE); gpio_set(52, 2); dprintf(INFO, "CAM B PWDN is HIGH\n"); return; } gpio_tlmm_config(52, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, GPIO_ENABLE); gpio_set(52, 0); dprintf(INFO, "CAM B PWDN is LOW\n"); } static void cam_pwdn_set(int enable) { camA_pwdn_set(enable); camB_pwdn_set(enable); #if 0 if (enable) { /* both cameras PWDN set to HIGH */ gpio_tlmm_config(51, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(51, 2); dprintf(INFO, "CAM A PWDN is HIGH\n"); gpio_tlmm_config(52, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(52, 2); dprintf(INFO, "CAM B PWDN is HIGH\n"); return; } /* both cameras PWDN set to LOW */ gpio_tlmm_config(51, /*func*/0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(51, 0); dprintf(INFO, "CAM A PWDN is LOW\n"); gpio_tlmm_config(52, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(52, 0); dprintf(INFO, "CAM B PWDN is LOW\n"); #endif } static void camA_reset_set(int enable) { if (enable) { gpio_tlmm_config(49, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, GPIO_ENABLE); gpio_set(49, 2); dprintf(INFO, "CAM A RESET is HIGH\n"); return; } gpio_tlmm_config(49, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, GPIO_ENABLE); gpio_set(49, 0); dprintf(INFO, "CAM A RESET is LOW\n"); } static void camB_reset_set(int enable) { if (enable) { gpio_tlmm_config(50, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, GPIO_ENABLE); gpio_set(50, 2); dprintf(INFO, "CAM B RESET is HIGH\n"); return; } gpio_tlmm_config(50, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, GPIO_ENABLE); gpio_set(50, 0); dprintf(INFO, "CAM B RESET is LOW\n"); } static void cam_reset_set(int enable) { camA_reset_set(enable); camB_reset_set(enable); #if 0 if (enable) { /* both cameras RESET set to HIGH */ gpio_tlmm_config(49, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(49, 2); dprintf(INFO, "CAM A RESET is HIGH\n"); gpio_tlmm_config(50, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(50, 2); return; } /* both cameras RESET set to LOW */ gpio_tlmm_config(49, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(49, 0); dprintf(INFO, "CAM A RESET is LOW\n"); gpio_tlmm_config(50, 0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(50, 0); dprintf(INFO, "CAM B RESET is LOW\n"); #endif } static void gpio_config_aux_board() { //GPIO_NO_PULL GPIO_PULL_DOWN GPIO_PULL_UP /* IMU power supply */ gpio_tlmm_config(53, /*func*/0, GPIO_OUTPUT, GPIO_PULL_UP, GPIO_8MA, 1); gpio_set(53, 2); dprintf(INFO, "IMU power on\n"); cam_pwdn_set(1); thread_sleep(50); cameras_power_config(); thread_sleep(150); // reset cameras camA_reset_set(0); thread_sleep(100); camA_reset_set(1); thread_sleep(100); camB_reset_set(0); thread_sleep(100); camB_reset_set(1); thread_sleep(100); }
124209.c
#include <avr/io.h> #include <compat/ina90.h> #define F_CPU 8000000UL #include <util/delay.h> #include "ISA.h" void ISA_Init(void) { // reset DDRC |= 0b00100000; // address DDRC |= 0b00011111; // read & write DDRB |= 0b11000000; PORTB |= 0b10000000; // read = 1 PORTB |= 0b01000000; // write= 1 } void ISA_HardwareReset(void) { uint16_t i; PORTC |= 0b00100000; for (i = 0; i < 10; i++ ) { _delay_ms(10); } PORTC &= ~0b00100000; } void ISA_Write(uint8_t address, uint8_t data) { PORTC = address | (PORTC & ~0b00011111); // set data bits DDRB |= 0b00000111; PORTB &= 0b11111000; PORTB |= (data & 0b00000111); DDRD |= 0b11111000; PORTD &= 0b00000111; PORTD |= (data & 0b11111000); PORTB &= ~0b01000000; // write = 0 _NOP(); PORTB |= 0b01000000; // write = 1 } uint8_t ISA_Read(uint8_t address) { uint8_t data = 0x00; DDRB &= ~0b00000111; PORTB |= 0b00000111; DDRD &= ~0b11111000; PORTD |= 0b11111000; PORTC = address | (PORTC & ~0b00011111); PORTB &= ~0b10000000; // read = 0 _NOP(); data |= (PINB & 0b00000111); data |= (PIND & 0b11111000); PORTB |= 0b10000000; // read = 1 return data; }
582263.c
//***************************************************************************** // // Startup code for use with TI's Code Composer Studio. // // Copyright (c) 2011-2014 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // //***************************************************************************** #include <stdint.h> //***************************************************************************** // // Forward declaration of the default fault handlers. // //***************************************************************************** void ResetISR(void); static void NmiSR(void); static void FaultISR(void); static void IntDefaultHandler(void); extern void USB0DeviceIntHandler(void); //***************************************************************************** // // External declaration for the reset handler that is to be called when the // processor is started // //***************************************************************************** extern void _c_int00(void); //***************************************************************************** // // Linker variable that marks the top of the stack. // //***************************************************************************** extern uint32_t __STACK_TOP; //***************************************************************************** // // External declarations for the interrupt handlers used by the application. // //***************************************************************************** // To be added by user //***************************************************************************** // // The vector table. Note that the proper constructs must be placed on this to // ensure that it ends up at physical address 0x0000.0000 or at the start of // the program if located at a start address other than 0. // //***************************************************************************** #pragma DATA_SECTION(g_pfnVectors, ".intvecs") void (* const g_pfnVectors[])(void) = { (void (*)(void))((uint32_t)&__STACK_TOP), // The initial stack pointer ResetISR, // The reset handler NmiSR, // The NMI handler FaultISR, // The hard fault handler IntDefaultHandler, // The MPU fault handler IntDefaultHandler, // The bus fault handler IntDefaultHandler, // The usage fault handler 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // SVCall handler IntDefaultHandler, // Debug monitor handler 0, // Reserved IntDefaultHandler, // The PendSV handler IntDefaultHandler, // The SysTick handler IntDefaultHandler, // GPIO Port A IntDefaultHandler, // GPIO Port B IntDefaultHandler, // GPIO Port C IntDefaultHandler, // GPIO Port D IntDefaultHandler, // GPIO Port E IntDefaultHandler, // UART0 Rx and Tx IntDefaultHandler, // UART1 Rx and Tx IntDefaultHandler, // SSI0 Rx and Tx IntDefaultHandler, // I2C0 Master and Slave IntDefaultHandler, // PWM Fault IntDefaultHandler, // PWM Generator 0 IntDefaultHandler, // PWM Generator 1 IntDefaultHandler, // PWM Generator 2 IntDefaultHandler, // Quadrature Encoder 0 IntDefaultHandler, // ADC Sequence 0 IntDefaultHandler, // ADC Sequence 1 IntDefaultHandler, // ADC Sequence 2 IntDefaultHandler, // ADC Sequence 3 IntDefaultHandler, // Watchdog timer IntDefaultHandler, // Timer 0 subtimer A IntDefaultHandler, // Timer 0 subtimer B IntDefaultHandler, // Timer 1 subtimer A IntDefaultHandler, // Timer 1 subtimer B IntDefaultHandler, // Timer 2 subtimer A IntDefaultHandler, // Timer 2 subtimer B IntDefaultHandler, // Analog Comparator 0 IntDefaultHandler, // Analog Comparator 1 IntDefaultHandler, // Analog Comparator 2 IntDefaultHandler, // System Control (PLL, OSC, BO) IntDefaultHandler, // FLASH Control IntDefaultHandler, // GPIO Port F IntDefaultHandler, // GPIO Port G IntDefaultHandler, // GPIO Port H IntDefaultHandler, // UART2 Rx and Tx IntDefaultHandler, // SSI1 Rx and Tx IntDefaultHandler, // Timer 3 subtimer A IntDefaultHandler, // Timer 3 subtimer B IntDefaultHandler, // I2C1 Master and Slave IntDefaultHandler, // Quadrature Encoder 1 IntDefaultHandler, // CAN0 IntDefaultHandler, // CAN1 0, // Reserved 0, // Reserved IntDefaultHandler, // Hibernate IntDefaultHandler, // USB0DeviceIntHandler, // USB0 IntDefaultHandler, // PWM Generator 3 IntDefaultHandler, // uDMA Software Transfer IntDefaultHandler, // uDMA Error IntDefaultHandler, // ADC1 Sequence 0 IntDefaultHandler, // ADC1 Sequence 1 IntDefaultHandler, // ADC1 Sequence 2 IntDefaultHandler, // ADC1 Sequence 3 0, // Reserved 0, // Reserved IntDefaultHandler, // GPIO Port J IntDefaultHandler, // GPIO Port K IntDefaultHandler, // GPIO Port L IntDefaultHandler, // SSI2 Rx and Tx IntDefaultHandler, // SSI3 Rx and Tx IntDefaultHandler, // UART3 Rx and Tx IntDefaultHandler, // UART4 Rx and Tx IntDefaultHandler, // UART5 Rx and Tx IntDefaultHandler, // UART6 Rx and Tx IntDefaultHandler, // UART7 Rx and Tx 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // I2C2 Master and Slave IntDefaultHandler, // I2C3 Master and Slave IntDefaultHandler, // Timer 4 subtimer A IntDefaultHandler, // Timer 4 subtimer B 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // Timer 5 subtimer A IntDefaultHandler, // Timer 5 subtimer B IntDefaultHandler, // Wide Timer 0 subtimer A IntDefaultHandler, // Wide Timer 0 subtimer B IntDefaultHandler, // Wide Timer 1 subtimer A IntDefaultHandler, // Wide Timer 1 subtimer B IntDefaultHandler, // Wide Timer 2 subtimer A IntDefaultHandler, // Wide Timer 2 subtimer B IntDefaultHandler, // Wide Timer 3 subtimer A IntDefaultHandler, // Wide Timer 3 subtimer B IntDefaultHandler, // Wide Timer 4 subtimer A IntDefaultHandler, // Wide Timer 4 subtimer B IntDefaultHandler, // Wide Timer 5 subtimer A IntDefaultHandler, // Wide Timer 5 subtimer B IntDefaultHandler, // FPU 0, // Reserved 0, // Reserved IntDefaultHandler, // I2C4 Master and Slave IntDefaultHandler, // I2C5 Master and Slave IntDefaultHandler, // GPIO Port M IntDefaultHandler, // GPIO Port N IntDefaultHandler, // Quadrature Encoder 2 0, // Reserved 0, // Reserved IntDefaultHandler, // GPIO Port P (Summary or P0) IntDefaultHandler, // GPIO Port P1 IntDefaultHandler, // GPIO Port P2 IntDefaultHandler, // GPIO Port P3 IntDefaultHandler, // GPIO Port P4 IntDefaultHandler, // GPIO Port P5 IntDefaultHandler, // GPIO Port P6 IntDefaultHandler, // GPIO Port P7 IntDefaultHandler, // GPIO Port Q (Summary or Q0) IntDefaultHandler, // GPIO Port Q1 IntDefaultHandler, // GPIO Port Q2 IntDefaultHandler, // GPIO Port Q3 IntDefaultHandler, // GPIO Port Q4 IntDefaultHandler, // GPIO Port Q5 IntDefaultHandler, // GPIO Port Q6 IntDefaultHandler, // GPIO Port Q7 IntDefaultHandler, // GPIO Port R IntDefaultHandler, // GPIO Port S IntDefaultHandler, // PWM 1 Generator 0 IntDefaultHandler, // PWM 1 Generator 1 IntDefaultHandler, // PWM 1 Generator 2 IntDefaultHandler, // PWM 1 Generator 3 IntDefaultHandler // PWM 1 Fault }; //***************************************************************************** // // This is the code that gets called when the processor first starts execution // following a reset event. Only the absolutely necessary set is performed, // after which the application supplied entry() routine is called. Any fancy // actions (such as making decisions based on the reset cause register, and // resetting the bits in that register) are left solely in the hands of the // application. // //***************************************************************************** void ResetISR(void) { // // Jump to the CCS C initialization routine. This will enable the // floating-point unit as well, so that does not need to be done here. // __asm(" .global _c_int00\n" " b.w _c_int00"); } //***************************************************************************** // // This is the code that gets called when the processor receives a NMI. This // simply enters an infinite loop, preserving the system state for examination // by a debugger. // //***************************************************************************** static void NmiSR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives a fault // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void FaultISR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives an unexpected // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void IntDefaultHandler(void) { // // Go into an infinite loop. // while(1) { } }
859897.c
#include "utility.h" #include "contact.h" void get_data(char *name) { int i = 0, j; char c, ch; __fpurge(stdin); do { c = getchar(); if (c != '\n') { *(name + i) = c; putchar(c); i++; } if (c == 8) { if (i > 0) { i--; } for (j = 0; j < i; j++) { ch = *(name + j); putchar(ch); } } } while (c != '\n'); *(name + i) = '\0'; } void get_contact_details(contact_t *contact) { printf("\nEnter name: "); __fpurge(stdin); get_data(contact->name); printf("\nEnter the Phone number: "); __fpurge(stdin); get_data(contact->ph_number); printf("\nEnter Email ID: "); __fpurge(stdin); get_data(contact->email_id); }
342495.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014, Bill Nagel <[email protected]>, Exacq Technologies * Copyright (C) 2016-2019, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && (CURL_SIZEOF_CURL_OFF_T > 4) #if !defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO) #define BUILDING_CURL_SMB_C #ifdef HAVE_PROCESS_H #include <process.h> #ifdef CURL_WINDOWS_APP #define getpid GetCurrentProcessId #elif !defined(MSDOS) #define getpid _getpid #endif #endif #include "smb.h" #include "urldata.h" #include "sendf.h" #include "multiif.h" #include "connect.h" #include "progress.h" #include "transfer.h" #include "vtls/vtls.h" #include "curl_ntlm_core.h" #include "escape.h" #include "curl_endian.h" /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* Local API functions */ static CURLcode smb_setup_connection(struct connectdata* conn); static CURLcode smb_connect(struct connectdata* conn, bool* done); static CURLcode smb_connection_state(struct connectdata* conn, bool* done); static CURLcode smb_do(struct connectdata* conn, bool* done); static CURLcode smb_request_state(struct connectdata* conn, bool* done); static CURLcode smb_done(struct connectdata* conn, CURLcode status, bool premature); static CURLcode smb_disconnect(struct connectdata* conn, bool dead); static int smb_getsock(struct connectdata* conn, curl_socket_t* socks); static CURLcode smb_parse_url_path(struct connectdata* conn); /* * SMB handler interface */ const struct Curl_handler Curl_handler_smb = { "SMB", /* scheme */ smb_setup_connection, /* setup_connection */ smb_do, /* do_it */ smb_done, /* done */ ZERO_NULL, /* do_more */ smb_connect, /* connect_it */ smb_connection_state, /* connecting */ smb_request_state, /* doing */ smb_getsock, /* proto_getsock */ smb_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ smb_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SMB, /* defport */ CURLPROTO_SMB, /* protocol */ PROTOPT_NONE /* flags */ }; #ifdef USE_SSL /* * SMBS handler interface */ const struct Curl_handler Curl_handler_smbs = { "SMBS", /* scheme */ smb_setup_connection, /* setup_connection */ smb_do, /* do_it */ smb_done, /* done */ ZERO_NULL, /* do_more */ smb_connect, /* connect_it */ smb_connection_state, /* connecting */ smb_request_state, /* doing */ smb_getsock, /* proto_getsock */ smb_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ smb_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ PORT_SMBS, /* defport */ CURLPROTO_SMBS, /* protocol */ PROTOPT_SSL /* flags */ }; #endif #define MAX_PAYLOAD_SIZE 0x8000 #define MAX_MESSAGE_SIZE (MAX_PAYLOAD_SIZE + 0x1000) #define CLIENTNAME "curl" #define SERVICENAME "?????" /* Append a string to an SMB message */ #define MSGCAT(str) \ strcpy(p, (str)); \ p += strlen(str); /* Append a null-terminated string to an SMB message */ #define MSGCATNULL(str) \ strcpy(p, (str)); \ p += strlen(str) + 1; /* SMB is mostly little endian */ #if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || defined(__OS400__) static unsigned short smb_swap16(unsigned short x) { return (unsigned short)((x << 8) | ((x >> 8) & 0xff)); } static unsigned int smb_swap32(unsigned int x) { return (x << 24) | ((x << 8) & 0xff0000) | ((x >> 8) & 0xff00) | ((x >> 24) & 0xff); } static curl_off_t smb_swap64(curl_off_t x) { return ((curl_off_t)smb_swap32((unsigned int)x) << 32) | smb_swap32((unsigned int)(x >> 32)); } #else #define smb_swap16(x) (x) #define smb_swap32(x) (x) #define smb_swap64(x) (x) #endif /* SMB request state */ enum smb_req_state { SMB_REQUESTING, SMB_TREE_CONNECT, SMB_OPEN, SMB_DOWNLOAD, SMB_UPLOAD, SMB_CLOSE, SMB_TREE_DISCONNECT, SMB_DONE }; /* SMB request data */ struct smb_request { enum smb_req_state state; char* path; unsigned short tid; /* Even if we connect to the same tree as another */ unsigned short fid; /* request, the tid will be different */ CURLcode result; }; static void conn_state(struct connectdata* conn, enum smb_conn_state newstate) { struct smb_conn* smbc = &conn->proto.smbc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* For debug purposes */ static const char* const names[] = { "SMB_NOT_CONNECTED", "SMB_CONNECTING", "SMB_NEGOTIATE", "SMB_SETUP", "SMB_CONNECTED", /* LAST */ }; if (smbc->state != newstate) infof( conn->data, "SMB conn %p state change from %s to %s\n", (void*)smbc, names[smbc->state], names[newstate]); #endif smbc->state = newstate; } static void request_state(struct connectdata* conn, enum smb_req_state newstate) { struct smb_request* req = conn->data->req.protop; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* For debug purposes */ static const char* const names[] = { "SMB_REQUESTING", "SMB_TREE_CONNECT", "SMB_OPEN", "SMB_DOWNLOAD", "SMB_UPLOAD", "SMB_CLOSE", "SMB_TREE_DISCONNECT", "SMB_DONE", /* LAST */ }; if (req->state != newstate) infof( conn->data, "SMB request %p state change from %s to %s\n", (void*)req, names[req->state], names[newstate]); #endif req->state = newstate; } /* this should setup things in the connection, not in the easy handle */ static CURLcode smb_setup_connection(struct connectdata* conn) { struct smb_request* req; /* Initialize the request state */ conn->data->req.protop = req = calloc(1, sizeof(struct smb_request)); if (!req) return CURLE_OUT_OF_MEMORY; /* Parse the URL path */ return smb_parse_url_path(conn); } static CURLcode smb_connect(struct connectdata* conn, bool* done) { struct smb_conn* smbc = &conn->proto.smbc; char* slash; (void)done; /* Check we have a username and password to authenticate with */ if (!conn->bits.user_passwd) return CURLE_LOGIN_DENIED; /* Initialize the connection state */ smbc->state = SMB_CONNECTING; smbc->recv_buf = malloc(MAX_MESSAGE_SIZE); if (!smbc->recv_buf) return CURLE_OUT_OF_MEMORY; /* Multiple requests are allowed with this connection */ connkeep(conn, "SMB default"); /* Parse the username, domain, and password */ slash = strchr(conn->user, '/'); if (!slash) slash = strchr(conn->user, '\\'); if (slash) { smbc->user = slash + 1; smbc->domain = strdup(conn->user); if (!smbc->domain) return CURLE_OUT_OF_MEMORY; smbc->domain[slash - conn->user] = 0; } else { smbc->user = conn->user; smbc->domain = strdup(conn->host.name); if (!smbc->domain) return CURLE_OUT_OF_MEMORY; } return CURLE_OK; } static CURLcode smb_recv_message(struct connectdata* conn, void** msg) { struct smb_conn* smbc = &conn->proto.smbc; char* buf = smbc->recv_buf; ssize_t bytes_read; size_t nbt_size; size_t msg_size; size_t len = MAX_MESSAGE_SIZE - smbc->got; CURLcode result; result = Curl_read(conn, FIRSTSOCKET, buf + smbc->got, len, &bytes_read); if (result) return result; if (!bytes_read) return CURLE_OK; smbc->got += bytes_read; /* Check for a 32-bit nbt header */ if (smbc->got < sizeof(unsigned int)) return CURLE_OK; nbt_size = Curl_read16_be((const unsigned char*)(buf + sizeof(unsigned short))) + sizeof(unsigned int); if (smbc->got < nbt_size) return CURLE_OK; msg_size = sizeof(struct smb_header); if (nbt_size >= msg_size + 1) { /* Add the word count */ msg_size += 1 + ((unsigned char)buf[msg_size]) * sizeof(unsigned short); if (nbt_size >= msg_size + sizeof(unsigned short)) { /* Add the byte count */ msg_size += sizeof(unsigned short) + Curl_read16_le((const unsigned char*)&buf[msg_size]); if (nbt_size < msg_size) return CURLE_READ_ERROR; } } *msg = buf; return CURLE_OK; } static void smb_pop_message(struct connectdata* conn) { struct smb_conn* smbc = &conn->proto.smbc; smbc->got = 0; } static void smb_format_message(struct connectdata* conn, struct smb_header* h, unsigned char cmd, size_t len) { struct smb_conn* smbc = &conn->proto.smbc; struct smb_request* req = conn->data->req.protop; unsigned int pid; memset(h, 0, sizeof(*h)); h->nbt_length = htons((unsigned short)(sizeof(*h) - sizeof(unsigned int) + len)); memcpy((char*)h->magic, "\xffSMB", 4); h->command = cmd; h->flags = SMB_FLAGS_CANONICAL_PATHNAMES | SMB_FLAGS_CASELESS_PATHNAMES; h->flags2 = smb_swap16(SMB_FLAGS2_IS_LONG_NAME | SMB_FLAGS2_KNOWS_LONG_NAME); h->uid = smb_swap16(smbc->uid); h->tid = smb_swap16(req->tid); pid = getpid(); h->pid_high = smb_swap16((unsigned short)(pid >> 16)); h->pid = smb_swap16((unsigned short)pid); } static CURLcode smb_send(struct connectdata* conn, ssize_t len, size_t upload_size) { struct smb_conn* smbc = &conn->proto.smbc; ssize_t bytes_written; CURLcode result; result = Curl_write(conn, FIRSTSOCKET, conn->data->state.ulbuf, len, &bytes_written); if (result) return result; if (bytes_written != len) { smbc->send_size = len; smbc->sent = bytes_written; } smbc->upload_size = upload_size; return CURLE_OK; } static CURLcode smb_flush(struct connectdata* conn) { struct smb_conn* smbc = &conn->proto.smbc; ssize_t bytes_written; ssize_t len = smbc->send_size - smbc->sent; CURLcode result; if (!smbc->send_size) return CURLE_OK; result = Curl_write(conn, FIRSTSOCKET, conn->data->state.ulbuf + smbc->sent, len, &bytes_written); if (result) return result; if (bytes_written != len) smbc->sent += bytes_written; else smbc->send_size = 0; return CURLE_OK; } static CURLcode smb_send_message(struct connectdata* conn, unsigned char cmd, const void* msg, size_t msg_len) { CURLcode result = Curl_get_upload_buffer(conn->data); if (result) return result; smb_format_message(conn, (struct smb_header*)conn->data->state.ulbuf, cmd, msg_len); memcpy(conn->data->state.ulbuf + sizeof(struct smb_header), msg, msg_len); return smb_send(conn, sizeof(struct smb_header) + msg_len, 0); } static CURLcode smb_send_negotiate(struct connectdata* conn) { const char* msg = "\x00\x0c\x00\x02NT LM 0.12"; return smb_send_message(conn, SMB_COM_NEGOTIATE, msg, 15); } static CURLcode smb_send_setup(struct connectdata* conn) { struct smb_conn* smbc = &conn->proto.smbc; struct smb_setup msg; char* p = msg.bytes; unsigned char lm_hash[21]; unsigned char lm[24]; unsigned char nt_hash[21]; unsigned char nt[24]; size_t byte_count = sizeof(lm) + sizeof(nt); byte_count += strlen(smbc->user) + strlen(smbc->domain); byte_count += strlen(OS) + strlen(CLIENTNAME) + 4; /* 4 null chars */ if (byte_count > sizeof(msg.bytes)) return CURLE_FILESIZE_EXCEEDED; Curl_ntlm_core_mk_lm_hash(conn->data, conn->passwd, lm_hash); Curl_ntlm_core_lm_resp(lm_hash, smbc->challenge, lm); #ifdef USE_NTRESPONSES Curl_ntlm_core_mk_nt_hash(conn->data, conn->passwd, nt_hash); Curl_ntlm_core_lm_resp(nt_hash, smbc->challenge, nt); #else memset(nt, 0, sizeof(nt)); #endif memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_SETUP_ANDX; msg.andx.command = SMB_COM_NO_ANDX_COMMAND; msg.max_buffer_size = smb_swap16(MAX_MESSAGE_SIZE); msg.max_mpx_count = smb_swap16(1); msg.vc_number = smb_swap16(1); msg.session_key = smb_swap32(smbc->session_key); msg.capabilities = smb_swap32(SMB_CAP_LARGE_FILES); msg.lengths[0] = smb_swap16(sizeof(lm)); msg.lengths[1] = smb_swap16(sizeof(nt)); memcpy(p, lm, sizeof(lm)); p += sizeof(lm); memcpy(p, nt, sizeof(nt)); p += sizeof(nt); MSGCATNULL(smbc->user); MSGCATNULL(smbc->domain); MSGCATNULL(OS); MSGCATNULL(CLIENTNAME); byte_count = p - msg.bytes; msg.byte_count = smb_swap16((unsigned short)byte_count); return smb_send_message( conn, SMB_COM_SETUP_ANDX, &msg, sizeof(msg) - sizeof(msg.bytes) + byte_count); } static CURLcode smb_send_tree_connect(struct connectdata* conn) { struct smb_tree_connect msg; struct smb_conn* smbc = &conn->proto.smbc; char* p = msg.bytes; size_t byte_count = strlen(conn->host.name) + strlen(smbc->share); byte_count += strlen(SERVICENAME) + 5; /* 2 nulls and 3 backslashes */ if (byte_count > sizeof(msg.bytes)) return CURLE_FILESIZE_EXCEEDED; memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_TREE_CONNECT_ANDX; msg.andx.command = SMB_COM_NO_ANDX_COMMAND; msg.pw_len = 0; MSGCAT("\\\\"); MSGCAT(conn->host.name); MSGCAT("\\"); MSGCATNULL(smbc->share); MSGCATNULL(SERVICENAME); /* Match any type of service */ byte_count = p - msg.bytes; msg.byte_count = smb_swap16((unsigned short)byte_count); return smb_send_message( conn, SMB_COM_TREE_CONNECT_ANDX, &msg, sizeof(msg) - sizeof(msg.bytes) + byte_count); } static CURLcode smb_send_open(struct connectdata* conn) { struct smb_request* req = conn->data->req.protop; struct smb_nt_create msg; size_t byte_count; if ((strlen(req->path) + 1) > sizeof(msg.bytes)) return CURLE_FILESIZE_EXCEEDED; memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_NT_CREATE_ANDX; msg.andx.command = SMB_COM_NO_ANDX_COMMAND; byte_count = strlen(req->path); msg.name_length = smb_swap16((unsigned short)byte_count); msg.share_access = smb_swap32(SMB_FILE_SHARE_ALL); if (conn->data->set.upload) { msg.access = smb_swap32(SMB_GENERIC_READ | SMB_GENERIC_WRITE); msg.create_disposition = smb_swap32(SMB_FILE_OVERWRITE_IF); } else { msg.access = smb_swap32(SMB_GENERIC_READ); msg.create_disposition = smb_swap32(SMB_FILE_OPEN); } msg.byte_count = smb_swap16((unsigned short)++byte_count); strcpy(msg.bytes, req->path); return smb_send_message( conn, SMB_COM_NT_CREATE_ANDX, &msg, sizeof(msg) - sizeof(msg.bytes) + byte_count); } static CURLcode smb_send_close(struct connectdata* conn) { struct smb_request* req = conn->data->req.protop; struct smb_close msg; memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_CLOSE; msg.fid = smb_swap16(req->fid); return smb_send_message(conn, SMB_COM_CLOSE, &msg, sizeof(msg)); } static CURLcode smb_send_tree_disconnect(struct connectdata* conn) { struct smb_tree_disconnect msg; memset(&msg, 0, sizeof(msg)); return smb_send_message(conn, SMB_COM_TREE_DISCONNECT, &msg, sizeof(msg)); } static CURLcode smb_send_read(struct connectdata* conn) { struct smb_request* req = conn->data->req.protop; curl_off_t offset = conn->data->req.offset; struct smb_read msg; memset(&msg, 0, sizeof(msg)); msg.word_count = SMB_WC_READ_ANDX; msg.andx.command = SMB_COM_NO_ANDX_COMMAND; msg.fid = smb_swap16(req->fid); msg.offset = smb_swap32((unsigned int)offset); msg.offset_high = smb_swap32((unsigned int)(offset >> 32)); msg.min_bytes = smb_swap16(MAX_PAYLOAD_SIZE); msg.max_bytes = smb_swap16(MAX_PAYLOAD_SIZE); return smb_send_message(conn, SMB_COM_READ_ANDX, &msg, sizeof(msg)); } static CURLcode smb_send_write(struct connectdata* conn) { struct smb_write* msg; struct smb_request* req = conn->data->req.protop; curl_off_t offset = conn->data->req.offset; curl_off_t upload_size = conn->data->req.size - conn->data->req.bytecount; CURLcode result = Curl_get_upload_buffer(conn->data); if (result) return result; msg = (struct smb_write*)conn->data->state.ulbuf; if (upload_size >= MAX_PAYLOAD_SIZE - 1) /* There is one byte of padding */ upload_size = MAX_PAYLOAD_SIZE - 1; memset(msg, 0, sizeof(*msg)); msg->word_count = SMB_WC_WRITE_ANDX; msg->andx.command = SMB_COM_NO_ANDX_COMMAND; msg->fid = smb_swap16(req->fid); msg->offset = smb_swap32((unsigned int)offset); msg->offset_high = smb_swap32((unsigned int)(offset >> 32)); msg->data_length = smb_swap16((unsigned short)upload_size); msg->data_offset = smb_swap16(sizeof(*msg) - sizeof(unsigned int)); msg->byte_count = smb_swap16((unsigned short)(upload_size + 1)); smb_format_message( conn, &msg->h, SMB_COM_WRITE_ANDX, sizeof(*msg) - sizeof(msg->h) + (size_t)upload_size); return smb_send(conn, sizeof(*msg), (size_t)upload_size); } static CURLcode smb_send_and_recv(struct connectdata* conn, void** msg) { struct smb_conn* smbc = &conn->proto.smbc; CURLcode result; *msg = NULL; /* if it returns early */ /* Check if there is data in the transfer buffer */ if (!smbc->send_size && smbc->upload_size) { size_t nread = smbc->upload_size > conn->data->set.upload_buffer_size ? conn->data->set.upload_buffer_size : smbc->upload_size; conn->data->req.upload_fromhere = conn->data->state.ulbuf; result = Curl_fillreadbuffer(conn, nread, &nread); if (result && result != CURLE_AGAIN) return result; if (!nread) return CURLE_OK; smbc->upload_size -= nread; smbc->send_size = nread; smbc->sent = 0; } /* Check if there is data to send */ if (smbc->send_size) { result = smb_flush(conn); if (result) return result; } /* Check if there is still data to be sent */ if (smbc->send_size || smbc->upload_size) return CURLE_AGAIN; return smb_recv_message(conn, msg); } static CURLcode smb_connection_state(struct connectdata* conn, bool* done) { struct smb_conn* smbc = &conn->proto.smbc; struct smb_negotiate_response* nrsp; struct smb_header* h; CURLcode result; void* msg = NULL; if (smbc->state == SMB_CONNECTING) { #ifdef USE_SSL if ((conn->handler->flags & PROTOPT_SSL)) { bool ssl_done = FALSE; result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, &ssl_done); if (result && result != CURLE_AGAIN) return result; if (!ssl_done) return CURLE_OK; } #endif result = smb_send_negotiate(conn); if (result) { connclose(conn, "SMB: failed to send negotiate message"); return result; } conn_state(conn, SMB_NEGOTIATE); } /* Send the previous message and check for a response */ result = smb_send_and_recv(conn, &msg); if (result && result != CURLE_AGAIN) { connclose(conn, "SMB: failed to communicate"); return result; } if (!msg) return CURLE_OK; h = msg; switch (smbc->state) { case SMB_NEGOTIATE: if ((smbc->got < sizeof(*nrsp) + sizeof(smbc->challenge) - 1) || h->status) { connclose(conn, "SMB: negotiation failed"); return CURLE_COULDNT_CONNECT; } nrsp = msg; memcpy(smbc->challenge, nrsp->bytes, sizeof(smbc->challenge)); smbc->session_key = smb_swap32(nrsp->session_key); result = smb_send_setup(conn); if (result) { connclose(conn, "SMB: failed to send setup message"); return result; } conn_state(conn, SMB_SETUP); break; case SMB_SETUP: if (h->status) { connclose(conn, "SMB: authentication failed"); return CURLE_LOGIN_DENIED; } smbc->uid = smb_swap16(h->uid); conn_state(conn, SMB_CONNECTED); *done = true; break; default: smb_pop_message(conn); return CURLE_OK; /* ignore */ } smb_pop_message(conn); return CURLE_OK; } /* * Convert a timestamp from the Windows world (100 nsec units from 1 Jan 1601) * to Posix time. Cap the output to fit within a time_t. */ static void get_posix_time(time_t* out, curl_off_t timestamp) { timestamp -= 116444736000000000; timestamp /= 10000000; #if SIZEOF_TIME_T < SIZEOF_CURL_OFF_T if (timestamp > TIME_T_MAX) *out = TIME_T_MAX; else if (timestamp < TIME_T_MIN) *out = TIME_T_MIN; else #endif *out = (time_t)timestamp; } static CURLcode smb_request_state(struct connectdata* conn, bool* done) { struct smb_request* req = conn->data->req.protop; struct smb_header* h; struct smb_conn* smbc = &conn->proto.smbc; enum smb_req_state next_state = SMB_DONE; unsigned short len; unsigned short off; CURLcode result; void* msg = NULL; const struct smb_nt_create_response* smb_m; /* Start the request */ if (req->state == SMB_REQUESTING) { result = smb_send_tree_connect(conn); if (result) { connclose(conn, "SMB: failed to send tree connect message"); return result; } request_state(conn, SMB_TREE_CONNECT); } /* Send the previous message and check for a response */ result = smb_send_and_recv(conn, &msg); if (result && result != CURLE_AGAIN) { connclose(conn, "SMB: failed to communicate"); return result; } if (!msg) return CURLE_OK; h = msg; switch (req->state) { case SMB_TREE_CONNECT: if (h->status) { req->result = CURLE_REMOTE_FILE_NOT_FOUND; if (h->status == smb_swap32(SMB_ERR_NOACCESS)) req->result = CURLE_REMOTE_ACCESS_DENIED; break; } req->tid = smb_swap16(h->tid); next_state = SMB_OPEN; break; case SMB_OPEN: if (h->status || smbc->got < sizeof(struct smb_nt_create_response)) { req->result = CURLE_REMOTE_FILE_NOT_FOUND; if (h->status == smb_swap32(SMB_ERR_NOACCESS)) req->result = CURLE_REMOTE_ACCESS_DENIED; next_state = SMB_TREE_DISCONNECT; break; } smb_m = (const struct smb_nt_create_response*)msg; req->fid = smb_swap16(smb_m->fid); conn->data->req.offset = 0; if (conn->data->set.upload) { conn->data->req.size = conn->data->state.infilesize; Curl_pgrsSetUploadSize(conn->data, conn->data->req.size); next_state = SMB_UPLOAD; } else { smb_m = (const struct smb_nt_create_response*)msg; conn->data->req.size = smb_swap64(smb_m->end_of_file); if (conn->data->req.size < 0) { req->result = CURLE_WEIRD_SERVER_REPLY; next_state = SMB_CLOSE; } else { Curl_pgrsSetDownloadSize(conn->data, conn->data->req.size); if (conn->data->set.get_filetime) get_posix_time(&conn->data->info.filetime, smb_m->last_change_time); next_state = SMB_DOWNLOAD; } } break; case SMB_DOWNLOAD: if (h->status || smbc->got < sizeof(struct smb_header) + 14) { req->result = CURLE_RECV_ERROR; next_state = SMB_CLOSE; break; } len = Curl_read16_le(((const unsigned char*)msg) + sizeof(struct smb_header) + 11); off = Curl_read16_le(((const unsigned char*)msg) + sizeof(struct smb_header) + 13); if (len > 0) { if (off + sizeof(unsigned int) + len > smbc->got) { failf(conn->data, "Invalid input packet"); result = CURLE_RECV_ERROR; } else result = Curl_client_write( conn, CLIENTWRITE_BODY, (char*)msg + off + sizeof(unsigned int), len); if (result) { req->result = result; next_state = SMB_CLOSE; break; } } conn->data->req.bytecount += len; conn->data->req.offset += len; Curl_pgrsSetDownloadCounter(conn->data, conn->data->req.bytecount); next_state = (len < MAX_PAYLOAD_SIZE) ? SMB_CLOSE : SMB_DOWNLOAD; break; case SMB_UPLOAD: if (h->status || smbc->got < sizeof(struct smb_header) + 6) { req->result = CURLE_UPLOAD_FAILED; next_state = SMB_CLOSE; break; } len = Curl_read16_le(((const unsigned char*)msg) + sizeof(struct smb_header) + 5); conn->data->req.bytecount += len; conn->data->req.offset += len; Curl_pgrsSetUploadCounter(conn->data, conn->data->req.bytecount); if (conn->data->req.bytecount >= conn->data->req.size) next_state = SMB_CLOSE; else next_state = SMB_UPLOAD; break; case SMB_CLOSE: /* We don't care if the close failed, proceed to tree disconnect anyway */ next_state = SMB_TREE_DISCONNECT; break; case SMB_TREE_DISCONNECT: next_state = SMB_DONE; break; default: smb_pop_message(conn); return CURLE_OK; /* ignore */ } smb_pop_message(conn); switch (next_state) { case SMB_OPEN: result = smb_send_open(conn); break; case SMB_DOWNLOAD: result = smb_send_read(conn); break; case SMB_UPLOAD: result = smb_send_write(conn); break; case SMB_CLOSE: result = smb_send_close(conn); break; case SMB_TREE_DISCONNECT: result = smb_send_tree_disconnect(conn); break; case SMB_DONE: result = req->result; *done = true; break; default: break; } if (result) { connclose(conn, "SMB: failed to send message"); return result; } request_state(conn, next_state); return CURLE_OK; } static CURLcode smb_done(struct connectdata* conn, CURLcode status, bool premature) { (void)premature; Curl_safefree(conn->data->req.protop); return status; } static CURLcode smb_disconnect(struct connectdata* conn, bool dead) { struct smb_conn* smbc = &conn->proto.smbc; (void)dead; Curl_safefree(smbc->share); Curl_safefree(smbc->domain); Curl_safefree(smbc->recv_buf); return CURLE_OK; } static int smb_getsock(struct connectdata* conn, curl_socket_t* socks) { socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0); } static CURLcode smb_do(struct connectdata* conn, bool* done) { struct smb_conn* smbc = &conn->proto.smbc; *done = FALSE; if (smbc->share) { return CURLE_OK; } return CURLE_URL_MALFORMAT; } static CURLcode smb_parse_url_path(struct connectdata* conn) { struct Curl_easy* data = conn->data; struct smb_request* req = data->req.protop; struct smb_conn* smbc = &conn->proto.smbc; char* path; char* slash; /* URL decode the path */ CURLcode result = Curl_urldecode(data, data->state.up.path, 0, &path, NULL, TRUE); if (result) return result; /* Parse the path for the share */ smbc->share = strdup((*path == '/' || *path == '\\') ? path + 1 : path); free(path); if (!smbc->share) return CURLE_OUT_OF_MEMORY; slash = strchr(smbc->share, '/'); if (!slash) slash = strchr(smbc->share, '\\'); /* The share must be present */ if (!slash) { Curl_safefree(smbc->share); return CURLE_URL_MALFORMAT; } /* Parse the path for the file path converting any forward slashes into backslashes */ *slash++ = 0; req->path = slash; for (; *slash; slash++) { if (*slash == '/') *slash = '\\'; } return CURLE_OK; } #endif /* !USE_WINDOWS_SSPI || USE_WIN32_CRYPTO */ #endif /* CURL_DISABLE_SMB && USE_NTLM && CURL_SIZEOF_CURL_OFF_T > 4 */
664806.c
/* { dg-do compile } */ /* { dg-options "-O1 -fdump-tree-cddce3" } */ extern void abort (void); struct rtx_def; typedef struct rtx_def *rtx; enum rtx_code { UNKNOWN, CODE_LABEL, NOTE, LAST_AND_UNUSED_RTX_CODE = 256 }; typedef union rtunion_def rtunion; struct rtx_def { enum rtx_code code:16; }; void delete_dead_jumptables () { rtx insn, next; if (insn->code == CODE_LABEL) { rtx const _rtx = insn; if (_rtx->code != CODE_LABEL && _rtx->code != NOTE) abort (); } ; } /* There should be no loads of ->code. If any exist, then we failed to optimize away all the IF statements and the statements feeding their conditions. */ /* { dg-final { scan-tree-dump-times "->code" 0 "cddce3"} } */ /* There should be no IF statements. */ /* { dg-final { scan-tree-dump-times "if " 0 "cddce3"} } */
125181.c
/// @file rainbow.c /// @brief The standard implementations for functions in rainbow.h /// #include "blas.h" #include "parallel_matrix_op.h" #include "rainbow.h" #include "rainbow_blas.h" #include "rainbow_config.h" #include "rainbow_keypair.h" #include "utils_hash.h" #include "utils_prng.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #define MAX_ATTEMPT_FRMAT 128 int PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_rainbow_sign(uint8_t *signature, const sk_t *sk, const uint8_t *_digest) { uint8_t mat_l1[_O1 * _O1_BYTE]; uint8_t mat_l2[_O2 * _O2_BYTE]; uint8_t mat_buffer[2 * _MAX_O * _MAX_O_BYTE]; // setup PRNG prng_t prng_sign; uint8_t prng_preseed[LEN_SKSEED + _HASH_LEN]; memcpy(prng_preseed, sk->sk_seed, LEN_SKSEED); memcpy(prng_preseed + LEN_SKSEED, _digest, _HASH_LEN); // prng_preseed = sk_seed || digest uint8_t prng_seed[_HASH_LEN]; PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_hash_msg(prng_seed, _HASH_LEN, prng_preseed, _HASH_LEN + LEN_SKSEED); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_prng_set(&prng_sign, prng_seed, _HASH_LEN); // seed = H( sk_seed || digest ) for (unsigned int i = 0; i < LEN_SKSEED + _HASH_LEN; i++) { prng_preseed[i] ^= prng_preseed[i]; // clean } for (unsigned int i = 0; i < _HASH_LEN; i++) { prng_seed[i] ^= prng_seed[i]; // clean } // roll vinegars. uint8_t vinegar[_V1_BYTE]; unsigned int n_attempt = 0; unsigned int l1_succ = 0; while (!l1_succ) { if (MAX_ATTEMPT_FRMAT <= n_attempt) { break; } PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_prng_gen(&prng_sign, vinegar, _V1_BYTE); // generating vinegars gfmat_prod(mat_l1, sk->l1_F2, _O1 * _O1_BYTE, _V1, vinegar); // generating the linear equations for layer 1 l1_succ = gfmat_inv(mat_l1, mat_l1, _O1, mat_buffer); // check if the linear equation solvable n_attempt++; } // Given the vinegars, pre-compute variables needed for layer 2 uint8_t r_l1_F1[_O1_BYTE] = {0}; uint8_t r_l2_F1[_O2_BYTE] = {0}; batch_quad_trimat_eval(r_l1_F1, sk->l1_F1, vinegar, _V1, _O1_BYTE); batch_quad_trimat_eval(r_l2_F1, sk->l2_F1, vinegar, _V1, _O2_BYTE); uint8_t mat_l2_F3[_O2 * _O2_BYTE]; uint8_t mat_l2_F2[_O1 * _O2_BYTE]; gfmat_prod(mat_l2_F3, sk->l2_F3, _O2 * _O2_BYTE, _V1, vinegar); gfmat_prod(mat_l2_F2, sk->l2_F2, _O1 * _O2_BYTE, _V1, vinegar); // Some local variables. uint8_t _z[_PUB_M_BYTE]; uint8_t y[_PUB_M_BYTE]; uint8_t *x_v1 = vinegar; uint8_t x_o1[_O1_BYTE]; uint8_t x_o2[_O1_BYTE]; uint8_t digest_salt[_HASH_LEN + _SALT_BYTE]; memcpy(digest_salt, _digest, _HASH_LEN); uint8_t *salt = digest_salt + _HASH_LEN; uint8_t temp_o[_MAX_O_BYTE + 32] = {0}; unsigned int succ = 0; while (!succ) { if (MAX_ATTEMPT_FRMAT <= n_attempt) { break; } // The computation: H(digest||salt) --> z --S--> y --C-map--> x --T--> w PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_prng_gen(&prng_sign, salt, _SALT_BYTE); // roll the salt PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_hash_msg(_z, _PUB_M_BYTE, digest_salt, _HASH_LEN + _SALT_BYTE); // H(digest||salt) // y = S^-1 * z memcpy(y, _z, _PUB_M_BYTE); // identity part of S gfmat_prod(temp_o, sk->s1, _O1_BYTE, _O2, _z + _O1_BYTE); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(y, temp_o, _O1_BYTE); // Central Map: // layer 1: calculate x_o1 memcpy(temp_o, r_l1_F1, _O1_BYTE); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(temp_o, y, _O1_BYTE); gfmat_prod(x_o1, mat_l1, _O1_BYTE, _O1, temp_o); // layer 2: calculate x_o2 PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_set_zero(temp_o, _O2_BYTE); gfmat_prod(temp_o, mat_l2_F2, _O2_BYTE, _O1, x_o1); // F2 batch_quad_trimat_eval(mat_l2, sk->l2_F5, x_o1, _O1, _O2_BYTE); // F5 PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(temp_o, mat_l2, _O2_BYTE); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(temp_o, r_l2_F1, _O2_BYTE); // F1 PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(temp_o, y + _O1_BYTE, _O2_BYTE); // generate the linear equations of the 2nd layer gfmat_prod(mat_l2, sk->l2_F6, _O2 * _O2_BYTE, _O1, x_o1); // F6 PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(mat_l2, mat_l2_F3, _O2 * _O2_BYTE); // F3 succ = gfmat_inv(mat_l2, mat_l2, _O2, mat_buffer); gfmat_prod(x_o2, mat_l2, _O2_BYTE, _O2, temp_o); // solve l2 eqs n_attempt++; }; // w = T^-1 * y uint8_t w[_PUB_N_BYTE]; // identity part of T. memcpy(w, x_v1, _V1_BYTE); memcpy(w + _V1_BYTE, x_o1, _O1_BYTE); memcpy(w + _V2_BYTE, x_o2, _O2_BYTE); // Computing the t1 part. gfmat_prod(y, sk->t1, _V1_BYTE, _O1, x_o1); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(w, y, _V1_BYTE); // Computing the t4 part. gfmat_prod(y, sk->t4, _V1_BYTE, _O2, x_o2); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(w, y, _V1_BYTE); // Computing the t3 part. gfmat_prod(y, sk->t3, _O1_BYTE, _O2, x_o2); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(w + _V1_BYTE, y, _O1_BYTE); memset(signature, 0, _SIGNATURE_BYTE); // set the output 0 // clean memset(&prng_sign, 0, sizeof(prng_t)); memset(vinegar, 0, _V1_BYTE); memset(r_l1_F1, 0, _O1_BYTE); memset(r_l2_F1, 0, _O2_BYTE); memset(_z, 0, _PUB_M_BYTE); memset(y, 0, _PUB_M_BYTE); memset(x_o1, 0, _O1_BYTE); memset(x_o2, 0, _O2_BYTE); memset(temp_o, 0, sizeof(temp_o)); // return: copy w and salt to the signature. if (MAX_ATTEMPT_FRMAT <= n_attempt) { return -1; } PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(signature, w, _PUB_N_BYTE); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_gf256v_add(signature + _PUB_N_BYTE, salt, _SALT_BYTE); return 0; } int PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_rainbow_verify(const uint8_t *digest, const uint8_t *signature, const pk_t *pk) { unsigned char digest_ck[_PUB_M_BYTE]; // public_map( digest_ck , pk , signature ); Evaluating the quadratic public polynomials. batch_quad_trimat_eval(digest_ck, pk->pk, signature, _PUB_N, _PUB_M_BYTE); unsigned char correct[_PUB_M_BYTE]; unsigned char digest_salt[_HASH_LEN + _SALT_BYTE]; memcpy(digest_salt, digest, _HASH_LEN); memcpy(digest_salt + _HASH_LEN, signature + _PUB_N_BYTE, _SALT_BYTE); PQCLEAN_RAINBOWIIICCLASSIC_CLEAN_hash_msg(correct, _PUB_M_BYTE, digest_salt, _HASH_LEN + _SALT_BYTE); // H( digest || salt ) // check consistancy. unsigned char cc = 0; for (unsigned int i = 0; i < _PUB_M_BYTE; i++) { cc |= (digest_ck[i] ^ correct[i]); } return (0 == cc) ? 0 : -1; }
939128.c
/***************************************************************************** * Module name: main.c * * First written on May 23, 2019 by Miguel. * *****************************************************************************/ #include <stdio.h> #include "CommandInterpreter.h" #define MAX_SIZE_OF_INPUT_LINE 128 int main(void) { char userInputLine[MAX_SIZE_OF_INPUT_LINE]; CommandInt_Init(); while(1) { printf("> "); fgets(userInputLine, sizeof(userInputLine), stdin); CommandInt_Handle(userInputLine); } return 0; }
272162.c
// Copyright (c) 2004-2013 Sergey Lyubka // Copyright (c) 2013-2021 Cesanta Software Limited // All rights reserved // // This software is dual-licensed: 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. For the terms of this // license, see <http://www.gnu.org/licenses/>. // // You are free to use this software under the terms of the GNU General // Public License, 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. // // Alternatively, you can license this software under a commercial // license, as set out in <https://www.cesanta.com/license>. #include "mongoose.h" #ifdef MG_ENABLE_LINES #line 1 "src/private.h" #endif void mg_connect_resolved(struct mg_connection *); #if MG_ARCH == MG_ARCH_FREERTOS static inline void *mg_calloc(int cnt, size_t size) { void *p = pvPortMalloc(size); if (p != NULL) memset(p, 0, size); return p; } #define calloc(a, b) mg_calloc((a), (b)) #define malloc(a) pvPortMalloc(a) #define free(a) vPortFree(a) #endif #ifdef MG_ENABLE_LINES #line 1 "src/base64.c" #endif #include <string.h> static int mg_b64idx(int c) { if (c < 26) { return c + 'A'; } else if (c < 52) { return c - 26 + 'a'; } else if (c < 62) { return c - 52 + '0'; } else { return c == 62 ? '+' : '/'; } } static int mg_b64rev(int c) { if (c >= 'A' && c <= 'Z') { return c - 'A'; } else if (c >= 'a' && c <= 'z') { return c + 26 - 'a'; } else if (c >= '0' && c <= '9') { return c + 52 - '0'; } else if (c == '+') { return 62; } else if (c == '/') { return 63; } else if (c == '=') { return 64; } else { return -1; } } int mg_base64_update(unsigned char ch, char *to, int n) { unsigned char rem = (n & 3) % 3; if (rem == 0) { to[n] = mg_b64idx(ch >> 2); to[++n] = (ch & 3) << 4; } else if (rem == 1) { to[n] = mg_b64idx(to[n] | (ch >> 4)); to[++n] = (ch & 15) << 2; } else { to[n] = mg_b64idx(to[n] | (ch >> 6)); to[++n] = mg_b64idx(ch & 63); n++; } return n; } int mg_base64_final(char *to, int n) { int saved = n; // printf("---[%.*s]\n", n, to); if (n & 3) n = mg_base64_update(0, to, n); if ((saved & 3) == 2) n--; // printf(" %d[%.*s]\n", n, n, to); while (n & 3) to[n++] = '='; to[n] = '\0'; return n; } int mg_base64_encode(const unsigned char *p, int n, char *to) { int i, len = 0; for (i = 0; i < n; i++) len = mg_base64_update(p[i], to, len); len = mg_base64_final(to, len); return len; } int mg_base64_decode(const char *src, int n, char *dst) { const char *end = src + n; int len = 0; while (src + 3 < end) { int a = mg_b64rev(src[0]), b = mg_b64rev(src[1]), c = mg_b64rev(src[2]), d = mg_b64rev(src[3]); if (a == 64 || a < 0 || b == 64 || b < 0 || c < 0 || d < 0) return 0; dst[len++] = (a << 2) | (b >> 4); if (src[2] != '=') { dst[len++] = (b << 4) | (c >> 2); if (src[3] != '=') dst[len++] = (c << 6) | d; } src += 4; } dst[len] = '\0'; return len; } #ifdef MG_ENABLE_LINES #line 1 "src/dns.c" #endif struct dns_data { struct dns_data *next; struct mg_connection *c; unsigned long expire; uint16_t txnid; }; static struct dns_data *s_reqs; // Active DNS requests static void mg_sendnsreq(struct mg_connection *, struct mg_str *, int, struct mg_dns *, bool); static void mg_dns_free(struct dns_data *d) { LIST_DELETE(struct dns_data, &s_reqs, d); free(d); } void mg_resolve_cancel(struct mg_connection *c) { struct dns_data *tmp, *d; for (d = s_reqs; d != NULL; d = tmp) { tmp = d->next; if (d->c == c) mg_dns_free(d); } } static size_t mg_dns_parse_name_depth(const uint8_t *s, size_t len, size_t ofs, char *to, size_t tolen, int depth) { size_t i = 0, j = 0; if (tolen > 0) to[0] = '\0'; if (depth > 5) return 0; while (ofs + i + 1 < len) { size_t n = s[ofs + i]; if (n == 0) { i++; break; } if (n & 0xc0) { size_t ptr = (((n & 0x3f) << 8) | s[ofs + i + 1]); // 12 is hdr len if (ptr + 1 < len && (s[ptr] & 0xc0) == 0 && mg_dns_parse_name_depth(s, len, ptr, to, tolen, depth + 1) == 0) return 0; i += 2; break; } if (ofs + i + n + 1 >= len) return 0; if (j > 0) { if (j < tolen) to[j] = '.'; j++; } if (j + n < tolen) memcpy(&to[j], &s[ofs + i + 1], n); j += n; i += n + 1; if (j < tolen) to[j] = '\0'; // Zero-terminate this chunk } if (tolen > 0) to[tolen - 1] = '\0'; // Make sure make sure it is nul-term return i; } size_t mg_dns_parse_name(const uint8_t *s, size_t n, size_t ofs, char *dst, size_t dstlen) { return mg_dns_parse_name_depth(s, n, ofs, dst, dstlen, 0); } size_t mg_dns_parse_rr(const uint8_t *buf, size_t len, size_t ofs, bool is_question, struct mg_dns_rr *rr) { const uint8_t *s = buf + ofs, *e = &buf[len]; memset(rr, 0, sizeof(*rr)); if (len < sizeof(struct mg_dns_header)) return 0; // Too small if (len > 512) return 0; // Too large, we don't expect that if (s >= e) return 0; // Overflow if ((rr->nlen = (uint16_t) mg_dns_parse_name(buf, len, ofs, NULL, 0)) == 0) return 0; s += rr->nlen + 4; if (s > e) return 0; rr->atype = ((uint16_t) s[-4] << 8) | s[-3]; rr->aclass = ((uint16_t) s[-2] << 8) | s[-1]; if (is_question) return rr->nlen + 4; s += 6; if (s > e) return 0; rr->alen = ((uint16_t) s[-2] << 8) | s[-1]; if (s + rr->alen > e) return 0; return rr->nlen + rr->alen + 10; } bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) { const struct mg_dns_header *h = (struct mg_dns_header *) buf; struct mg_dns_rr rr; size_t i, n, ofs = sizeof(*h); memset(dm, 0, sizeof(*dm)); if (len < sizeof(*h)) return 0; // Too small, headers dont fit if (mg_ntohs(h->num_questions) > 1) return 0; // Sanity if (mg_ntohs(h->num_answers) > 10) return 0; // Sanity dm->txnid = mg_ntohs(h->txnid); for (i = 0; i < mg_ntohs(h->num_questions); i++) { if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false; // LOG(LL_INFO, ("Q %zu %zu", ofs, n)); ofs += n; } for (i = 0; i < mg_ntohs(h->num_answers); i++) { // LOG(LL_INFO, ("A -- %zu %zu %s", ofs, n, dm->name)); if ((n = mg_dns_parse_rr(buf, len, ofs, false, &rr)) == 0) return false; mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name)); ofs += n; if (rr.alen == 4 && rr.atype == 1 && rr.aclass == 1) { dm->addr.is_ip6 = false; memcpy(&dm->addr.ip, &buf[ofs - 4], 4); dm->resolved = true; break; // Return success } else if (rr.alen == 16 && rr.atype == 28 && rr.aclass == 1) { dm->addr.is_ip6 = true; memcpy(&dm->addr.ip6, &buf[ofs - 16], 16); dm->resolved = true; break; // Return success } } return true; } static void dns_cb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { struct dns_data *d, *tmp; if (ev == MG_EV_POLL) { unsigned long now = *(unsigned long *) ev_data; for (d = s_reqs; d != NULL; d = tmp) { tmp = d->next; // LOG(LL_DEBUG, ("%lu %lu dns poll", d->expire, now)); if (now > d->expire) mg_error(d->c, "DNS timeout"); } } else if (ev == MG_EV_READ) { struct mg_dns_message dm; int resolved = 0; if (mg_dns_parse(c->recv.buf, c->recv.len, &dm) == false) { char *s = mg_hexdump(c->recv.buf, c->recv.len); LOG(LL_ERROR, ("Unexpected DNS response:\n%s\n", s)); free(s); } else { LOG(LL_VERBOSE_DEBUG, ("%s %d", dm.name, dm.resolved)); for (d = s_reqs; d != NULL; d = tmp) { tmp = d->next; // LOG(LL_INFO, ("d %p %hu %hu", d, d->txnid, dm.txnid)); if (dm.txnid != d->txnid) continue; if (d->c->is_resolving) { d->c->is_resolving = 0; if (dm.resolved) { #if MG_ENABLE_LOG char buf[100]; #endif dm.addr.port = d->c->peer.port; // Save port d->c->peer = dm.addr; // Copy resolved address LOG(LL_DEBUG, ("%lu %s resolved to %s", d->c->id, dm.name, mg_ntoa(&d->c->peer, buf, sizeof(buf)))); mg_connect_resolved(d->c); #if MG_ENABLE_IPV6 } else if (dm.addr.is_ip6 == false && dm.name[0] != '\0') { struct mg_str x = mg_str(dm.name); mg_sendnsreq(d->c, &x, c->mgr->dnstimeout, &c->mgr->dns6, true); #endif } else { mg_error(d->c, "%s DNS lookup failed", dm.name); } } else { LOG(LL_ERROR, ("%lu already resolved", d->c->id)); } mg_dns_free(d); resolved = 1; } } if (!resolved) LOG(LL_ERROR, ("stray DNS reply")); c->recv.len = 0; } else if (ev == MG_EV_CLOSE) { for (d = s_reqs; d != NULL; d = tmp) { tmp = d->next; mg_dns_free(d); } } (void) fn_data; } void mg_dns_send(struct mg_connection *c, const struct mg_str *name, uint16_t txnid, bool ipv6) { struct { struct mg_dns_header header; uint8_t data[256]; } pkt; size_t i, n; memset(&pkt, 0, sizeof(pkt)); pkt.header.txnid = mg_htons(txnid); pkt.header.flags = mg_htons(0x100); pkt.header.num_questions = mg_htons(1); for (i = n = 0; i < sizeof(pkt.data) - 5; i++) { if (name->ptr[i] == '.' || i >= name->len) { pkt.data[n] = (uint8_t)(i - n); memcpy(&pkt.data[n + 1], name->ptr + n, i - n); n = i + 1; } if (i >= name->len) break; } memcpy(&pkt.data[n], "\x00\x00\x01\x00\x01", 5); // A query n += 5; if (ipv6) pkt.data[n - 3] = 0x1c; // AAAA query // memcpy(&pkt.data[n], "\xc0\x0c\x00\x1c\x00\x01", 6); // AAAA query // n += 6; mg_send(c, &pkt, sizeof(pkt.header) + n); #if 0 // Immediately after A query, send AAAA query. Whatever reply comes first, // we'll use it. Note: we cannot send two queries in a single packet. // https://stackoverflow.com/questions/4082081/requesting-a-and-aaaa-records-in-single-dns-query pkt.data[n - 3] = 0x1c; // AAAA query mg_send(c, &pkt, sizeof(pkt.header) + n); #endif } static void mg_sendnsreq(struct mg_connection *c, struct mg_str *name, int ms, struct mg_dns *dnsc, bool ipv6) { struct dns_data *d = NULL; if (dnsc->url == NULL) { mg_error(c, "DNS server URL is NULL. Call mg_mgr_init()"); } else if (dnsc->c == NULL) { dnsc->c = mg_connect(c->mgr, dnsc->url, NULL, NULL); if (dnsc->c != NULL) { dnsc->c->pfn = dns_cb; snprintf(dnsc->c->label, sizeof(dnsc->c->label), "%s", "DNS"); // dnsc->c->is_hexdumping = 1; } } if (dnsc->c == NULL) { mg_error(c, "resolver"); } else if ((d = (struct dns_data *) calloc(1, sizeof(*d))) == NULL) { mg_error(c, "resolve OOM"); } else { d->txnid = s_reqs ? s_reqs->txnid + 1 : 1; d->next = s_reqs; s_reqs = d; d->expire = mg_millis() + ms; d->c = c; c->is_resolving = 1; LOG(LL_VERBOSE_DEBUG, ("%lu resolving %.*s, txnid %hu", c->id, (int) name->len, name->ptr, d->txnid)); mg_dns_send(dnsc->c, name, d->txnid, ipv6); } } void mg_resolve(struct mg_connection *c, struct mg_str *name, int ms) { if (mg_aton(*name, &c->peer)) { // name is an IP address, do not fire name resolution mg_connect_resolved(c); } else { // name is not an IP, send DNS resolution request mg_sendnsreq(c, name, ms, &c->mgr->dns4, false); } } #ifdef MG_ENABLE_LINES #line 1 "src/event.c" #endif void mg_call(struct mg_connection *c, int ev, void *ev_data) { if (c->pfn != NULL) c->pfn(c, ev, ev_data, c->pfn_data); if (c->fn != NULL) c->fn(c, ev, ev_data, c->fn_data); } void mg_error(struct mg_connection *c, const char *fmt, ...) { char mem[256], *buf = mem; va_list ap; va_start(ap, fmt); mg_vasprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); LOG(LL_ERROR, ("%lu %s", c->id, buf)); mg_call(c, MG_EV_ERROR, buf); if (buf != mem) free(buf); c->is_closing = 1; } #ifdef MG_ENABLE_LINES #line 1 "src/http.c" #endif // Multipart POST example: // --xyz // Content-Disposition: form-data; name="val" // // abcdef // --xyz // Content-Disposition: form-data; name="foo"; filename="a.txt" // Content-Type: text/plain // // hello world // // --xyz-- size_t mg_http_next_multipart(struct mg_str body, size_t ofs, struct mg_http_part *part) { struct mg_str cd = mg_str_n("Content-Disposition", 19); const char *s = body.ptr; size_t b = ofs, h1, h2, b1, b2, max = body.len; // Init part params if (part != NULL) part->name = part->filename = part->body = mg_str_n(0, 0); // Skip boundary while (b + 2 < max && s[b] != '\r' && s[b + 1] != '\n') b++; if (b <= ofs || b + 2 >= max) return 0; // LOG(LL_INFO, ("B: %zu %zu [%.*s]", ofs, b - ofs, (int) (b - ofs), s)); // Skip headers h1 = h2 = b + 2; for (;;) { while (h2 + 2 < max && s[h2] != '\r' && s[h2 + 1] != '\n') h2++; if (h2 == h1) break; if (h2 + 2 >= max) return 0; // LOG(LL_INFO, ("Header: [%.*s]", (int) (h2 - h1), &s[h1])); if (part != NULL && h1 + cd.len + 2 < h2 && s[h1 + cd.len] == ':' && mg_ncasecmp(&s[h1], cd.ptr, cd.len) == 0) { struct mg_str v = mg_str_n(&s[h1 + cd.len + 2], h2 - (h1 + cd.len + 2)); part->name = mg_http_get_header_var(v, mg_str_n("name", 4)); part->filename = mg_http_get_header_var(v, mg_str_n("filename", 8)); } h1 = h2 = h2 + 2; } b1 = b2 = h2 + 2; while (b2 + 2 + (b - ofs) + 2 < max && !(s[b2] == '\r' && s[b2 + 1] == '\n' && memcmp(&s[b2 + 2], s, b - ofs) == 0)) b2++; if (b2 + 2 >= max) return 0; if (part != NULL) part->body = mg_str_n(&s[b1], b2 - b1); // LOG(LL_INFO, ("Body: [%.*s]", (int) (b2 - b1), &s[b1])); return b2 + 2; } void mg_http_bauth(struct mg_connection *c, const char *user, const char *pass) { struct mg_str u = mg_str(user), p = mg_str(pass); size_t need = c->send.len + 36 + (u.len + p.len) * 2; if (c->send.size < need) mg_iobuf_resize(&c->send, need); if (c->send.size >= need) { size_t i, n = 0; char *buf = (char *) &c->send.buf[c->send.len + 21]; memcpy(&buf[-21], "Authorization: Basic ", 21); // DON'T use mg_send! for (i = 0; i < u.len; i++) n = mg_base64_update(u.ptr[i], buf, n); if (p.len > 0) { n = mg_base64_update(':', buf, n); for (i = 0; i < p.len; i++) n = mg_base64_update(p.ptr[i], buf, n); } n = mg_base64_final(buf, n); c->send.len += 21 + n + 2; memcpy(&c->send.buf[c->send.len - 2], "\r\n", 2); } else { LOG(LL_ERROR, ("%lu %s cannot resize iobuf %d->%d ", c->id, c->label, (int) c->send.size, (int) need)); } } int mg_http_get_var(const struct mg_str *buf, const char *name, char *dst, int dst_len) { const char *p, *e, *s; size_t name_len; int len; if (dst == NULL || dst_len == 0) { len = -2; // Bad destination } else if (buf->ptr == NULL || name == NULL || buf->len == 0) { len = -1; // Bad source dst[0] = '\0'; } else { name_len = strlen(name); e = buf->ptr + buf->len; len = -4; // Name does not exist dst[0] = '\0'; for (p = buf->ptr; p + name_len < e; p++) { if ((p == buf->ptr || p[-1] == '&') && p[name_len] == '=' && !mg_ncasecmp(name, p, name_len)) { p += name_len + 1; s = (const char *) memchr(p, '&', (size_t)(e - p)); if (s == NULL) s = e; len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1); if (len < 0) len = -3; // Failed to decode break; } } } return len; } int mg_url_decode(const char *src, size_t src_len, char *dst, size_t dst_len, int is_form_url_encoded) { size_t i, j; for (i = j = 0; i < src_len && j + 1 < dst_len; i++, j++) { if (src[i] == '%') { // Use `i + 2 < src_len`, not `i < src_len - 2`, note small src_len if (i + 2 < src_len && isxdigit(*(const unsigned char *) (src + i + 1)) && isxdigit(*(const unsigned char *) (src + i + 2))) { mg_unhex(src + i + 1, 2, (uint8_t *) &dst[j]); i += 2; } else { return -1; } } else if (is_form_url_encoded && src[i] == '+') { dst[j] = ' '; } else { dst[j] = src[i]; } } if (j < dst_len) dst[j] = '\0'; // Null-terminate the destination return i >= src_len && j < dst_len ? (int) j : -1; } int mg_http_get_request_len(const unsigned char *buf, size_t buf_len) { size_t i; for (i = 0; i < buf_len; i++) { if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) return -1; if ((i > 0 && buf[i] == '\n' && buf[i - 1] == '\n') || (i > 3 && buf[i] == '\n' && buf[i - 1] == '\r' && buf[i - 2] == '\n')) return (int) i + 1; } return 0; } static const char *skip(const char *s, const char *e, const char *d, struct mg_str *v) { v->ptr = s; while (s < e && *s != '\n' && strchr(d, *s) == NULL) s++; v->len = s - v->ptr; while (s < e && strchr(d, *s) != NULL) s++; return s; } struct mg_str *mg_http_get_header(struct mg_http_message *h, const char *name) { size_t i, n = strlen(name), max = sizeof(h->headers) / sizeof(h->headers[0]); for (i = 0; i < max && h->headers[i].name.len > 0; i++) { struct mg_str *k = &h->headers[i].name, *v = &h->headers[i].value; if (n == k->len && mg_ncasecmp(k->ptr, name, n) == 0) return v; } return NULL; } void mg_http_parse_headers(const char *s, const char *end, struct mg_http_header *h, int max_headers) { int i; for (i = 0; i < max_headers; i++) { struct mg_str k, v, tmp; const char *he = skip(s, end, "\n", &tmp); s = skip(s, he, ": \r\n", &k); s = skip(s, he, "\r\n", &v); if (k.len == tmp.len) continue; while (v.len > 0 && v.ptr[v.len - 1] == ' ') v.len--; // Trim spaces if (k.len == 0) break; // LOG(LL_INFO, ("--HH [%.*s] [%.*s] [%.*s]", (int) tmp.len - 1, tmp.ptr, //(int) k.len, k.ptr, (int) v.len, v.ptr)); h[i].name = k; h[i].value = v; } } int mg_http_parse(const char *s, size_t len, struct mg_http_message *hm) { int is_response, req_len = mg_http_get_request_len((unsigned char *) s, len); const char *end = s + req_len, *qs; struct mg_str *cl; memset(hm, 0, sizeof(*hm)); if (req_len <= 0) return req_len; hm->message.ptr = hm->head.ptr = s; hm->body.ptr = end; hm->head.len = req_len; hm->chunk.ptr = end; hm->message.len = hm->body.len = (size_t) ~0; // Set body length to infinite // Parse request line s = skip(s, end, " ", &hm->method); s = skip(s, end, " ", &hm->uri); s = skip(s, end, "\r\n", &hm->proto); // Sanity check if (hm->method.len == 0 || hm->uri.len == 0 || hm->proto.len == 0) return -1; // If URI contains '?' character, setup query string if ((qs = (const char *) memchr(hm->uri.ptr, '?', hm->uri.len)) != NULL) { hm->query.ptr = qs + 1; hm->query.len = &hm->uri.ptr[hm->uri.len] - (qs + 1); hm->uri.len = qs - hm->uri.ptr; } mg_http_parse_headers(s, end, hm->headers, sizeof(hm->headers) / sizeof(hm->headers[0])); if ((cl = mg_http_get_header(hm, "Content-Length")) != NULL) { hm->body.len = (size_t) mg_to64(*cl); hm->message.len = req_len + hm->body.len; } // mg_http_parse() is used to parse both HTTP requests and HTTP // responses. If HTTP response does not have Content-Length set, then // body is read until socket is closed, i.e. body.len is infinite (~0). // // For HTTP requests though, according to // http://tools.ietf.org/html/rfc7231#section-8.1.3, // only POST and PUT methods have defined body semantics. // Therefore, if Content-Length is not specified and methods are // not one of PUT or POST, set body length to 0. // // So, if it is HTTP request, and Content-Length is not set, // and method is not (PUT or POST) then reset body length to zero. is_response = mg_ncasecmp(hm->method.ptr, "HTTP/", 5) == 0; if (hm->body.len == (size_t) ~0 && !is_response && mg_vcasecmp(&hm->method, "PUT") != 0 && mg_vcasecmp(&hm->method, "POST") != 0) { hm->body.len = 0; hm->message.len = req_len; } // The 204 (No content) responses also have 0 body length if (hm->body.len == (size_t) ~0 && is_response && mg_vcasecmp(&hm->uri, "204") == 0) { hm->body.len = 0; hm->message.len = req_len; } return req_len; } static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt, va_list ap) { char mem[256], *buf = mem; int len = mg_vasprintf(&buf, sizeof(mem), fmt, ap); mg_printf(c, "%X\r\n", len); mg_send(c, buf, len); mg_send(c, "\r\n", 2); if (buf != mem) free(buf); } void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) { va_list ap; va_start(ap, fmt); mg_http_vprintf_chunk(c, fmt, ap); va_end(ap); } void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) { mg_printf(c, "%X\r\n", len); mg_send(c, buf, len); mg_send(c, "\r\n", 2); } void mg_http_reply(struct mg_connection *c, int code, const char *headers, const char *fmt, ...) { char mem[100], *buf = mem; va_list ap; int len; va_start(ap, fmt); len = mg_vasprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); mg_printf(c, "HTTP/1.1 %d OK\r\n%sContent-Length: %d\r\n\r\n", code, headers == NULL ? "" : headers, len); mg_send(c, buf, len); if (buf != mem) free(buf); } #if MG_ENABLE_FS static void http_cb(struct mg_connection *, int, void *, void *); static void restore_http_cb(struct mg_connection *c) { if (c->pfn_data != NULL) fclose((FILE *) c->pfn_data); c->pfn_data = NULL; c->pfn = http_cb; } char *mg_http_etag(char *buf, size_t len, mg_stat_t *st) { snprintf(buf, len, "\"%lx." MG_INT64_FMT "\"", (unsigned long) st->st_mtime, (int64_t) st->st_size); return buf; } int mg_http_upload(struct mg_connection *c, struct mg_http_message *hm, const char *dir) { char offset[40] = "", name[200] = "", path[256]; mg_http_get_var(&hm->query, "offset", offset, sizeof(offset)); mg_http_get_var(&hm->query, "name", name, sizeof(name)); if (name[0] == '\0') { mg_http_reply(c, 400, "", "%s", "name required"); return -1; } else { FILE *fp; size_t oft = strtoul(offset, NULL, 0); snprintf(path, sizeof(path), "%s%c%s", dir, MG_DIRSEP, name); LOG(LL_DEBUG, ("%p %d bytes @ %d [%s]", c->fd, (int) hm->body.len, (int) oft, name)); if ((fp = mg_fopen(path, oft == 0 ? "wb" : "ab")) == NULL) { mg_http_reply(c, 400, "", "fopen(%s): %d", name, errno); return -2; } else { fwrite(hm->body.ptr, 1, hm->body.len, fp); fclose(fp); mg_http_reply(c, 200, "", ""); return hm->body.len; } } } static void static_cb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { if (ev == MG_EV_WRITE || ev == MG_EV_POLL) { FILE *fp = (FILE *) fn_data; // Read to send IO buffer directly, avoid extra on-stack buffer size_t n, max = 2 * MG_IO_SIZE; if (c->send.size < max) mg_iobuf_resize(&c->send, max); if (c->send.len >= c->send.size) return; // Rate limit n = fread(c->send.buf + c->send.len, 1, c->send.size - c->send.len, fp); if (n > 0) c->send.len += n; if (c->send.len < c->send.size) restore_http_cb(c); } else if (ev == MG_EV_CLOSE) { restore_http_cb(c); } (void) ev_data; } static const char *guess_content_type(const char *filename) { size_t n = strlen(filename); #define MIME_ENTRY(_ext, _type) \ { _ext, sizeof(_ext) - 1, _type } const struct { const char *ext; size_t ext_len; const char *type; } * t, types[] = { MIME_ENTRY("html", "text/html; charset=utf-8"), MIME_ENTRY("htm", "text/html; charset=utf-8"), MIME_ENTRY("shtml", "text/html; charset=utf-8"), MIME_ENTRY("css", "text/css"), MIME_ENTRY("js", "text/javascript"), MIME_ENTRY("mjs", "text/javascript"), MIME_ENTRY("json", "application/json"), MIME_ENTRY("ico", "image/x-icon"), MIME_ENTRY("gif", "image/gif"), MIME_ENTRY("jpg", "image/jpeg"), MIME_ENTRY("jpeg", "image/jpeg"), MIME_ENTRY("png", "image/png"), MIME_ENTRY("svg", "image/svg+xml"), MIME_ENTRY("txt", "text/plain; charset=utf-8"), MIME_ENTRY("wav", "audio/wav"), MIME_ENTRY("mp3", "audio/mpeg"), MIME_ENTRY("mid", "audio/mid"), MIME_ENTRY("ogg", "application/ogg"), MIME_ENTRY("xml", "application/xml"), MIME_ENTRY("ttf", "font/ttf"), MIME_ENTRY("json", "application/json"), MIME_ENTRY("xsl", "application/xml"), MIME_ENTRY("doc", "application/msword"), MIME_ENTRY("exe", "application/octet-stream"), MIME_ENTRY("zip", "application/zip"), MIME_ENTRY("xls", "application/excel"), MIME_ENTRY("tgz", "application/tar-gz"), MIME_ENTRY("tar", "application/tar"), MIME_ENTRY("gz", "application/gzip"), MIME_ENTRY("rar", "application/rar"), MIME_ENTRY("rtf", "application/rtf"), MIME_ENTRY("pdf", "application/pdf"), MIME_ENTRY("mpg", "video/mpeg"), MIME_ENTRY("webm", "video/webm"), MIME_ENTRY("mpeg", "video/mpeg"), MIME_ENTRY("mov", "video/quicktime"), MIME_ENTRY("mp4", "video/mp4"), MIME_ENTRY("avi", "video/x-msvideo"), MIME_ENTRY("csv", "text/csv"), MIME_ENTRY("bmp", "image/bmp"), MIME_ENTRY("bin", "application/octet-stream"), MIME_ENTRY("wasm", "application/wasm"), {NULL, 0, NULL}, }; for (t = types; t->ext != NULL; t++) { if (n < t->ext_len + 2) continue; if (mg_ncasecmp(t->ext, &filename[n - t->ext_len], t->ext_len)) continue; return t->type; } return "text/plain; charset=utf-8"; } void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm, const char *path, const char *mime, const char *hdrs) { struct mg_str *inm = mg_http_get_header(hm, "If-None-Match"); mg_stat_t st; char etag[64]; FILE *fp = mg_fopen(path, "rb"); if (fp == NULL || mg_stat(path, &st) != 0 || mg_http_etag(etag, sizeof(etag), &st) != etag) { LOG(LL_DEBUG, ("404 [%.*s] [%s] %p", (int) hm->uri.len, hm->uri.ptr, path, fp)); mg_http_reply(c, 404, "", "%s", "Not found\n"); if (fp != NULL) fclose(fp); } else if (inm != NULL && mg_vcasecmp(inm, etag) == 0) { fclose(fp); mg_printf(c, "HTTP/1.1 304 Not Modified\r\nContent-Length: 0\r\n\r\n"); } else { mg_printf(c, "HTTP/1.1 200 OK\r\nContent-Type: %s\r\n" "Etag: %s\r\nContent-Length: " MG_INT64_FMT "\r\n%s\r\n", mime, etag, (int64_t) st.st_size, hdrs ? hdrs : ""); if (mg_vcasecmp(&hm->method, "HEAD") == 0) { fclose(fp); } else { c->pfn = static_cb; c->pfn_data = fp; } } } #if MG_ARCH == MG_ARCH_ESP32 || MG_ARCH == MG_ARCH_ESP8266 || \ MG_ARCH == MG_ARCH_FREERTOS char *realpath(const char *src, char *dst) { int len = strlen(src); if (len > MG_PATH_MAX - 1) len = MG_PATH_MAX - 1; strncpy(dst, src, len); dst[len] = '\0'; LOG(LL_DEBUG, ("[%s] -> [%s]", src, dst)); return dst; } #endif // Allow user to override this function bool mg_is_dir(const char *path) WEAK; bool mg_is_dir(const char *path) { #if MG_ARCH == MG_ARCH_FREERTOS struct FF_STAT st; return (ff_stat(path, &st) == 0) && (st.st_mode & FF_IFDIR); #else mg_stat_t st; return mg_stat(path, &st) == 0 && S_ISDIR(st.st_mode); #endif } #if MG_ENABLE_DIRECTORY_LISTING #ifdef _WIN32 struct dirent { char d_name[MAX_PATH]; }; typedef struct win32_dir { HANDLE handle; WIN32_FIND_DATAW info; struct dirent result; } DIR; int gettimeofday(struct timeval *tv, void *tz) { FILETIME ft; unsigned __int64 tmpres = 0; if (tv != NULL) { GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; tmpres /= 10; // convert into microseconds tmpres -= (int64_t) 11644473600000000; tv->tv_sec = (long) (tmpres / 1000000UL); tv->tv_usec = (long) (tmpres % 1000000UL); } (void) tz; return 0; } static int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { int ret; char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p; strncpy(buf, path, sizeof(buf)); buf[sizeof(buf) - 1] = '\0'; // Trim trailing slashes. Leave backslash for paths like "X:\" p = buf + strlen(buf) - 1; while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0'; memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); // Convert back to Unicode. If doubly-converted string does not match the // original, something is fishy, reject. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), NULL, NULL); if (strcmp(buf, buf2) != 0) { wbuf[0] = L'\0'; ret = 0; } return ret; } DIR *opendir(const char *name) { DIR *d = NULL; wchar_t wpath[MAX_PATH]; DWORD attrs; if (name == NULL) { SetLastError(ERROR_BAD_ARGUMENTS); } else if ((d = (DIR *) malloc(sizeof(*d))) == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { to_wchar(name, wpath, sizeof(wpath) / sizeof(wpath[0])); attrs = GetFileAttributesW(wpath); if (attrs != 0Xffffffff && (attrs & FILE_ATTRIBUTE_DIRECTORY)) { (void) wcscat(wpath, L"\\*"); d->handle = FindFirstFileW(wpath, &d->info); d->result.d_name[0] = '\0'; } else { free(d); d = NULL; } } return d; } int closedir(DIR *d) { int result = 0; if (d != NULL) { if (d->handle != INVALID_HANDLE_VALUE) result = FindClose(d->handle) ? 0 : -1; free(d); } else { result = -1; SetLastError(ERROR_BAD_ARGUMENTS); } return result; } struct dirent *readdir(DIR *d) { struct dirent *result = NULL; if (d != NULL) { memset(&d->result, 0, sizeof(d->result)); if (d->handle != INVALID_HANDLE_VALUE) { result = &d->result; WideCharToMultiByte(CP_UTF8, 0, d->info.cFileName, -1, result->d_name, sizeof(result->d_name), NULL, NULL); if (!FindNextFileW(d->handle, &d->info)) { FindClose(d->handle); d->handle = INVALID_HANDLE_VALUE; } } else { SetLastError(ERROR_FILE_NOT_FOUND); } } else { SetLastError(ERROR_BAD_ARGUMENTS); } return result; } #endif static void printdirentry(struct mg_connection *c, const char *name, mg_stat_t *stp) { char size[64], mod[64], path[MG_PATH_MAX]; int is_dir = S_ISDIR(stp->st_mode), n = 0; const char *slash = is_dir ? "/" : ""; if (is_dir) { snprintf(size, sizeof(size), "%s", "[DIR]"); } else { if (stp->st_size < 1024) { snprintf(size, sizeof(size), "%d", (int) stp->st_size); } else if (stp->st_size < 0x100000) { snprintf(size, sizeof(size), "%.1fk", (double) stp->st_size / 1024.0); } else if (stp->st_size < 0x40000000) { snprintf(size, sizeof(size), "%.1fM", (double) stp->st_size / 1048576); } else { snprintf(size, sizeof(size), "%.1fG", (double) stp->st_size / 1073741824); } } strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime)); n = mg_url_encode(name, strlen(name), path, sizeof(path)); mg_printf(c, " <tr><td><a href=\"%.*s%s\">%s%s</a></td>" "<td>%s</td><td>%s</td></tr>\n", n, path, slash, name, slash, mod, size); } static void listdir(struct mg_connection *c, struct mg_http_message *hm, struct mg_http_serve_opts *opts, char *dir) { char path[MG_PATH_MAX], *p = &dir[strlen(dir) - 1], tmp[10]; struct dirent *dp; DIR *dirp; static const char *sort_js_code = "<script>function srt(tb, sc, so, d) {" "var tr = Array.prototype.slice.call(tb.rows, 0)," "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc]," "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), " "t1 = a.cells[2].getAttribute('name'), " "t2 = b.cells[2].getAttribute('name'); " "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : " "n1 ? parseInt(n2) - parseInt(n1) : " "c1.textContent.trim().localeCompare(c2.textContent.trim())); });"; static const char *sort_js_code2 = "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); " "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); " "};" "window.onload = function() {" "var tb = document.getElementById('tb');" "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];" "var sc = m[1], so = m[2]; document.onclick = function(ev) { " "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); " "sc = c; ev.preventDefault();}};" "srt(tb, sc, so, true);" "}" "</script>"; while (p > dir && *p != '/') *p-- = '\0'; if ((dirp = (opendir(dir))) != NULL) { size_t off, n; mg_printf(c, "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=utf-8\r\n" "%s" "Content-Length: \r\n\r\n", opts->extra_headers == NULL ? "" : opts->extra_headers); off = c->send.len; // Start of body mg_printf(c, "<!DOCTYPE html><html><head><title>Index of %.*s</title>%s%s" "<style>th,td {text-align: left; padding-right: 1em; " "font-family: monospace; }</style></head>" "<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>" "<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>" "<a href=\"#\" rel=\"1\">Modified</a></th>" "<th><a href=\"#\" rel=\"2\">Size</a></th></tr>" "<tr><td colspan=\"3\"><hr></td></tr>" "</thead>" "<tbody id=\"tb\">\n", (int) hm->uri.len, hm->uri.ptr, sort_js_code, sort_js_code2, (int) hm->uri.len, hm->uri.ptr); while ((dp = readdir(dirp)) != NULL) { mg_stat_t st; const char *sep = dp->d_name[0] == MG_DIRSEP ? "/" : ""; // Do not show current dir and hidden files if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue; // SPIFFS can report "/foo.txt" in the dp->d_name if (snprintf(path, sizeof(path), "%s%s%s", dir, sep, dp->d_name) < 0) { LOG(LL_ERROR, ("%s truncated", dp->d_name)); } else if (mg_stat(path, &st) != 0) { LOG(LL_ERROR, ("%lu stat(%s): %d", c->id, path, errno)); } else { printdirentry(c, dp->d_name, &st); } } closedir(dirp); mg_printf(c, "</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>" "</table><address>Mongoose v.%s</address></body></html>\n", MG_VERSION); n = snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off)); memcpy(c->send.buf + off - 10, tmp, n); // Set content length } else { mg_http_reply(c, 400, "", "Cannot open dir"); LOG(LL_ERROR, ("%lu opendir(%s) -> %d", c->id, dir, errno)); } } #endif void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm, struct mg_http_serve_opts *opts) { char t1[MG_PATH_MAX], t2[sizeof(t1)]; t1[0] = t2[0] = '\0'; if (realpath(opts->root_dir, t1) == NULL) { LOG(LL_ERROR, ("realpath(%s): %d", opts->root_dir, errno)); mg_http_reply(c, 400, "", "Bad web root [%s]\n", opts->root_dir); } else if (!mg_is_dir(t1)) { mg_http_reply(c, 400, "", "Invalid web root [%s]\n", t1); } else { // NOTE(lsm): Xilinx snprintf does not 0-terminate the detination for // the %.*s specifier, if the length is zero. Make sure hm->uri.len > 0 bool is_index = false; size_t n1 = strlen(t1), n2; mg_url_decode(hm->uri.ptr, hm->uri.len, t1 + n1, sizeof(t1) - n1, 0); t1[sizeof(t1) - 1] = '\0'; n2 = strlen(t1); while (n2 > 0 && t1[n2 - 1] == '/') t1[--n2] = 0; if (realpath(t1, t2) == NULL) { LOG(LL_ERROR, ("realpath(%s): %d", t1, errno)); mg_http_reply(c, 404, "", "Not found [%.*s]\n", (int) hm->uri.len, hm->uri.ptr); return; } if (mg_is_dir(t2)) { strncat(t2, "/index.html", sizeof(t2) - strlen(t2) - 1); t2[sizeof(t2) - 1] = '\0'; is_index = true; } if (strlen(t2) < n1 || memcmp(t1, t2, n1) != 0) { // Requested file is located outside root directory, fail mg_http_reply(c, 404, "", "Invalid URI [%.*s]\n", (int) hm->uri.len, hm->uri.ptr); } else { FILE *fp = mg_fopen(t2, "r"); #if MG_ENABLE_SSI if (is_index && fp == NULL) { char *p = t2 + strlen(t2); while (p > t2 && p[-1] != '/') p--; strncpy(p, "index.shtml", &t2[sizeof(t2)] - p - 2); t2[sizeof(t2) - 1] = '\0'; fp = mg_fopen(t2, "r"); } #endif if (is_index && fp == NULL) { #if MG_ENABLE_DIRECTORY_LISTING listdir(c, hm, opts, t2); #else mg_http_reply(c, 403, "", "%s", "Directory listing not supported"); #endif #if MG_ENABLE_SSI } else if (opts->ssi_pattern != NULL && mg_globmatch(opts->ssi_pattern, strlen(opts->ssi_pattern), t2, strlen(t2))) { t1[n1] = '\0'; mg_http_serve_ssi(c, t1, t2); #endif } else { mg_http_serve_file(c, hm, t2, guess_content_type(t2), opts->extra_headers); } if (fp != NULL) fclose(fp); } } } #endif static bool mg_is_url_safe(int c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~'; } int mg_url_encode(const char *s, size_t sl, char *buf, size_t len) { size_t i, n = 0; for (i = 0; i < sl; i++) { int c = *(unsigned char *) &s[i]; if (n + 4 >= len) return 0; if (mg_is_url_safe(c)) { buf[n++] = s[i]; } else { buf[n++] = '%'; mg_hex(&s[i], 1, &buf[n]); n += 2; } } return n; } void mg_http_creds(struct mg_http_message *hm, char *user, int userlen, char *pass, int passlen) { struct mg_str *v = mg_http_get_header(hm, "Authorization"); user[0] = pass[0] = '\0'; if (v != NULL && v->len > 6 && memcmp(v->ptr, "Basic ", 6) == 0) { char buf[256]; int n = mg_base64_decode(v->ptr + 6, (int) v->len - 6, buf); const char *p = (const char *) memchr(buf, ':', n); if (p != NULL) { snprintf(user, userlen, "%.*s", (int) (p - buf), buf); snprintf(pass, passlen, "%.*s", n - (int) (p - buf) - 1, p + 1); } } else if (v != NULL && v->len > 7 && memcmp(v->ptr, "Bearer ", 7) == 0) { snprintf(pass, passlen, "%.*s", (int) v->len - 7, v->ptr + 7); } else if ((v = mg_http_get_header(hm, "Cookie")) != NULL) { struct mg_str t = mg_http_get_header_var(*v, mg_str_n("access_token", 12)); if (t.len > 0) snprintf(pass, passlen, "%.*s", (int) t.len, t.ptr); } else { mg_http_get_var(&hm->query, "access_token", pass, passlen); } } static struct mg_str stripquotes(struct mg_str s) { return s.len > 1 && s.ptr[0] == '"' && s.ptr[s.len - 1] == '"' ? mg_str_n(s.ptr + 1, s.len - 2) : s; } struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v) { size_t i; for (i = 0; i + v.len + 2 < s.len; i++) { if (s.ptr[i + v.len] == '=' && memcmp(&s.ptr[i], v.ptr, v.len) == 0) { const char *p = &s.ptr[i + v.len + 1], *b = p, *x = &s.ptr[s.len]; int q = p < x && *p == '"' ? 1 : 0; while (p < x && (q ? p == b || *p != '"' : *p != ';' && *p != ' ')) p++; // LOG(LL_INFO, ("[%.*s] [%.*s] [%.*s]", (int) s.len, s.ptr, (int) v.len, // v.ptr, (int) (p - b), b)); return stripquotes(mg_str_n(b, p - b + q)); } } return mg_str_n(NULL, 0); } bool mg_http_match_uri(const struct mg_http_message *hm, const char *glob) { return mg_globmatch(glob, strlen(glob), hm->uri.ptr, hm->uri.len); } static size_t get_chunk_length(const char *buf, size_t len, size_t *ll) { size_t i = 0, n; while (i < len && buf[i] != '\r' && i != '\n') i++; n = mg_unhexn((char *) buf, i); while (i < len && (buf[i] == '\r' || i == '\n')) i++; // LOG(LL_INFO, ("len %zu i %zu n %zu ", len, i, n)); if (ll != NULL) *ll = i + 1; if (i < len && i + n + 2 < len) return i + n + 3; return 0; } // Walk through all chunks in the chunked body. For each chunk, fire // an MG_EV_HTTP_CHUNK event. static void walkchunks(struct mg_connection *c, struct mg_http_message *hm, int reqlen) { size_t off = 0, bl, ll; while (off + reqlen < c->recv.len) { char *buf = (char *) &c->recv.buf[reqlen]; size_t memo = c->recv.len; size_t cl = get_chunk_length(&buf[off], memo - reqlen - off, &ll); // LOG(LL_INFO, ("len %zu off %zu cl %zu ll %zu", len, off, cl, ll)); if (cl == 0) break; hm->chunk = mg_str_n(&buf[off + ll], cl < ll + 2 ? 0 : cl - ll - 2); mg_call(c, MG_EV_HTTP_CHUNK, hm); // Increase offset only if user has not deleted this chunk if (memo == c->recv.len) off += cl; if (cl <= 5) { // Zero chunk - last one. Prepare body - cut off chunk lengths off = bl = 0; while (off + reqlen < c->recv.len) { char *buf = (char *) &c->recv.buf[reqlen]; size_t memo = c->recv.len; size_t cl = get_chunk_length(&buf[off], memo - reqlen - off, &ll); size_t n = cl < ll + 2 ? 0 : cl - ll - 2; memmove(buf + bl, buf + off + ll, n); bl += n; off += cl; if (cl <= 5) break; } // LOG(LL_INFO, ("BL->%d del %d off %d", (int) bl, (int) del, (int) off)); c->recv.len -= off - bl; // Set message length to indicate we've received // everything, to fire MG_EV_HTTP_MSG hm->message.len = bl + reqlen; hm->body.len = bl; break; } } } static bool mg_is_chunked(struct mg_http_message *hm) { struct mg_str needle = mg_str_n("chunked", 7); struct mg_str *te = mg_http_get_header(hm, "Transfer-Encoding"); return te != NULL && mg_strstr(*te, needle) != NULL; } void mg_http_delete_chunk(struct mg_connection *c, struct mg_http_message *hm) { struct mg_str ch = hm->chunk; if (mg_is_chunked(hm)) { ch.len += 4; // \r\n before and after the chunk ch.ptr -= 2; while (ch.ptr > hm->body.ptr && *ch.ptr != '\n') ch.ptr--, ch.len++; } { const char *end = &ch.ptr[ch.len]; size_t n = end - (char *) c->recv.buf; if (c->recv.len > n) memmove((char *) ch.ptr, end, c->recv.len - n); // LOG(LL_INFO, ("DELETING CHUNK: %zu %zu %zu\n%.*s", c->recv.len, n, // ch.len, (int) ch.len, ch.ptr)); } c->recv.len -= ch.len; } static void http_cb(struct mg_connection *c, int ev, void *evd, void *fnd) { if (ev == MG_EV_READ || ev == MG_EV_CLOSE) { struct mg_http_message hm; for (;;) { int n = mg_http_parse((char *) c->recv.buf, c->recv.len, &hm); bool is_chunked = n > 0 && mg_is_chunked(&hm); if (ev == MG_EV_CLOSE) { hm.message.len = c->recv.len; hm.body.len = hm.message.len - (hm.body.ptr - hm.message.ptr); } else if (is_chunked) { walkchunks(c, &hm, n); } // LOG(LL_INFO, //("---->%d %d\n%.*s", n, is_chunked, (int) c->recv.len, c->recv.buf)); if (n < 0 && ev == MG_EV_READ) { mg_error(c, "HTTP parse:\n%.*s", (int) c->recv.len, c->recv.buf); break; } else if (n > 0 && (size_t) c->recv.len >= hm.message.len) { mg_call(c, MG_EV_HTTP_MSG, &hm); mg_iobuf_delete(&c->recv, hm.message.len); } else { if (n > 0 && !is_chunked) { hm.chunk = mg_str_n((char *) &c->recv.buf[n], c->recv.len - n); mg_call(c, MG_EV_HTTP_CHUNK, &hm); } break; } } } (void) fnd; (void) evd; } struct mg_connection *mg_http_connect(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data) { struct mg_connection *c = mg_connect(mgr, url, fn, fn_data); if (c != NULL) c->pfn = http_cb; return c; } struct mg_connection *mg_http_listen(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data) { struct mg_connection *c = mg_listen(mgr, url, fn, fn_data); if (c != NULL) c->pfn = http_cb; return c; } #ifdef MG_ENABLE_LINES #line 1 "src/iobuf.c" #endif #include <string.h> int mg_iobuf_resize(struct mg_iobuf *io, size_t new_size) { int ok = 1; if (new_size == 0) { free(io->buf); io->buf = NULL; io->len = io->size = 0; } else if (new_size != io->size) { // NOTE(lsm): do not use realloc here. Use malloc/free only, to ease the // porting to some obscure platforms like FreeRTOS void *p = malloc(new_size); if (p != NULL) { size_t len = new_size < io->len ? new_size : io->len; if (len > 0) memcpy(p, io->buf, len); free(io->buf); io->buf = (unsigned char *) p; io->size = new_size; } else { ok = 0; LOG(LL_ERROR, ("%lu->%lu", (unsigned long) io->size, (unsigned long) new_size)); } } return ok; } int mg_iobuf_init(struct mg_iobuf *io, size_t size) { return mg_iobuf_resize(io, size); } size_t mg_iobuf_append(struct mg_iobuf *io, const void *buf, size_t len, size_t chunk_size) { size_t new_size = io->len + len + chunk_size; new_size -= new_size % chunk_size; if (new_size != io->size) mg_iobuf_resize(io, new_size); if (new_size != io->size) len = 0; // Realloc failure, append nothing if (buf != NULL) memmove(io->buf + io->len, buf, len); io->len += len; return len; } size_t mg_iobuf_delete(struct mg_iobuf *io, size_t len) { if (len > io->len) len = 0; memmove(io->buf, io->buf + len, io->len - len); io->len -= len; return len; } void mg_iobuf_free(struct mg_iobuf *io) { mg_iobuf_resize(io, 0); } #ifdef MG_ENABLE_LINES #line 1 "src/log.c" #endif #if MG_ENABLE_MGOS #else #if MG_ENABLE_LOG static void mg_log_stdout(const void *buf, int len, void *userdata) { (void) userdata; fwrite(buf, 1, len, stdout); } static const char *s_spec = "2"; static void (*s_fn)(const void *, int, void *) = mg_log_stdout; static void *s_fn_param = NULL; void mg_log_set(const char *spec) { LOG(LL_DEBUG, ("Setting log level to %s", spec)); s_spec = spec; } bool mg_log_prefix(int level, const char *file, int line, const char *fname) { // static unsigned long seq; int max = LL_INFO; struct mg_str k, v, s = mg_str(s_spec); const char *p = strrchr(file, '/'); if (p == NULL) p = strrchr(file, '\\'); p = p == NULL ? file : p + 1; if (s_fn == NULL) return false; while (mg_next_comma_entry(&s, &k, &v)) { if (v.len == 0) max = atoi(k.ptr); if (v.len > 0 && strncmp(p, k.ptr, k.len) == 0) max = atoi(v.ptr); } if (level <= max) { char timebuf[21], buf[50] = ""; time_t t = time(NULL); struct tm *tm = gmtime(&t); int n, tag; strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", tm); tag = level == LL_ERROR ? 'E' : level == LL_INFO ? 'I' : ' '; n = snprintf(buf, sizeof(buf), "%s %c %s:%d:%s", timebuf, tag, p, line, fname); if (n < 0 || n > (int) sizeof(buf) - 2) n = sizeof(buf) - 2; while (n < (int) sizeof(buf) - 1) buf[n++] = ' '; s_fn(buf, sizeof(buf) - 1, s_fn_param); return true; } else { return false; } } void mg_log(const char *fmt, ...) { char mem[256], *buf = mem; va_list ap; int len = 0; va_start(ap, fmt); len = mg_vasprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); s_fn(buf, len, s_fn_param); s_fn("\n", 1, s_fn_param); if (buf != mem) free(buf); } void mg_log_set_callback(void (*fn)(const void *, int, void *), void *param) { s_fn = fn; s_fn_param = param; } #endif #endif #ifdef MG_ENABLE_LINES #line 1 "src/lwip.c" #endif #if MG_ENABLE_LWIP #include <lwip/tcp.h> #include <lwip/udp.h> static void tcp_error_cb(void *arg, err_t err) { struct mg_connection *c = (struct mg_connection *) arg; mg_error(c, "%p err %ld", c->fd, err); } static err_t connect_cb(void *arg, struct tcp_pcb *pcb, err_t err) { struct mg_connection *c = (struct mg_connection *) arg; LOG(LL_DEBUG, ("err %ld, arg %p, pcb %p", err, arg, pcb)); c->is_connecting = 0; if (err != ERR_OK) mg_error(c, "%p err %d", c->fd, err); return err; } static err_t tcp_recv_cb(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { struct mg_connection *c = (struct mg_connection *) arg; LOG(LL_DEBUG, ("err %ld, pbuf %p/%d, io.len %d, io.size %d", err, p, p == NULL ? 0 : (int) p->len, (int) c->recv.len, (int) c->recv.size)); if (err == ERR_OK && p != NULL) { #if 0 if (s->io.size < s->io.len + p->len) { char *buf = realloc(s->io.buf, s->io.len + p->len); if (buf != NULL) { s->io.buf = buf; s->io.size = s->io.len + p->len; } else { return ERR_MEM; } } // MLOG(LL_DEBUG, " --> cpy, %p %p", s->io.buf, p->payload); memcpy(s->io.buf + s->io.len, p->payload, p->len); s->io.len += p->len; #endif tcp_recved(pcb, p->len); pbuf_free(p); return err; } else { // rmsock(s); return ERR_ABRT; } } static void udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, uint16_t port) { LOG(LL_DEBUG, ("%p %p pbuf %p/%d port %hu", arg, pcb, p, p == NULL ? 0 : p->len, port)); } static err_t tcp_sent_cb(void *arg, struct tcp_pcb *pcb, uint16_t len) { LOG(LL_DEBUG, ("%p %d", pcb, (int) len)); return ERR_OK; } #if 0 static int ll_write(struct mg_connection *c, const void *buf, int len, int *fail) { int n = c->is_tls ? mg_tls_send(c, buf, len, fail) : mg_sock_send(c, buf, len, fail); LOG(*fail ? LL_ERROR : LL_VERBOSE_DEBUG, ("%p %c%c%c %d/%d %d", c->fd, c->is_tls ? 'T' : 't', c->is_udp ? 'U' : 'u', c->is_connecting ? 'C' : 'c', n, len, MG_SOCK_ERRNO)); if (n > 0 && c->is_hexdumping) mg_hexdump(c, "->", buf, n); return n; } #endif int mg_send(struct mg_connection *c, const void *buf, size_t len) { if (c->is_udp) { struct udp_pcb *pcb = (struct udp_pcb *) c->fd; struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); if (p != NULL) { // p->payload = (void *) buf; memcpy(p->payload, buf, len); err_t err = udp_send(pcb, p); pbuf_free(p); LOG(LL_DEBUG, ("%lu UDP %d bytes -> %x:%hu, err %ld", c->id, (int) len, (unsigned) *(uint32_t *) &pcb->remote_ip, pcb->remote_port, err)); if (err != ERR_OK) mg_error(c, "%p err %d", c->fd, err); } else { mg_error(c, "%p pbuf OOM", c->fd); } } else if (c->is_connecting) { mg_iobuf_append(&c->send, buf, len, MG_IO_SIZE); } else { } #if 0 int fail, n = c->is_udp ? ll_write(c, buf, (SOCKET) len, &fail) : mg_iobuf_append(&c->send, buf, len, MG_IO_SIZE); return n; #endif return 0; } static struct mg_connection *mg_mkconn(const char *url) { struct mg_connection *c = (struct mg_connection *) calloc(1, sizeof(*c)); typedef void *(*new_t)(void); int is_udp = strncmp(url, "udp:", 4) == 0; if (c == NULL) { LOG(LL_ERROR, ("%s %s", url, "OOM")); } else if ((c->fd = (is_udp ? (new_t) udp_new : (new_t) tcp_new)()) == NULL) { LOG(LL_ERROR, ("%s new", url)); free(c); c = NULL; } else { c->is_udp = is_udp; } return c; } struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data) { struct mg_connection *c = mg_mkconn(url); struct mg_str host = mg_url_host(url); if (c == NULL) return c; c->next = mgr->conns; mgr->conns = c; // mg_set_non_blocking_mode((SOCKET) c->fd); c->is_client = 1; c->peer.port = mg_htons(mg_url_port(url)); c->fn = fn; c->fn_data = fn_data; c->is_hexdumping = 1; if (c->is_udp) { udp_bind(c->fd, IP_ADDR_ANY, 0); udp_recv(c->fd, udp_recv_cb, c); } else { tcp_arg(c->fd, c); tcp_err(c->fd, tcp_error_cb); tcp_sent(c->fd, tcp_sent_cb); tcp_recv(c->fd, tcp_recv_cb); tcp_bind(c->fd, IP_ADDR_ANY, 0); tcp_nagle_disable((struct tcp_pcb *) c->fd); } LOG(LL_DEBUG, ("%lu -> %s %s", c->id, url, c->is_udp ? "UDP" : "TCP")); mg_resolve(mgr, c, &host, mgr->dnstimeout); return c; } void mg_connect_resolved(struct mg_connection *c) { char buf[40]; ip_addr_t ipaddr; memcpy(&ipaddr, &c->peer.ip, sizeof(ipaddr)); mg_call(c, MG_EV_RESOLVE, NULL); LOG(LL_DEBUG, ("%lu resolved to %s", c->id, mg_straddr(c, buf, sizeof(buf)))); err_t err = c->is_udp ? udp_connect((struct udp_pcb *) c->fd, &ipaddr, mg_ntohs(c->peer.port)) : tcp_connect((struct tcp_pcb *) c->fd, &ipaddr, mg_ntohs(c->peer.port), connect_cb); if (c->is_udp) c->is_connecting = 0; if (err != ERR_OK) mg_error(c, "%p failed, err %d", c->fd, err); } static err_t accept_cb(void *arg, struct tcp_pcb *pcb, err_t e) { LOG(LL_DEBUG, ("%p err %ld, pcb %p", arg, e, pcb)); return ERR_OK; } struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data) { struct mg_connection *c = mg_mkconn(url); struct mg_str host = mg_url_host(url); uint16_t port = mg_url_port(url); uint32_t ipaddr; err_t err; if (c == NULL) return c; mg_aton(host.ptr, &ipaddr); if (!mg_vcasecmp(&host, "localhost")) ipaddr = mg_htonl(0x7f000001); if ((err = tcp_bind(c->fd, (ip_addr_t *) &ipaddr, port)) != ERR_OK) { mg_error(c, "%p tcp_bind(%x:%hu) -> %ld", c->fd, ipaddr, port, err); } else { tcp_listen(c->fd); tcp_accept(c->fd, accept_cb); } return c; } void mg_mgr_poll(struct mg_mgr *mgr, int ms) { LOG(LL_DEBUG, ("%p %d", mgr, ms)); mg_usleep(200 * 1000); mg_timer_poll(mg_millis()); } #endif #ifdef MG_ENABLE_LINES #line 1 "src/md5.c" #endif #include <string.h> #if MG_ENABLE_MD5 #if !defined(BYTE_ORDER) && defined(__BYTE_ORDER) #define BYTE_ORDER __BYTE_ORDER #ifndef LITTLE_ENDIAN #define LITTLE_ENDIAN __LITTLE_ENDIAN #endif /* LITTLE_ENDIAN */ #ifndef BIG_ENDIAN #define BIG_ENDIAN __LITTLE_ENDIAN #endif /* BIG_ENDIAN */ #endif /* BYTE_ORDER */ static void mg_byte_reverse(unsigned char *buf, unsigned longs) { /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */ #if BYTE_ORDER == BIG_ENDIAN do { uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 | ((unsigned) buf[1] << 8 | buf[0]); *(uint32_t *) buf = t; buf += 4; } while (--longs); #else (void) buf; (void) longs; #endif } #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) #define MD5STEP(f, w, x, y, z, data, s) \ (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void mg_md5_init(mg_md5_ctx *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } static void mg_md5_transform(uint32_t buf[4], uint32_t const in[16]) { uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } void mg_md5_update(mg_md5_ctx *ctx, const unsigned char *buf, size_t len) { uint32_t t; t = ctx->bits[0]; if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; ctx->bits[1] += (uint32_t) len >> 29; t = (t >> 3) & 0x3f; if (t) { unsigned char *p = (unsigned char *) ctx->in + t; t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); mg_byte_reverse(ctx->in, 16); mg_md5_transform(ctx->buf, (uint32_t *) ctx->in); buf += t; len -= t; } while (len >= 64) { memcpy(ctx->in, buf, 64); mg_byte_reverse(ctx->in, 16); mg_md5_transform(ctx->buf, (uint32_t *) ctx->in); buf += 64; len -= 64; } memcpy(ctx->in, buf, len); } void mg_md5_final(mg_md5_ctx *ctx, unsigned char digest[16]) { unsigned count; unsigned char *p; uint32_t *a; count = (ctx->bits[0] >> 3) & 0x3F; p = ctx->in + count; *p++ = 0x80; count = 64 - 1 - count; if (count < 8) { memset(p, 0, count); mg_byte_reverse(ctx->in, 16); mg_md5_transform(ctx->buf, (uint32_t *) ctx->in); memset(ctx->in, 0, 56); } else { memset(p, 0, count - 8); } mg_byte_reverse(ctx->in, 14); a = (uint32_t *) ctx->in; a[14] = ctx->bits[0]; a[15] = ctx->bits[1]; mg_md5_transform(ctx->buf, (uint32_t *) ctx->in); mg_byte_reverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset((char *) ctx, 0, sizeof(*ctx)); } #endif #ifdef MG_ENABLE_LINES #line 1 "src/mqtt.c" #endif #define MQTT_CLEAN_SESSION 0x02 #define MQTT_HAS_WILL 0x04 #define MQTT_WILL_RETAIN 0x20 #define MQTT_HAS_PASSWORD 0x40 #define MQTT_HAS_USER_NAME 0x80 #define MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3) #define MQTT_SET_WILL_QOS(flags, qos) (flags) = ((flags) & ~0x18) | ((qos) << 3) enum { MQTT_OK, MQTT_INCOMPLETE, MQTT_MALFORMED }; void mg_mqtt_send_header(struct mg_connection *c, uint8_t cmd, uint8_t flags, uint32_t len) { uint8_t buf[1 + sizeof(len)], *vlen = &buf[1]; buf[0] = (cmd << 4) | flags; do { *vlen = len % 0x80; len /= 0x80; if (len > 0) *vlen |= 0x80; vlen++; } while (len > 0 && vlen < &buf[sizeof(buf)]); mg_send(c, buf, vlen - buf); } static void mg_send_u16(struct mg_connection *c, uint16_t value) { mg_send(c, &value, sizeof(value)); } static void mqtt_login(struct mg_connection *c, const char *url, struct mg_mqtt_opts *opts) { uint32_t total_len = 7 + 1 + 2 + 2; uint16_t flags = (opts->qos & 3) << 3; struct mg_str user = mg_url_user(url); struct mg_str pass = mg_url_pass(url); if (user.len > 0) { total_len += 2 + (uint32_t) user.len; flags |= MQTT_HAS_USER_NAME; } if (pass.len > 0) { total_len += 2 + (uint32_t) pass.len; flags |= MQTT_HAS_PASSWORD; } if (opts->will_topic.len > 0 && opts->will_message.len > 0) { total_len += 4 + (uint32_t) opts->will_topic.len + (uint32_t) opts->will_message.len; flags |= MQTT_HAS_WILL; } if (opts->clean || opts->client_id.len == 0) flags |= MQTT_CLEAN_SESSION; if (opts->will_retain) flags |= MQTT_WILL_RETAIN; total_len += (uint32_t) opts->client_id.len; mg_mqtt_send_header(c, MQTT_CMD_CONNECT, 0, total_len); mg_send(c, "\00\04MQTT\04", 7); mg_send(c, &flags, 1); // keepalive == 0 means "do not disconnect us!" mg_send_u16(c, mg_htons((uint16_t) opts->keepalive)); mg_send_u16(c, mg_htons((uint16_t) opts->client_id.len)); mg_send(c, opts->client_id.ptr, opts->client_id.len); if (flags & MQTT_HAS_WILL) { mg_send_u16(c, mg_htons((uint16_t) opts->will_topic.len)); mg_send(c, opts->will_topic.ptr, opts->will_topic.len); mg_send_u16(c, mg_htons((uint16_t) opts->will_message.len)); mg_send(c, opts->will_message.ptr, opts->will_message.len); } if (user.len > 0) { mg_send_u16(c, mg_htons((uint16_t) user.len)); mg_send(c, user.ptr, user.len); } if (pass.len > 0) { mg_send_u16(c, mg_htons((uint16_t) pass.len)); mg_send(c, pass.ptr, pass.len); } } void mg_mqtt_pub(struct mg_connection *c, struct mg_str *topic, struct mg_str *data) { uint8_t flags = MQTT_QOS(1); uint32_t total_len = 2 + (uint32_t) topic->len + (uint32_t) data->len; LOG(LL_DEBUG, ("%lu [%.*s] -> [%.*s]", c->id, (int) topic->len, (char *) topic->ptr, (int) data->len, (char *) data->ptr)); if (MQTT_GET_QOS(flags) > 0) total_len += 2; mg_mqtt_send_header(c, MQTT_CMD_PUBLISH, flags, total_len); mg_send_u16(c, mg_htons((uint16_t) topic->len)); mg_send(c, topic->ptr, topic->len); if (MQTT_GET_QOS(flags) > 0) { static uint16_t s_id; if (++s_id == 0) s_id++; mg_send_u16(c, mg_htons(s_id)); } mg_send(c, data->ptr, data->len); } void mg_mqtt_sub(struct mg_connection *c, struct mg_str *topic) { static uint16_t s_id; uint8_t qos = 1; uint32_t total_len = 2 + (uint32_t) topic->len + 2 + 1; mg_mqtt_send_header(c, MQTT_CMD_SUBSCRIBE, (uint8_t) MQTT_QOS(qos), total_len); if (++s_id == 0) ++s_id; mg_send_u16(c, mg_htons(s_id)); mg_send_u16(c, mg_htons((uint16_t) topic->len)); mg_send(c, topic->ptr, topic->len); mg_send(c, &qos, sizeof(qos)); } int mg_mqtt_parse(const uint8_t *buf, size_t len, struct mg_mqtt_message *m) { uint8_t lc = 0, *p, *end; uint32_t n = 0, len_len = 0; memset(m, 0, sizeof(*m)); m->dgram.ptr = (char *) buf; if (len < 2) return MQTT_INCOMPLETE; m->cmd = buf[0] >> 4; m->qos = (buf[0] >> 1) & 3; n = len_len = 0; p = (uint8_t *) buf + 1; while ((size_t)(p - buf) < len) { lc = *((uint8_t *) p++); n += (lc & 0x7f) << 7 * len_len; len_len++; if (!(lc & 0x80)) break; if (len_len >= 4) return MQTT_MALFORMED; } end = p + n; if (lc & 0x80 || end > buf + len) return MQTT_INCOMPLETE; m->dgram.len = end - buf; switch (m->cmd) { case MQTT_CMD_CONNACK: if (end - p < 2) return MQTT_MALFORMED; m->ack = p[1]; break; case MQTT_CMD_PUBACK: case MQTT_CMD_PUBREC: case MQTT_CMD_PUBREL: case MQTT_CMD_PUBCOMP: case MQTT_CMD_SUBACK: if (p + 2 > end) return MQTT_MALFORMED; m->id = (p[0] << 8) | p[1]; break; case MQTT_CMD_SUBSCRIBE: { if (p + 2 > end) return MQTT_MALFORMED; m->id = (p[0] << 8) | p[1]; p += 2; break; } case MQTT_CMD_PUBLISH: { if (p + 2 > end) return MQTT_MALFORMED; m->topic.len = (p[0] << 8) | p[1]; m->topic.ptr = (char *) p + 2; p += 2 + m->topic.len; if (p > end) return MQTT_MALFORMED; if (m->qos > 0) { if (p + 2 > end) return MQTT_MALFORMED; m->id = (p[0] << 8) | p[1]; p += 2; } if (p > end) return MQTT_MALFORMED; m->data.ptr = (char *) p; m->data.len = end - p; break; } default: break; } return MQTT_OK; } static int mg_mqtt_next_topic(struct mg_mqtt_message *msg, struct mg_str *topic, uint8_t *qos, int pos) { unsigned char *buf = (unsigned char *) msg->dgram.ptr + pos; int new_pos; if ((size_t) pos >= msg->dgram.len) return -1; topic->len = buf[0] << 8 | buf[1]; topic->ptr = (char *) buf + 2; new_pos = pos + 2 + topic->len + (qos == NULL ? 0 : 1); if ((size_t) new_pos > msg->dgram.len) return -1; if (qos != NULL) *qos = buf[2 + topic->len]; return new_pos; } int mg_mqtt_next_sub(struct mg_mqtt_message *msg, struct mg_str *topic, uint8_t *qos, int pos) { uint8_t tmp; return mg_mqtt_next_topic(msg, topic, qos == NULL ? &tmp : qos, pos); } int mg_mqtt_next_unsub(struct mg_mqtt_message *msg, struct mg_str *topic, int pos) { return mg_mqtt_next_topic(msg, topic, NULL, pos); } static void mqtt_cb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { if (ev == MG_EV_READ) { for (;;) { struct mg_mqtt_message mm; int rc = mg_mqtt_parse(c->recv.buf, c->recv.len, &mm); if (rc == MQTT_MALFORMED) { LOG(LL_ERROR, ("%lu MQTT malformed message", c->id)); c->is_closing = 1; break; } else if (rc == MQTT_OK) { LOG(LL_VERBOSE_DEBUG, ("%p MQTT CMD %d len %d [%.*s]", c->fd, mm.cmd, (int) mm.dgram.len, (int) mm.data.len, mm.data.ptr)); switch (mm.cmd) { case MQTT_CMD_CONNACK: mg_call(c, MG_EV_MQTT_OPEN, &mm.ack); if (mm.ack == 0) { LOG(LL_INFO, ("%lu Connected", c->id)); } else { LOG(LL_ERROR, ("%lu MQTT auth failed, code %d", c->id, mm.ack)); c->is_closing = 1; } break; case MQTT_CMD_PUBLISH: { LOG(LL_DEBUG, ("%lu [%.*s] -> [%.*s]", c->id, (int) mm.topic.len, mm.topic.ptr, (int) mm.data.len, mm.data.ptr)); mg_call(c, MG_EV_MQTT_MSG, &mm); break; } } mg_call(c, MG_EV_MQTT_CMD, &mm); mg_iobuf_delete(&c->recv, mm.dgram.len); } else { break; } } } (void) ev_data; (void) fn_data; } void mg_mqtt_ping(struct mg_connection *nc) { mg_mqtt_send_header(nc, MQTT_CMD_PINGREQ, 0, 0); } void mg_mqtt_pong(struct mg_connection *nc) { mg_mqtt_send_header(nc, MQTT_CMD_PINGRESP, 0, 0); } void mg_mqtt_disconnect(struct mg_connection *nc) { mg_mqtt_send_header(nc, MQTT_CMD_DISCONNECT, 0, 0); } struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url, struct mg_mqtt_opts *opts, mg_event_handler_t fn, void *fn_data) { struct mg_connection *c = mg_connect(mgr, url, fn, fn_data); if (c != NULL) { struct mg_mqtt_opts empty; memset(&empty, 0, sizeof(empty)); mqtt_login(c, url, opts == NULL ? &empty : opts); c->pfn = mqtt_cb; } return c; } struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data) { struct mg_connection *c = mg_listen(mgr, url, fn, fn_data); if (c != NULL) c->pfn = mqtt_cb, c->pfn_data = mgr; return c; } #ifdef MG_ENABLE_LINES #line 1 "src/net.c" #endif int mg_vprintf(struct mg_connection *c, const char *fmt, va_list ap) { char mem[256], *buf = mem; int len = mg_vasprintf(&buf, sizeof(mem), fmt, ap); len = mg_send(c, buf, len); if (buf != mem) free(buf); return len; } int mg_printf(struct mg_connection *c, const char *fmt, ...) { int len = 0; va_list ap; va_start(ap, fmt); len = mg_vprintf(c, fmt, ap); va_end(ap); return len; } char *mg_straddr(struct mg_connection *c, char *buf, size_t len) { char tmp[100]; const char *fmt = c->peer.is_ip6 ? "[%s]:%d" : "%s:%d"; mg_ntoa(&c->peer, tmp, sizeof(tmp)); snprintf(buf, len, fmt, tmp, (int) mg_ntohs(c->peer.port)); return buf; } char *mg_ntoa(const struct mg_addr *addr, char *buf, size_t len) { if (addr->is_ip6) { uint16_t *p = (uint16_t *) addr->ip6; snprintf(buf, len, "%x:%x:%x:%x:%x:%x:%x:%x", mg_htons(p[0]), mg_htons(p[1]), mg_htons(p[2]), mg_htons(p[3]), mg_htons(p[4]), mg_htons(p[5]), mg_htons(p[6]), mg_htons(p[7])); } else { uint8_t p[4]; memcpy(p, &addr->ip, sizeof(p)); snprintf(buf, len, "%d.%d.%d.%d", (int) p[0], (int) p[1], (int) p[2], (int) p[3]); } return buf; } static bool mg_atonl(struct mg_str str, struct mg_addr *addr) { if (mg_vcasecmp(&str, "localhost") != 0) return false; addr->ip = mg_htonl(0x7f000001); addr->is_ip6 = false; return true; } static bool mg_aton4(struct mg_str str, struct mg_addr *addr) { uint8_t data[4] = {0, 0, 0, 0}; size_t i, num_dots = 0; for (i = 0; i < str.len; i++) { if (str.ptr[i] >= '0' && str.ptr[i] <= '9') { int octet = data[num_dots] * 10 + (str.ptr[i] - '0'); if (octet > 255) return false; data[num_dots] = octet; } else if (str.ptr[i] == '.') { if (num_dots >= 3 || i == 0 || str.ptr[i - 1] == '.') return false; num_dots++; } else { return false; } } if (num_dots != 3 || str.ptr[i - 1] == '.') return false; memcpy(&addr->ip, data, sizeof(data)); addr->is_ip6 = false; return true; } static bool mg_aton6(struct mg_str str, struct mg_addr *addr) { size_t i, j = 0, n = 0, dc = 42; for (i = 0; i < str.len; i++) { if ((str.ptr[i] >= '0' && str.ptr[i] <= '9') || (str.ptr[i] >= 'a' && str.ptr[i] <= 'f') || (str.ptr[i] >= 'A' && str.ptr[i] <= 'F')) { unsigned long val; if (i > j + 3) return false; // LOG(LL_DEBUG, ("%zu %zu [%.*s]", i, j, (int) (i - j + 1), // &str.ptr[j])); val = mg_unhexn(&str.ptr[j], i - j + 1); addr->ip6[n] = (uint8_t)((val >> 8) & 255); addr->ip6[n + 1] = (uint8_t)(val & 255); } else if (str.ptr[i] == ':') { j = i + 1; if (i > 0 && str.ptr[i - 1] == ':') { dc = n; // Double colon if (i > 1 && str.ptr[i - 2] == ':') return false; } else if (i > 0) { n += 2; } if (n > 14) return false; addr->ip6[n] = addr->ip6[n + 1] = 0; // For trailing :: } else { return false; } } if (n < 14 && dc == 42) return false; if (n < 14) { memmove(&addr->ip6[dc + (14 - n)], &addr->ip6[dc], n - dc + 2); memset(&addr->ip6[dc], 0, 14 - n); } addr->is_ip6 = true; return true; } bool mg_aton(struct mg_str str, struct mg_addr *addr) { // LOG(LL_INFO, ("[%.*s]", (int) str.len, str.ptr)); return mg_atonl(str, addr) || mg_aton4(str, addr) || mg_aton6(str, addr); } void mg_mgr_free(struct mg_mgr *mgr) { struct mg_connection *c; for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1; mg_mgr_poll(mgr, 0); #if MG_ARCH == MG_ARCH_FREERTOS FreeRTOS_DeleteSocketSet(mgr->ss); #endif LOG(LL_INFO, ("All connections closed")); } void mg_mgr_init(struct mg_mgr *mgr) { #if defined(_WIN32) && MG_ENABLE_WINSOCK WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); #elif MG_ARCH == MG_ARCH_FREERTOS mgr->ss = FreeRTOS_CreateSocketSet(); #elif defined(__unix) || defined(__unix__) || defined(__APPLE__) // Ignore SIGPIPE signal, so if client cancels the request, it // won't kill the whole process. signal(SIGPIPE, SIG_IGN); #endif memset(mgr, 0, sizeof(*mgr)); mgr->dnstimeout = 3000; mgr->dns4.url = "udp://8.8.8.8:53"; mgr->dns6.url = "udp://[2001:4860:4860::8888]:53"; } #ifdef MG_ENABLE_LINES #line 1 "src/sha1.c" #endif /* Copyright(c) By Steve Reid <[email protected]> */ /* 100% Public Domain */ #include <string.h> /* * clang with std=-c99 uses __LITTLE_ENDIAN, by default * while for ex, RTOS gcc - LITTLE_ENDIAN, by default * it depends on __USE_BSD, but let's have everything */ #if !defined(BYTE_ORDER) && defined(__BYTE_ORDER) #define BYTE_ORDER __BYTE_ORDER #ifndef LITTLE_ENDIAN #define LITTLE_ENDIAN __LITTLE_ENDIAN #endif /* LITTLE_ENDIAN */ #ifndef BIG_ENDIAN #define BIG_ENDIAN __LITTLE_ENDIAN #endif /* BIG_ENDIAN */ #endif /* BYTE_ORDER */ union char64long16 { unsigned char c[64]; uint32_t l[16]; }; #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) static uint32_t blk0(union char64long16 *block, int i) { /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */ #if BYTE_ORDER == LITTLE_ENDIAN block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF); #endif return block->l[i]; } /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */ #undef blk #undef R0 #undef R1 #undef R2 #undef R3 #undef R4 #define blk(i) \ (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \ block->l[(i + 2) & 15] ^ block->l[i & 15], \ 1)) #define R0(v, w, x, y, z, i) \ z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \ w = rol(w, 30); #define R1(v, w, x, y, z, i) \ z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \ w = rol(w, 30); #define R2(v, w, x, y, z, i) \ z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \ w = rol(w, 30); #define R3(v, w, x, y, z, i) \ z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \ w = rol(w, 30); #define R4(v, w, x, y, z, i) \ z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \ w = rol(w, 30); void mg_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) { uint32_t a, b, c, d, e; union char64long16 block[1]; memcpy(block, buffer, 64); a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; R0(a, b, c, d, e, 0); R0(e, a, b, c, d, 1); R0(d, e, a, b, c, 2); R0(c, d, e, a, b, 3); R0(b, c, d, e, a, 4); R0(a, b, c, d, e, 5); R0(e, a, b, c, d, 6); R0(d, e, a, b, c, 7); R0(c, d, e, a, b, 8); R0(b, c, d, e, a, 9); R0(a, b, c, d, e, 10); R0(e, a, b, c, d, 11); R0(d, e, a, b, c, 12); R0(c, d, e, a, b, 13); R0(b, c, d, e, a, 14); R0(a, b, c, d, e, 15); R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19); R2(a, b, c, d, e, 20); R2(e, a, b, c, d, 21); R2(d, e, a, b, c, 22); R2(c, d, e, a, b, 23); R2(b, c, d, e, a, 24); R2(a, b, c, d, e, 25); R2(e, a, b, c, d, 26); R2(d, e, a, b, c, 27); R2(c, d, e, a, b, 28); R2(b, c, d, e, a, 29); R2(a, b, c, d, e, 30); R2(e, a, b, c, d, 31); R2(d, e, a, b, c, 32); R2(c, d, e, a, b, 33); R2(b, c, d, e, a, 34); R2(a, b, c, d, e, 35); R2(e, a, b, c, d, 36); R2(d, e, a, b, c, 37); R2(c, d, e, a, b, 38); R2(b, c, d, e, a, 39); R3(a, b, c, d, e, 40); R3(e, a, b, c, d, 41); R3(d, e, a, b, c, 42); R3(c, d, e, a, b, 43); R3(b, c, d, e, a, 44); R3(a, b, c, d, e, 45); R3(e, a, b, c, d, 46); R3(d, e, a, b, c, 47); R3(c, d, e, a, b, 48); R3(b, c, d, e, a, 49); R3(a, b, c, d, e, 50); R3(e, a, b, c, d, 51); R3(d, e, a, b, c, 52); R3(c, d, e, a, b, 53); R3(b, c, d, e, a, 54); R3(a, b, c, d, e, 55); R3(e, a, b, c, d, 56); R3(d, e, a, b, c, 57); R3(c, d, e, a, b, 58); R3(b, c, d, e, a, 59); R4(a, b, c, d, e, 60); R4(e, a, b, c, d, 61); R4(d, e, a, b, c, 62); R4(c, d, e, a, b, 63); R4(b, c, d, e, a, 64); R4(a, b, c, d, e, 65); R4(e, a, b, c, d, 66); R4(d, e, a, b, c, 67); R4(c, d, e, a, b, 68); R4(b, c, d, e, a, 69); R4(a, b, c, d, e, 70); R4(e, a, b, c, d, 71); R4(d, e, a, b, c, 72); R4(c, d, e, a, b, 73); R4(b, c, d, e, a, 74); R4(a, b, c, d, e, 75); R4(e, a, b, c, d, 76); R4(d, e, a, b, c, 77); R4(c, d, e, a, b, 78); R4(b, c, d, e, a, 79); state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Erase working structures. The order of operations is important, * used to ensure that compiler doesn't optimize those out. */ memset(block, 0, sizeof(block)); a = b = c = d = e = 0; (void) a; (void) b; (void) c; (void) d; (void) e; } void mg_sha1_init(mg_sha1_ctx *context) { context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } void mg_sha1_update(mg_sha1_ctx *context, const unsigned char *data, size_t len) { size_t i, j; j = context->count[0]; if ((context->count[0] += (uint32_t) len << 3) < j) context->count[1]++; context->count[1] += (uint32_t)(len >> 29); j = (j >> 3) & 63; if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64 - j)); mg_sha1_transform(context->state, context->buffer); for (; i + 63 < len; i += 64) { mg_sha1_transform(context->state, &data[i]); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); } void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *context) { unsigned i; unsigned char finalcount[8], c; for (i = 0; i < 8; i++) { finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); } c = 0200; mg_sha1_update(context, &c, 1); while ((context->count[0] & 504) != 448) { c = 0000; mg_sha1_update(context, &c, 1); } mg_sha1_update(context, finalcount, 8); for (i = 0; i < 20; i++) { digest[i] = (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); } memset(context, '\0', sizeof(*context)); memset(&finalcount, '\0', sizeof(finalcount)); } void mg_hmac_sha1(const unsigned char *key, size_t keylen, const unsigned char *data, size_t datalen, unsigned char out[20]) { mg_sha1_ctx ctx; unsigned char buf1[64], buf2[64], tmp_key[20], i; if (keylen > sizeof(buf1)) { mg_sha1_init(&ctx); mg_sha1_update(&ctx, key, keylen); mg_sha1_final(tmp_key, &ctx); key = tmp_key; keylen = sizeof(tmp_key); } memset(buf1, 0, sizeof(buf1)); memset(buf2, 0, sizeof(buf2)); memcpy(buf1, key, keylen); memcpy(buf2, key, keylen); for (i = 0; i < sizeof(buf1); i++) { buf1[i] ^= 0x36; buf2[i] ^= 0x5c; } mg_sha1_init(&ctx); mg_sha1_update(&ctx, buf1, sizeof(buf1)); mg_sha1_update(&ctx, data, datalen); mg_sha1_final(out, &ctx); mg_sha1_init(&ctx); mg_sha1_update(&ctx, buf2, sizeof(buf2)); mg_sha1_update(&ctx, out, 20); mg_sha1_final(out, &ctx); } #ifdef MG_ENABLE_LINES #line 1 "src/sntp.c" #endif #define SNTP_INTERVAL_SEC (3600) #define SNTP_TIME_OFFSET 2208988800 static unsigned long s_sntmp_next; int mg_sntp_parse(const unsigned char *buf, size_t len, struct timeval *tv) { int mode = len > 0 ? buf[0] & 7 : 0, res = -1; if (len < 48) { LOG(LL_ERROR, ("%s", "corrupt packet")); } else if ((buf[0] & 0x38) >> 3 != 4) { LOG(LL_ERROR, ("%s", "wrong version")); } else if (mode != 4 && mode != 5) { LOG(LL_ERROR, ("%s", "not a server reply")); } else if (buf[1] == 0) { LOG(LL_ERROR, ("%s", "server sent a kiss of death")); } else { uint32_t *data = (uint32_t *) &buf[40]; tv->tv_sec = mg_ntohl(data[0]) - SNTP_TIME_OFFSET; tv->tv_usec = mg_ntohl(data[1]); s_sntmp_next = tv->tv_sec + SNTP_INTERVAL_SEC; res = 0; } return res; } static void sntp_cb(struct mg_connection *c, int ev, void *evd, void *fnd) { if (ev == MG_EV_READ) { struct timeval tv = {0, 0}; if (mg_sntp_parse(c->recv.buf, c->recv.len, &tv) == 0) { mg_call(c, MG_EV_SNTP_TIME, &tv); LOG(LL_DEBUG, ("%u.%u, next at %lu", (unsigned) tv.tv_sec, (unsigned) tv.tv_usec, s_sntmp_next)); } c->recv.len = 0; // Clear receive buffer } else if (ev == MG_EV_RESOLVE) { mg_sntp_send(c, time(NULL)); } else if (ev == MG_EV_CLOSE) { // mg_fn_del(c, sntp_cb); } (void) fnd; (void) evd; } void mg_sntp_send(struct mg_connection *c, unsigned long utc) { if (c->is_resolving) { LOG(LL_ERROR, ("%lu wait until resolved", c->id)); } else if (utc > s_sntmp_next) { uint8_t buf[48] = {0}; s_sntmp_next = utc + SNTP_INTERVAL_SEC; buf[0] = (3 << 6) | (4 << 3) | 3; mg_send(c, buf, sizeof(buf)); LOG(LL_DEBUG, ("%p request sent, ct %lu, next at %lu", c->fd, utc, s_sntmp_next)); } } struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fnd) { struct mg_connection *c = NULL; if (url == NULL) url = "udp://time.google.com:123"; if ((c = mg_connect(mgr, url, fn, fnd)) != NULL) c->pfn = sntp_cb; return c; } #ifdef MG_ENABLE_LINES #line 1 "src/sock.c" #endif #if MG_ENABLE_SOCKET #if defined(_WIN32) && MG_ENABLE_WINSOCK #define MG_SOCK_ERRNO WSAGetLastError() #ifndef SO_EXCLUSIVEADDRUSE #define SO_EXCLUSIVEADDRUSE ((int) (~SO_REUSEADDR)) #endif #elif MG_ARCH == MG_ARCH_FREERTOS #define MG_SOCK_ERRNO errno typedef Socket_t SOCKET; #define INVALID_SOCKET FREERTOS_INVALID_SOCKET #else #define MG_SOCK_ERRNO errno #ifndef closesocket #define closesocket(x) close(x) #endif #define INVALID_SOCKET (-1) typedef int SOCKET; #endif union _su { SOCKET s; void *ptr; }; #define FD(c_) ptr2sock((c_)->fd) static SOCKET ptr2sock(void *ptr) { union _su u = {0}; u.ptr = ptr; return u.s; } static void *sock2ptr(SOCKET s) { union _su u = {s}; return u.ptr; } #ifndef MSG_NONBLOCKING #define MSG_NONBLOCKING 0 #endif union usa { struct sockaddr sa; struct sockaddr_in sin; #if MG_ENABLE_IPV6 struct sockaddr_in6 sin6; #endif }; static union usa tousa(struct mg_addr *a) { union usa usa; memset(&usa, 0, sizeof(usa)); usa.sin.sin_family = AF_INET; usa.sin.sin_port = a->port; *(uint32_t *) &usa.sin.sin_addr = a->ip; #if MG_ENABLE_IPV6 if (a->is_ip6) { usa.sin.sin_family = AF_INET6; usa.sin6.sin6_port = a->port; memcpy(&usa.sin6.sin6_addr, a->ip6, sizeof(a->ip6)); } #endif return usa; } static int mg_sock_failed(void) { int err = MG_SOCK_ERRNO; return err != EINPROGRESS && err != EWOULDBLOCK #ifndef WINCE && err != EAGAIN && err != EINTR #endif #if defined(_WIN32) && MG_ENABLE_WINSOCK && err != WSAEINTR && err != WSAEWOULDBLOCK #endif ; } static struct mg_connection *alloc_conn(struct mg_mgr *mgr, int is_client, SOCKET fd) { struct mg_connection *c = (struct mg_connection *) calloc(1, sizeof(*c)); if (c != NULL) { c->is_client = is_client; c->fd = sock2ptr(fd); c->mgr = mgr; c->id = ++mgr->nextid; } return c; } static int mg_sock_recv(struct mg_connection *c, void *buf, int len, int *fail) { int n = 0; if (c->is_udp) { union usa usa; socklen_t slen = sizeof(usa.sin); #if MG_ENABLE_IPV6 if (c->peer.is_ip6) slen = sizeof(usa.sin6); #endif n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen); if (n > 0) { if (c->peer.is_ip6) { #if MG_ENABLE_IPV6 memcpy(c->peer.ip6, &usa.sin6.sin6_addr, sizeof(c->peer.ip6)); c->peer.port = usa.sin6.sin6_port; #endif } else { c->peer.ip = *(uint32_t *) &usa.sin.sin_addr; c->peer.port = usa.sin.sin_port; } } } else { n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING); } *fail = (n == 0) || (n < 0 && mg_sock_failed()); return n; } static int mg_sock_send(struct mg_connection *c, const void *buf, int len, int *fail) { int n = 0; if (c->is_udp) { union usa usa = tousa(&c->peer); socklen_t slen = sizeof(usa.sin); #if MG_ENABLE_IPV6 if (c->peer.is_ip6) slen = sizeof(usa.sin6); #endif n = sendto(FD(c), (char *) buf, len, 0, &usa.sa, slen); } else { n = send(FD(c), (char *) buf, len, MSG_NONBLOCKING); } *fail = (n == 0) || (n < 0 && mg_sock_failed()); return n; } static int ll_read(struct mg_connection *c, void *buf, int len, int *fail) { int n = c->is_tls ? mg_tls_recv(c, buf, len, fail) : mg_sock_recv(c, buf, len, fail); LOG(*fail ? LL_DEBUG : LL_VERBOSE_DEBUG, ("%lu %c%c%c %d/%d %d %d", c->id, c->is_tls ? 'T' : 't', c->is_udp ? 'U' : 'u', c->is_connecting ? 'C' : 'c', n, len, MG_SOCK_ERRNO, *fail)); if (n > 0 && c->is_hexdumping) { char *s = mg_hexdump(buf, n); LOG(LL_INFO, ("\n-- %lu %s %s %d\n%s--", c->id, c->label, "<-", n, s)); free(s); } return n; } static int ll_write(struct mg_connection *c, const void *buf, int len, int *fail) { int n = c->is_tls ? mg_tls_send(c, buf, len, fail) : mg_sock_send(c, buf, len, fail); LOG(*fail ? LL_ERROR : LL_VERBOSE_DEBUG, ("%lu %c%c%c %d/%d %d", c->id, c->is_tls ? 'T' : 't', c->is_udp ? 'U' : 'u', c->is_connecting ? 'C' : 'c', n, len, MG_SOCK_ERRNO)); if (n > 0 && c->is_hexdumping) { char *s = mg_hexdump(buf, len); LOG(LL_INFO, ("\n-- %lu %s %s %d\n%s--", c->id, c->label, "->", len, s)); free(s); } return n; } int mg_send(struct mg_connection *c, const void *buf, size_t len) { int fail, n = c->is_udp ? ll_write(c, buf, (SOCKET) len, &fail) : (int) mg_iobuf_append(&c->send, buf, len, MG_IO_SIZE); if (len > 0 && n == 0) fail = 1; return n; } static void mg_set_non_blocking_mode(SOCKET fd) { #if defined(_WIN32) && MG_ENABLE_WINSOCK unsigned long on = 1; ioctlsocket(fd, FIONBIO, &on); #elif MG_ARCH == MG_ARCH_FREERTOS const BaseType_t off = 0; setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)); setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)); #else fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); #endif } SOCKET mg_open_listener(const char *url) { struct mg_addr addr; SOCKET fd = INVALID_SOCKET; memset(&addr, 0, sizeof(addr)); addr.port = mg_htons(mg_url_port(url)); if (!mg_aton(mg_url_host(url), &addr)) { LOG(LL_ERROR, ("invalid listening URL: %s", url)); } else { union usa usa = tousa(&addr); int on = 1, af = AF_INET; int type = strncmp(url, "udp:", 4) == 0 ? SOCK_DGRAM : SOCK_STREAM; int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP; socklen_t slen = sizeof(usa.sin); #if MG_ENABLE_IPV6 if (addr.is_ip6) af = AF_INET6, slen = sizeof(usa.sin6); #endif if ((fd = socket(af, type, proto)) != INVALID_SOCKET && #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE) // SO_RESUSEADDR is not enabled on Windows because the semantics of // SO_REUSEADDR on UNIX and Windows is different. On Windows, // SO_REUSEADDR allows to bind a socket to a port without error even if // the port is already open by another program. This is not the behavior // SO_REUSEADDR was designed for, and leads to hard-to-track failure // scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless // SO_EXCLUSIVEADDRUSE is supported and set on a socket. !setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)) && #endif #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE) // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" //! setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char *) &on, sizeof(on)) //! && !setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *) &on, sizeof(on)) && #endif bind(fd, &usa.sa, slen) == 0 && // NOTE(lsm): FreeRTOS uses backlog value as a connection limit (type == SOCK_DGRAM || listen(fd, 128) == 0)) { mg_set_non_blocking_mode(fd); } else if (fd != INVALID_SOCKET) { LOG(LL_ERROR, ("Failed to listen on %s, errno %d", url, MG_SOCK_ERRNO)); closesocket(fd); fd = INVALID_SOCKET; } } return fd; } static void read_conn(struct mg_connection *c, int (*fn)(struct mg_connection *, void *, int, int *)) { unsigned char *buf; int rc, len, fail; // NOTE(lsm): do only one iteration of reads, cause some systems // (e.g. FreeRTOS stack) return 0 instead of -1/EWOULDBLOCK when no data if (c->recv.size - c->recv.len < MG_IO_SIZE && c->recv.size < MG_MAX_RECV_BUF_SIZE && !mg_iobuf_resize(&c->recv, c->recv.size + MG_IO_SIZE)) { c->is_closing = 1; } buf = c->recv.buf + c->recv.len; len = (int) (c->recv.size - c->recv.len); rc = fn(c, buf, len, &fail); if (rc > 0) { struct mg_str evd = mg_str_n((char *) buf, rc); c->recv.len += rc; mg_call(c, MG_EV_READ, &evd); } else { if (fail) c->is_closing = 1; } } static int write_conn(struct mg_connection *c) { int fail, rc = ll_write(c, c->send.buf, (SOCKET) c->send.len, &fail); if (rc > 0) { mg_iobuf_delete(&c->send, rc); if (c->send.len == 0) mg_iobuf_resize(&c->send, 0); mg_call(c, MG_EV_WRITE, &rc); } else if (fail) { c->is_closing = 1; } return rc; } static void close_conn(struct mg_connection *c) { // Unlink this connection from the list mg_resolve_cancel(c); LIST_DELETE(struct mg_connection, &c->mgr->conns, c); if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL; if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL; mg_call(c, MG_EV_CLOSE, NULL); // while (c->callbacks != NULL) mg_fn_del(c, c->callbacks->fn); LOG(LL_DEBUG, ("%lu closed", c->id)); if (FD(c) != INVALID_SOCKET) { closesocket(FD(c)); #if MG_ARCH == MG_ARCH_FREERTOS FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL); #endif } mg_tls_free(c); free(c->recv.buf); free(c->send.buf); memset(c, 0, sizeof(*c)); free(c); } static void setsockopts(struct mg_connection *c) { #if MG_ARCH == MG_ARCH_FREERTOS FreeRTOS_FD_SET(c->fd, c->mgr->ss, eSELECT_READ | eSELECT_EXCEPT); #else int on = 1; #if !defined(SOL_TCP) #define SOL_TCP IPPROTO_TCP #endif setsockopt(FD(c), SOL_TCP, TCP_NODELAY, (char *) &on, sizeof(on)); #if defined(TCP_QUICKACK) setsockopt(FD(c), SOL_TCP, TCP_QUICKACK, (char *) &on, sizeof(on)); #endif setsockopt(FD(c), SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)); #if ESP32 || ESP8266 || defined(__linux__) int idle = 60; setsockopt(FD(c), IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)); #endif #if !defined(_WIN32) && !defined(__QNX__) { int cnt = 3, intvl = 20; setsockopt(FD(c), IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)); setsockopt(FD(c), IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)); } #endif #endif } void mg_connect_resolved(struct mg_connection *c) { char buf[40]; int type = c->is_udp ? SOCK_DGRAM : SOCK_STREAM; int af = AF_INET; #if MG_ENABLE_IPV6 if (c->peer.is_ip6) af = AF_INET6; #endif mg_straddr(c, buf, sizeof(buf)); c->fd = sock2ptr(socket(af, type, 0)); if (FD(c) == INVALID_SOCKET) { mg_error(c, "socket(): %d", MG_SOCK_ERRNO); return; } mg_set_non_blocking_mode(FD(c)); mg_call(c, MG_EV_RESOLVE, NULL); if (type == SOCK_STREAM) { union usa usa = tousa(&c->peer); socklen_t slen = #if MG_ENABLE_IPV6 c->peer.is_ip6 ? sizeof(usa.sin6) : #endif sizeof(usa.sin); int rc = connect(FD(c), &usa.sa, slen); int fail = rc < 0 && mg_sock_failed() ? MG_SOCK_ERRNO : 0; if (fail) { mg_error(c, "connect: %d", MG_SOCK_ERRNO); } else { setsockopts(c); } if (rc < 0) c->is_connecting = 1; } } struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data) { struct mg_connection *c = NULL; if ((c = alloc_conn(mgr, 1, INVALID_SOCKET)) == NULL) { LOG(LL_ERROR, ("OOM")); } else { struct mg_str host = mg_url_host(url); LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); c->is_udp = (strncmp(url, "udp:", 4) == 0); c->peer.port = mg_htons(mg_url_port(url)); c->fn = fn; c->fn_data = fn_data; LOG(LL_DEBUG, ("%lu -> %s", c->id, url)); mg_resolve(c, &host, mgr->dnstimeout); } return c; } static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) { struct mg_connection *c = NULL; union usa usa; socklen_t sa_len = sizeof(usa); SOCKET fd = accept(FD(lsn), &usa.sa, &sa_len); if (fd == INVALID_SOCKET) { LOG(LL_ERROR, ("%lu accept failed, errno %d", lsn->id, MG_SOCK_ERRNO)); #if !defined(_WIN32) } else if (fd >= FD_SETSIZE) { LOG(LL_ERROR, ("%ld > %ld", (long) fd, (long) FD_SETSIZE)); closesocket(fd); #endif } else if ((c = alloc_conn(mgr, 0, fd)) == NULL) { LOG(LL_ERROR, ("%lu OOM", lsn->id)); closesocket(fd); } else { char buf[40]; c->peer.port = usa.sin.sin_port; memcpy(&c->peer.ip, &usa.sin.sin_addr, sizeof(c->peer.ip)); #if MG_ENABLE_IPV6 if (sa_len == sizeof(usa.sin6)) { memcpy(c->peer.ip6, &usa.sin6.sin6_addr, sizeof(c->peer.ip6)); c->peer.port = usa.sin6.sin6_port; c->peer.is_ip6 = 1; } #endif mg_straddr(c, buf, sizeof(buf)); LOG(LL_DEBUG, ("%lu accepted %s", c->id, buf)); mg_set_non_blocking_mode(FD(c)); setsockopts(c); LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); c->is_accepted = 1; c->is_hexdumping = lsn->is_hexdumping; c->pfn = lsn->pfn; c->pfn_data = lsn->pfn_data; c->fn = lsn->fn; c->fn_data = lsn->fn_data; mg_call(c, MG_EV_ACCEPT, NULL); } } #if MG_ENABLE_SOCKETPAIR bool mg_socketpair(int *s1, int *s2) { #ifdef MG_ENABLE_NATIVE_SOCKETPAIR // For some reason, native socketpair() call fails on Macos // Enable this codepath only when MG_ENABLE_NATIVE_SOCKETPAIR is defined int sp[2], ret = 0; if (socketpair(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sp) == 0) { *s1 = sp[0], *s2 = sp[1], ret = 1; } LOG(LL_INFO, ("errno %d", errno)); return ret; #else union usa sa, sa2; SOCKET sp[2] = {INVALID_SOCKET, INVALID_SOCKET}; socklen_t len = sizeof(sa.sin); int ret = 0; (void) memset(&sa, 0, sizeof(sa)); sa.sin.sin_family = AF_INET; sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */ sa2 = sa; if ((sp[0] = socket(AF_INET, SOCK_DGRAM, 0)) != INVALID_SOCKET && (sp[1] = socket(AF_INET, SOCK_DGRAM, 0)) != INVALID_SOCKET && bind(sp[0], &sa.sa, len) == 0 && bind(sp[1], &sa2.sa, len) == 0 && getsockname(sp[0], &sa.sa, &len) == 0 && getsockname(sp[1], &sa2.sa, &len) == 0 && connect(sp[0], &sa2.sa, len) == 0 && connect(sp[1], &sa.sa, len) == 0) { mg_set_non_blocking_mode(sp[1]); *s1 = sp[0]; *s2 = sp[1]; ret = 1; } else { if (sp[0] != INVALID_SOCKET) closesocket(sp[0]); if (sp[1] != INVALID_SOCKET) closesocket(sp[1]); } return ret; #endif } #endif struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data) { struct mg_connection *c = NULL; int is_udp = strncmp(url, "udp:", 4) == 0; SOCKET fd = mg_open_listener(url); if (fd == INVALID_SOCKET) { } else if ((c = alloc_conn(mgr, 0, fd)) == NULL) { LOG(LL_ERROR, ("OOM %s", url)); closesocket(fd); } else { c->fd = sock2ptr(fd); c->is_listening = 1; c->is_udp = is_udp; LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c); c->fn = fn; c->fn_data = fn_data; LOG(LL_INFO, ("%lu accepting on %s", c->id, url)); } return c; } static void mg_iotest(struct mg_mgr *mgr, int ms) { #if MG_ARCH == MG_ARCH_FREERTOS struct mg_connection *c; for (c = mgr->conns; c != NULL; c = c->next) { FreeRTOS_FD_CLR(c->fd, mgr->ss, eSELECT_WRITE); if (c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0)) FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_WRITE); } FreeRTOS_select(mgr->ss, pdMS_TO_TICKS(ms)); for (c = mgr->conns; c != NULL; c = c->next) { EventBits_t bits = FreeRTOS_FD_ISSET(c->fd, mgr->ss); c->is_readable = bits & (eSELECT_READ | eSELECT_EXCEPT) ? 1 : 0; c->is_writable = bits & eSELECT_WRITE ? 1 : 0; } #else struct timeval tv = {ms / 1000, (ms % 1000) * 1000}; struct mg_connection *c; fd_set rset, wset; SOCKET maxfd = 0; int rc; FD_ZERO(&rset); FD_ZERO(&wset); for (c = mgr->conns; c != NULL; c = c->next) { // c->is_writable = 0; // TLS might have stuff buffered, so dig everything // c->is_readable = c->is_tls && c->is_readable ? 1 : 0; if (c->is_closing || c->is_resolving || FD(c) == INVALID_SOCKET) continue; FD_SET(FD(c), &rset); if (FD(c) > maxfd) maxfd = FD(c); if (c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0)) FD_SET(FD(c), &wset); } if ((rc = select(maxfd + 1, &rset, &wset, NULL, &tv)) < 0) { LOG(LL_DEBUG, ("select: %d %d", rc, MG_SOCK_ERRNO)); FD_ZERO(&rset); FD_ZERO(&wset); } for (c = mgr->conns; c != NULL; c = c->next) { // TLS might have stuff buffered, so dig everything c->is_readable = c->is_tls && c->is_readable ? 1 : FD(c) != INVALID_SOCKET && FD_ISSET(FD(c), &rset); c->is_writable = FD(c) != INVALID_SOCKET && FD_ISSET(FD(c), &wset); } #endif } static void connect_conn(struct mg_connection *c) { int rc = 0; socklen_t len = sizeof(rc); if (getsockopt(FD(c), SOL_SOCKET, SO_ERROR, (char *) &rc, &len)) rc = 1; if (rc == EAGAIN || rc == EWOULDBLOCK) rc = 0; c->is_connecting = 0; if (rc) { char buf[40]; mg_error(c, "error connecting to %s", mg_straddr(c, buf, sizeof(buf))); } else { if (c->is_tls_hs) mg_tls_handshake(c); mg_call(c, MG_EV_CONNECT, NULL); } } void mg_mgr_poll(struct mg_mgr *mgr, int ms) { struct mg_connection *c, *tmp; unsigned long now; mg_iotest(mgr, ms); now = mg_millis(); mg_timer_poll(now); for (c = mgr->conns; c != NULL; c = tmp) { tmp = c->next; mg_call(c, MG_EV_POLL, &now); LOG(LL_VERBOSE_DEBUG, ("%lu %c%c %c%c%c%c%c", c->id, c->is_readable ? 'r' : '-', c->is_writable ? 'w' : '-', c->is_tls ? 'T' : 't', c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h', c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c')); if (c->is_resolving || c->is_closing) { // Do nothing } else if (c->is_listening && c->is_udp == 0) { if (c->is_readable) accept_conn(mgr, c); } else if (c->is_connecting) { if (c->is_readable || c->is_writable) connect_conn(c); } else if (c->is_tls_hs) { if ((c->is_readable || c->is_writable)) mg_tls_handshake(c); } else { if (c->is_readable) read_conn(c, ll_read); if (c->is_writable) write_conn(c); } if (c->is_draining && c->send.len == 0) c->is_closing = 1; if (c->is_closing) close_conn(c); } } #endif #ifdef MG_ENABLE_LINES #line 1 "src/ssi.c" #endif #ifndef MG_MAX_SSI_DEPTH #define MG_MAX_SSI_DEPTH 5 #endif #if MG_ENABLE_SSI static char *mg_ssi(const char *path, const char *root, int depth) { struct mg_iobuf b = {NULL, 0, 0}; FILE *fp = mg_fopen(path, "rb"); if (fp != NULL) { char buf[BUFSIZ], arg[sizeof(buf)]; int ch, intag = 0; size_t len = 0, align = MG_IO_SIZE; while ((ch = fgetc(fp)) != EOF) { if (intag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') { buf[len++] = ch & 0xff; if (sscanf(buf, "<!--#include file=\"%[^\"]", arg)) { char tmp[MG_PATH_MAX + BUFSIZ + 10], *p = (char *) path + strlen(path), *data; while (p > path && p[-1] != MG_DIRSEP && p[-1] != '/') p--; snprintf(tmp, sizeof(tmp), "%.*s%s", (int) (p - path), path, arg); if (depth < MG_MAX_SSI_DEPTH && (data = mg_ssi(tmp, root, depth + 1)) != NULL) { mg_iobuf_append(&b, data, strlen(data), align); free(data); } else { LOG(LL_ERROR, ("%s: file=%s error or too deep", path, arg)); } } else if (sscanf(buf, "<!--#include virtual=\"%[^\"]", arg)) { char tmp[MG_PATH_MAX + BUFSIZ + 10], *data; snprintf(tmp, sizeof(tmp), "%s%s", root, arg); if (depth < MG_MAX_SSI_DEPTH && (data = mg_ssi(tmp, root, depth + 1)) != NULL) { mg_iobuf_append(&b, data, strlen(data), align); free(data); } else { LOG(LL_ERROR, ("%s: virtual=%s error or too deep", path, arg)); } } else { // Unknown SSI tag LOG(LL_INFO, ("Unknown SSI tag: %.*s", (int) len, buf)); mg_iobuf_append(&b, buf, len, align); } intag = 0; len = 0; } else if (ch == '<') { intag = 1; if (len > 0) mg_iobuf_append(&b, buf, len, align); len = 0; buf[len++] = ch & 0xff; } else if (intag) { if (len == 5 && strncmp(buf, "<!--#", 5) != 0) { intag = 0; } else if (len >= sizeof(buf) - 2) { LOG(LL_ERROR, ("%s: SSI tag is too large", path)); len = 0; } buf[len++] = ch & 0xff; } else { buf[len++] = ch & 0xff; if (len >= sizeof(buf)) { mg_iobuf_append(&b, buf, len, align); len = 0; } } } if (len > 0) mg_iobuf_append(&b, buf, len, align); if (b.len > 0) mg_iobuf_append(&b, "", 1, align); // nul-terminate fclose(fp); } (void) depth; (void) root; return (char *) b.buf; } void mg_http_serve_ssi(struct mg_connection *c, const char *root, const char *fullpath) { char *data = mg_ssi(fullpath, root, 0); mg_http_reply(c, 200, "", "%s", data == NULL ? "" : data); free(data); } #endif #ifdef MG_ENABLE_LINES #line 1 "src/str.c" #endif #include <stdlib.h> struct mg_str mg_str(const char *s) { struct mg_str str = {s, s == NULL ? 0 : strlen(s)}; return str; } struct mg_str mg_str_n(const char *s, size_t n) { struct mg_str str = {s, n}; return str; } int mg_lower(const char *s) { return tolower(*(const unsigned char *) s); } int mg_ncasecmp(const char *s1, const char *s2, size_t len) { int diff = 0; if (len > 0) do { diff = mg_lower(s1++) - mg_lower(s2++); } while (diff == 0 && s1[-1] != '\0' && --len > 0); return diff; } int mg_casecmp(const char *s1, const char *s2) { return mg_ncasecmp(s1, s2, (size_t) ~0); } int mg_vcmp(const struct mg_str *s1, const char *s2) { size_t n2 = strlen(s2), n1 = s1->len; int r = strncmp(s1->ptr, s2, (n1 < n2) ? n1 : n2); if (r == 0) return (int) (n1 - n2); return r; } int mg_vcasecmp(const struct mg_str *str1, const char *str2) { size_t n2 = strlen(str2), n1 = str1->len; int r = mg_ncasecmp(str1->ptr, str2, (n1 < n2) ? n1 : n2); if (r == 0) return (int) (n1 - n2); return r; } struct mg_str mg_strdup(const struct mg_str s) { struct mg_str r = {NULL, 0}; if (s.len > 0 && s.ptr != NULL) { char *sc = (char *) malloc(s.len + 1); if (sc != NULL) { memcpy(sc, s.ptr, s.len); sc[s.len] = '\0'; r.ptr = sc; r.len = s.len; } } return r; } int mg_strcmp(const struct mg_str str1, const struct mg_str str2) { size_t i = 0; while (i < str1.len && i < str2.len) { int c1 = str1.ptr[i]; int c2 = str2.ptr[i]; if (c1 < c2) return -1; if (c1 > c2) return 1; i++; } if (i < str1.len) return 1; if (i < str2.len) return -1; return 0; } const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle) { size_t i; if (needle.len > haystack.len) return NULL; for (i = 0; i <= haystack.len - needle.len; i++) { if (memcmp(haystack.ptr + i, needle.ptr, needle.len) == 0) { return haystack.ptr + i; } } return NULL; } struct mg_str mg_strstrip(struct mg_str s) { while (s.len > 0 && isspace((int) *s.ptr)) s.ptr++, s.len--; while (s.len > 0 && isspace((int) *(s.ptr + s.len - 1))) s.len--; return s; } #ifdef MG_ENABLE_LINES #line 1 "src/timer.c" #endif // Copyright (c) Cesanta Software Limited // All rights reserved struct mg_timer *g_timers; void mg_timer_init(struct mg_timer *t, int ms, int flags, void (*fn)(void *), void *arg) { struct mg_timer tmp = {ms, flags, fn, arg, 0UL, g_timers}; *t = tmp; g_timers = t; if (flags & MG_TIMER_RUN_NOW) fn(arg); } void mg_timer_free(struct mg_timer *t) { struct mg_timer **head = &g_timers; while (*head && *head != t) head = &(*head)->next; if (*head) *head = t->next; } void mg_timer_poll(unsigned long now_ms) { // If time goes back (wrapped around), reset timers struct mg_timer *t, *tmp; static unsigned long oldnow; // Timestamp in a previous invocation if (oldnow > now_ms) { // If it is wrapped, reset timers for (t = g_timers; t != NULL; t = t->next) t->expire = 0; } oldnow = now_ms; for (t = g_timers; t != NULL; t = tmp) { tmp = t->next; if (t->expire == 0) t->expire = now_ms + t->period_ms; if (t->expire > now_ms) continue; t->fn(t->arg); // Try to tick timers with the given period as accurate as possible, // even if this polling function is called with some random period. t->expire = now_ms - t->expire > (unsigned long) t->period_ms ? now_ms + t->period_ms : t->expire + t->period_ms; if (!(t->flags & MG_TIMER_REPEAT)) mg_timer_free(t); } } #ifdef MG_ENABLE_LINES #line 1 "src/tls.c" #endif #if MG_ENABLE_MBEDTLS ///////////////////////////////////////// MBEDTLS #include <mbedtls/debug.h> #include <mbedtls/ssl.h> #ifndef EXTERN_C #ifdef __cplusplus #define EXTERN_C extern "C" #else #define EXTERN_C #endif #endif // Different versions have those in different files, so declare here EXTERN_C int mbedtls_net_recv(void *, unsigned char *, size_t); EXTERN_C int mbedtls_net_send(void *, const unsigned char *, size_t); struct mg_tls { char *cafile; // CA certificate path mbedtls_x509_crt ca; // Parsed CA certificate mbedtls_x509_crt cert; // Parsed certificate mbedtls_ssl_context ssl; // SSL/TLS context mbedtls_ssl_config conf; // SSL-TLS config mbedtls_pk_context pk; // Private key context }; int mg_tls_handshake(struct mg_connection *c) { struct mg_tls *tls = (struct mg_tls *) c->tls; int rc; mbedtls_ssl_set_bio(&tls->ssl, &c->fd, mbedtls_net_send, mbedtls_net_recv, 0); rc = mbedtls_ssl_handshake(&tls->ssl); if (rc == 0) { // Success LOG(LL_DEBUG, ("%lu success", c->id)); c->is_tls_hs = 0; } else if (rc == MBEDTLS_ERR_SSL_WANT_READ || rc == MBEDTLS_ERR_SSL_WANT_WRITE) { // Still pending LOG(LL_VERBOSE_DEBUG, ("%lu pending, %d%d %d (-%#x)", c->id, c->is_connecting, c->is_tls_hs, rc, -rc)); } else { mg_error(c, "TLS handshake: -%#x", -rc); // Error } return rc == 0; } static int mbed_rng(void *ctx, unsigned char *buf, size_t len) { mg_random(buf, len); (void) ctx; return 0; } static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) { n = strlen(s2) - 1; LOG(LL_VERBOSE_DEBUG, ("%p %.*s", ((struct mg_connection *) c)->fd, n, s2)); (void) s; (void) c; (void) lev; } int mg_tls_init(struct mg_connection *c, struct mg_tls_opts *opts) { struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls)); int rc = 0; const char *ca = opts->ca == NULL ? "-" : opts->ca[0] == '-' ? "(emb)" : opts->ca; const char *cert = opts->cert == NULL ? "-" : opts->cert[0] == '-' ? "(emb)" : opts->cert; const char *certkey = opts->certkey == NULL ? "-" : opts->certkey[0] == '-' ? "(emb)" : opts->certkey; if (tls == NULL) { mg_error(c, "TLS OOM"); goto fail; } LOG(LL_DEBUG, ("%lu Setting TLS, CA: %s, cert: %s, key: %s", c->id, ca, cert, certkey)); mbedtls_ssl_init(&tls->ssl); mbedtls_ssl_config_init(&tls->conf); mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c); #if !defined(ESP_PLATFORM) mbedtls_debug_set_threshold(5); #endif if ((rc = mbedtls_ssl_config_defaults( &tls->conf, c->is_client ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { mg_error(c, "tls defaults %#x", -rc); goto fail; } mbedtls_ssl_conf_rng(&tls->conf, mbed_rng, c); if (opts->ca == NULL || strcmp(opts->ca, "*") == 0) { mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE); } if (opts->ca != NULL && opts->ca[0] != '\0') { #if defined(MBEDTLS_X509_CA_CHAIN_ON_DISK) tls->cafile = strdup(opts->ca); rc = mbedtls_ssl_conf_ca_chain_file(&tls->conf, tls->cafile, NULL); if (rc != 0) { mg_error(c, "parse on-disk chain(%s) err %#x", ca, -rc); goto fail; } #else mbedtls_x509_crt_init(&tls->ca); rc = opts->ca[0] == '-' ? mbedtls_x509_crt_parse(&tls->ca, (uint8_t *) opts->ca, strlen(opts->ca) + 1) : mbedtls_x509_crt_parse_file(&tls->ca, opts->ca); if (rc != 0) { mg_error(c, "parse(%s) err %#x", ca, -rc); goto fail; } mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL); #endif if (opts->srvname.len > 0) { char mem[128], *buf = mem; mg_asprintf(&buf, sizeof(mem), "%.*s", (int) opts->srvname.len, opts->srvname.ptr); mbedtls_ssl_set_hostname(&tls->ssl, buf); if (buf != mem) free(buf); } mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED); } if (opts->cert != NULL && opts->cert[0] != '\0') { const char *key = opts->certkey; if (key == NULL) { key = opts->cert; certkey = cert; } mbedtls_x509_crt_init(&tls->cert); mbedtls_pk_init(&tls->pk); rc = opts->cert[0] == '-' ? mbedtls_x509_crt_parse(&tls->cert, (uint8_t *) opts->cert, strlen(opts->cert) + 1) : mbedtls_x509_crt_parse_file(&tls->cert, opts->cert); if (rc != 0) { mg_error(c, "parse(%s) err %#x", cert, -rc); goto fail; } rc = key[0] == '-' ? mbedtls_pk_parse_key(&tls->pk, (uint8_t *) key, strlen(key) + 1, NULL, 0) : mbedtls_pk_parse_keyfile(&tls->pk, key, NULL); if (rc != 0) { mg_error(c, "tls key(%s) %#x", certkey, -rc); goto fail; } rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk); if (rc != 0) { mg_error(c, "own cert %#x", -rc); goto fail; } } if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) { mg_error(c, "setup err %#x", -rc); goto fail; } c->tls = tls; c->is_tls = 1; c->is_tls_hs = 1; if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) { mg_tls_handshake(c); } return 1; fail: c->is_closing = 1; free(tls); return 0; } int mg_tls_recv(struct mg_connection *c, void *buf, size_t len, int *fail) { struct mg_tls *tls = (struct mg_tls *) c->tls; int n = mbedtls_ssl_read(&tls->ssl, (unsigned char *) buf, len); *fail = (n == 0) || (n < 0 && n != MBEDTLS_ERR_SSL_WANT_READ); return n; } int mg_tls_send(struct mg_connection *c, const void *buf, size_t len, int *fail) { struct mg_tls *tls = (struct mg_tls *) c->tls; int n = mbedtls_ssl_write(&tls->ssl, (unsigned char *) buf, len); *fail = (n == 0) || (n < 0 && n != MBEDTLS_ERR_SSL_WANT_WRITE); return n; } int mg_tls_free(struct mg_connection *c) { struct mg_tls *tls = (struct mg_tls *) c->tls; if (tls == NULL) return 0; free(tls->cafile); mbedtls_x509_crt_free(&tls->ca); mbedtls_x509_crt_free(&tls->cert); mbedtls_ssl_free(&tls->ssl); mbedtls_pk_free(&tls->pk); mbedtls_ssl_config_free(&tls->conf); free(tls); return 1; } #elif MG_ENABLE_OPENSSL ///////////////////////////////////////// OPENSSL #include <openssl/err.h> #include <openssl/ssl.h> struct mg_tls { SSL_CTX *ctx; SSL *ssl; }; static int mg_tls_err(struct mg_tls *tls, int res) { int err = SSL_get_error(tls->ssl, res); // We've just fetched the last error from the queue. // Now we need to clear the error queue. If we do not, then the following // can happen (actually reported): // - A new connection is accept()-ed with cert error (e.g. self-signed cert) // - Since all accept()-ed connections share listener's context, // - *ALL* SSL accepted connection report read error on the next poll cycle. // Thus a single errored connection can close all the rest, unrelated ones. // Clearing the error keeps the shared SSL_CTX in an OK state. ERR_clear_error(); if (err == SSL_ERROR_WANT_READ) return 0; if (err == SSL_ERROR_WANT_WRITE) return 0; return err; } int mg_tls_init(struct mg_connection *c, struct mg_tls_opts *opts) { struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls)); const char *id = "mongoose"; static unsigned char s_initialised = 0; int rc; if (tls == NULL) { mg_error(c, "TLS OOM"); goto fail; } if (!s_initialised) { SSL_library_init(); s_initialised++; } LOG(LL_DEBUG, ("%lu Setting TLS, CA: %s, cert: %s, key: %s", c->id, opts->ca == NULL ? "null" : opts->ca, opts->cert == NULL ? "null" : opts->cert, opts->certkey == NULL ? "null" : opts->certkey)); tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method()) : SSL_CTX_new(SSLv23_server_method()); if ((tls->ssl = SSL_new(tls->ctx)) == NULL) { mg_error(c, "SSL_new"); goto fail; } SSL_set_session_id_context(tls->ssl, (const uint8_t *) id, strlen(id)); // Disable deprecated protocols SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2); SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3); SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1); #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION); #endif #ifdef MG_ENABLE_OPENSSL_CIPHER_SERVER_PREFERENCE SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE); #endif if (opts->ca != NULL && opts->ca[0] != '\0') { SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); if ((rc = SSL_CTX_load_verify_locations(tls->ctx, opts->ca, NULL)) != 1) { mg_error(c, "parse(%s): err %d", opts->ca, mg_tls_err(tls, rc)); goto fail; } } if (opts->cert != NULL && opts->cert[0] != '\0') { const char *key = opts->certkey; if (key == NULL) key = opts->cert; if ((rc = SSL_use_certificate_file(tls->ssl, opts->cert, 1)) != 1) { mg_error(c, "Invalid SSL cert, err %d", mg_tls_err(tls, rc)); goto fail; } else if ((rc = SSL_use_PrivateKey_file(tls->ssl, key, 1)) != 1) { mg_error(c, "Invalid SSL key, err %d", mg_tls_err(tls, rc)); goto fail; #if OPENSSL_VERSION_NUMBER > 0x10002000L } else if ((rc = SSL_use_certificate_chain_file(tls->ssl, opts->cert)) != 1) { mg_error(c, "Invalid CA, err %d", mg_tls_err(tls, rc)); goto fail; #endif } else { SSL_set_mode(tls->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #if OPENSSL_VERSION_NUMBER > 0x10002000L SSL_set_ecdh_auto(tls->ssl, 1); #endif } } if (opts->ciphers != NULL) SSL_set_cipher_list(tls->ssl, opts->ciphers); if (opts->srvname.len > 0) { char mem[128], *buf = mem; mg_asprintf(&buf, sizeof(mem), "%.*s", (int) opts->srvname.len, opts->srvname.ptr); SSL_set_tlsext_host_name(tls->ssl, buf); if (buf != mem) free(buf); } c->tls = tls; c->is_tls = 1; c->is_tls_hs = 1; if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) { mg_tls_handshake(c); } c->is_hexdumping = 1; LOG(LL_DEBUG, ("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client")); return 1; fail: c->is_closing = 1; free(tls); return 0; } int mg_tls_handshake(struct mg_connection *c) { struct mg_tls *tls = (struct mg_tls *) c->tls; int rc; SSL_set_fd(tls->ssl, (long) c->fd); rc = c->is_client ? SSL_connect(tls->ssl) : SSL_accept(tls->ssl); if (rc == 1) { LOG(LL_DEBUG, ("%lu success", c->id)); c->is_tls_hs = 0; return 1; } else { int code; ERR_print_errors_fp(stderr); code = mg_tls_err(tls, rc); if (code != 0) mg_error(c, "tls hs: rc %d, err %d", rc, code); return 0; } } int mg_tls_free(struct mg_connection *c) { struct mg_tls *tls = (struct mg_tls *) c->tls; if (tls == NULL) return 0; SSL_free(tls->ssl); SSL_CTX_free(tls->ctx); free(tls); return 1; } int mg_tls_recv(struct mg_connection *c, void *buf, size_t len, int *fail) { struct mg_tls *tls = (struct mg_tls *) c->tls; int n = SSL_read(tls->ssl, buf, len); *fail = (n == 0) || (n < 0 && mg_tls_err(tls, n) != 0); return n; } int mg_tls_send(struct mg_connection *c, const void *buf, size_t len, int *fail) { struct mg_tls *tls = (struct mg_tls *) c->tls; int n = SSL_write(tls->ssl, buf, len); *fail = (n == 0) || (n < 0 && mg_tls_err(tls, n) != 0); return n; } #else ////////////////////////////////////////// NO TLS int mg_tls_init(struct mg_connection *c, struct mg_tls_opts *opts) { (void) opts; mg_error(c, "TLS is not enabled"); return 0; } int mg_tls_handshake(struct mg_connection *c) { return c != NULL; } int mg_tls_free(struct mg_connection *c) { return c != NULL; } int mg_tls_recv(struct mg_connection *c, void *buf, size_t len, int *fail) { *fail = 1; return c == NULL || buf == NULL || len == 0 ? 0 : -1; } int mg_tls_send(struct mg_connection *c, const void *buf, size_t len, int *fail) { *fail = 1; return c == NULL || buf == NULL || len == 0 ? 0 : -1; } #endif #ifdef MG_ENABLE_LINES #line 1 "src/url.c" #endif #include <stdlib.h> struct url { int key, user, pass, host, port, uri, end; }; int mg_url_is_ssl(const char *url) { return strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0 || strncmp(url, "mqtts:", 6) == 0 || strncmp(url, "ssl:", 4) == 0 || strncmp(url, "tls:", 4) == 0; } static struct url urlparse(const char *url) { int i; struct url u; memset(&u, 0, sizeof(u)); for (i = 0; url[i] != '\0'; i++) { if (i > 0 && u.host == 0 && url[i - 1] == '/' && url[i] == '/') { u.host = i + 1; u.port = 0; } else if (url[i] == ']') { u.port = 0; // IPv6 URLs, like http://[::1]/bar } else if (url[i] == ':' && u.port == 0) { u.port = i + 1; } else if (url[i] == '@' && u.user == 0 && u.pass == 0) { u.user = u.host; u.pass = u.port; u.host = i + 1; u.port = 0; } else if (u.host && u.uri == 0 && url[i] == '/') { u.uri = i; } } u.end = i; #if 0 printf("[%s] %d %d %d %d %d\n", url, u.user, u.pass, u.host, u.port, u.uri); #endif return u; } struct mg_str mg_url_host(const char *url) { struct url u = urlparse(url); int n = u.port ? u.port - u.host - 1 : u.uri ? u.uri - u.host : u.end - u.host; struct mg_str s = mg_str_n(url + u.host, n); if (s.len > 2 && s.ptr[0] == '[' && s.ptr[s.len - 1] == ']') { s.len -= 2; s.ptr++; } return s; } const char *mg_url_uri(const char *url) { struct url u = urlparse(url); return u.uri ? url + u.uri : "/"; } unsigned short mg_url_port(const char *url) { struct url u = urlparse(url); unsigned short port = 0; if (memcmp(url, "http:", 5) == 0 || memcmp(url, "ws:", 3) == 0) port = 80; if (memcmp(url, "wss:", 4) == 0 || memcmp(url, "https:", 6) == 0) port = 443; if (memcmp(url, "mqtt:", 5) == 0) port = 1883; if (memcmp(url, "mqtts:", 6) == 0) port = 8883; if (u.port) port = atoi(url + u.port); return port; } struct mg_str mg_url_user(const char *url) { struct url u = urlparse(url); struct mg_str s = mg_str(""); if (u.user && (u.pass || u.host)) { int n = u.pass ? u.pass - u.user - 1 : u.host - u.user - 1; s = mg_str_n(url + u.user, n); } return s; } struct mg_str mg_url_pass(const char *url) { struct url u = urlparse(url); struct mg_str s = mg_str(""); if (u.pass && u.host) { int n = u.host - u.pass - 1; s = mg_str_n(url + u.pass, n); } return s; } #ifdef MG_ENABLE_LINES #line 1 "src/util.c" #endif #if MG_ENABLE_FS int mg_stat(const char *path, mg_stat_t *st) { #ifdef _WIN32 wchar_t tmp[MG_PATH_MAX]; MultiByteToWideChar(CP_UTF8, 0, path, -1, tmp, sizeof(tmp) / sizeof(tmp[0])); return _wstati64(tmp, st); #else return stat(path, st); #endif } FILE *mg_fopen(const char *path, const char *mode) { #ifdef _WIN32 wchar_t b1[MG_PATH_MAX], b2[10]; MultiByteToWideChar(CP_UTF8, 0, path, -1, b1, sizeof(b1) / sizeof(b1[0])); MultiByteToWideChar(CP_UTF8, 0, mode, -1, b2, sizeof(b2) / sizeof(b2[0])); return _wfopen(b1, b2); #else return fopen(path, mode); #endif } int64_t mg_file_size(const char *path) { #if MG_ARCH == MG_ARCH_FREERTOS struct FF_STAT st; return ff_stat(path, &st) == 0 ? st.st_size : 0; #else mg_stat_t st; return mg_stat(path, &st) == 0 ? st.st_size : 0; #endif } char *mg_file_read(const char *path, size_t *sizep) { FILE *fp; char *data = NULL; size_t size = (size_t) mg_file_size(path); if ((fp = mg_fopen(path, "rb")) != NULL) { data = (char *) malloc(size + 1); if (data != NULL) { if (fread(data, 1, size, fp) != size) { free(data); data = NULL; } else { data[size] = '\0'; if (sizep != NULL) *sizep = size; } } fclose(fp); } return data; } bool mg_file_write(const char *path, const void *buf, size_t len) { bool result = false; FILE *fp; char tmp[MG_PATH_MAX]; snprintf(tmp, sizeof(tmp), "%s.%d", path, rand()); fp = mg_fopen(tmp, "wb"); if (fp != NULL) { result = fwrite(buf, 1, len, fp) == len; fclose(fp); if (result) { remove(path); rename(tmp, path); } else { remove(tmp); } } return result; } bool mg_file_printf(const char *path, const char *fmt, ...) { char tmp[256], *buf = tmp; bool result; size_t len; va_list ap; va_start(ap, fmt); len = mg_vasprintf(&buf, sizeof(tmp), fmt, ap); va_end(ap); result = mg_file_write(path, buf, len); if (buf != tmp) free(buf); return result; } #endif void mg_random(void *buf, size_t len) { bool done = false; #if MG_ENABLE_FS FILE *fp = mg_fopen("/dev/urandom", "rb"); if (fp != NULL) { if (fread(buf, 1, len, fp) == len) done = true; fclose(fp); } #endif if (!done) { // Fallback to a pseudo random gen size_t i; for (i = 0; i < len; i++) ((unsigned char *) buf)[i] = rand() % 0xff; } } bool mg_globmatch(const char *s1, int n1, const char *s2, int n2) { int i = 0, j = 0, ni = 0, nj = 0; while (i < n1 || j < n2) { if (i < n1 && j < n2 && (s1[i] == '?' || s2[j] == s1[i])) { i++, j++; } else if (i < n1 && (s1[i] == '*' || s1[i] == '#')) { ni = i, nj = j + 1, i++; } else if (nj > 0 && nj <= n2 && (s1[i - 1] == '#' || s2[j] != '/')) { i = ni, j = nj; } else { return false; } } return true; } static int mg_nextcommaentry(const char *s, int slen, int ofs, int *koff, int *klen, int *voff, int *vlen) { int kvlen, kl; for (kvlen = 0; ofs + kvlen < slen && s[ofs + kvlen] != ',';) kvlen++; for (kl = 0; kl < kvlen && s[ofs + kl] != '=';) kl++; if (koff != NULL) *koff = ofs; if (klen != NULL) *klen = kl; if (voff != NULL) *voff = kl < kvlen ? ofs + kl + 1 : 0; if (vlen != NULL) *vlen = kl < kvlen ? kvlen - kl - 1 : 0; return ofs >= slen ? slen : ofs + kvlen + 1; } bool mg_next_comma_entry(struct mg_str *s, struct mg_str *k, struct mg_str *v) { int koff, klen, voff, vlen; int off = mg_nextcommaentry(s->ptr, s->len, 0, &koff, &klen, &voff, &vlen); if (k != NULL) *k = mg_str_n(s->ptr + koff, klen); if (v != NULL) *v = mg_str_n(s->ptr + voff, vlen); *s = mg_str_n(s->ptr + off, s->len - off); return off > 0; } uint32_t mg_ntohl(uint32_t net) { uint8_t data[4] = {0, 0, 0, 0}; memcpy(&data, &net, sizeof(data)); return ((uint32_t) data[3] << 0) | ((uint32_t) data[2] << 8) | ((uint32_t) data[1] << 16) | ((uint32_t) data[0] << 24); } uint16_t mg_ntohs(uint16_t net) { uint8_t data[2] = {0, 0}; memcpy(&data, &net, sizeof(data)); return ((uint16_t) data[1] << 0) | ((uint32_t) data[0] << 8); } char *mg_hexdump(const void *buf, size_t len) { const unsigned char *p = (const unsigned char *) buf; size_t i, idx, n = 0, ofs = 0, dlen = len * 5 + 100; char ascii[17] = "", *dst = (char *) malloc(dlen); if (dst == NULL) return dst; for (i = 0; i < len; i++) { idx = i % 16; if (idx == 0) { if (i > 0 && dlen > n) n += snprintf(dst + n, dlen - n, " %s\n", ascii); if (dlen > n) n += snprintf(dst + n, dlen - n, "%04x ", (int) (i + ofs)); } if (dlen < n) break; n += snprintf(dst + n, dlen - n, " %02x", p[i]); ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i]; ascii[idx + 1] = '\0'; } while (i++ % 16) { if (n < dlen) n += snprintf(dst + n, dlen - n, "%s", " "); } if (n < dlen) n += snprintf(dst + n, dlen - n, " %s\n", ascii); if (n > dlen - 1) n = dlen - 1; dst[n] = '\0'; return dst; } char *mg_hex(const void *buf, int len, char *to) { const unsigned char *p = (const unsigned char *) buf; static const char *hex = "0123456789abcdef"; int i = 0; for (; len--; p++) { to[i++] = hex[p[0] >> 4]; to[i++] = hex[p[0] & 0x0f]; } to[i] = '\0'; return to; } unsigned long mg_unhexn(const char *s, int len) { unsigned long i = 0, v = 0; for (i = 0; i < (unsigned long) len; i++) { int c = s[i]; if (i > 0) v <<= 4; v |= (c >= '0' && c <= '9') ? c - '0' : (c >= 'A' && c <= 'F') ? c - '7' : c - 'W'; } return v; } void mg_unhex(const char *buf, int len, unsigned char *to) { int i; for (i = 0; i < len; i += 2) { to[i >> 1] = (unsigned char) mg_unhexn(&buf[i], 2); } } int mg_vasprintf(char **buf, size_t size, const char *fmt, va_list ap) { va_list ap_copy; int len; va_copy(ap_copy, ap); len = vsnprintf(*buf, size, fmt, ap_copy); va_end(ap_copy); if (len < 0) { // eCos and Windows are not standard-compliant and return -1 when // the buffer is too small. Keep allocating larger buffers until we // succeed or out of memory. // LCOV_EXCL_START *buf = NULL; while (len < 0) { free(*buf); if (size == 0) size = 5; size *= 2; if ((*buf = (char *) malloc(size)) == NULL) { len = -1; break; } va_copy(ap_copy, ap); len = vsnprintf(*buf, size - 1, fmt, ap_copy); va_end(ap_copy); } // Microsoft version of vsnprintf() is not always null-terminated, so put // the terminator manually if (*buf != NULL) (*buf)[len] = 0; // LCOV_EXCL_STOP } else if (len >= (int) size) { /// Standard-compliant code path. Allocate a buffer that is large enough if ((*buf = (char *) malloc(len + 1)) == NULL) { len = -1; // LCOV_EXCL_LINE } else { // LCOV_EXCL_LINE va_copy(ap_copy, ap); len = vsnprintf(*buf, len + 1, fmt, ap_copy); va_end(ap_copy); } } return len; } int mg_asprintf(char **buf, size_t size, const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = mg_vasprintf(buf, size, fmt, ap); va_end(ap); return ret; } int64_t mg_to64(struct mg_str str) { int64_t result = 0, neg = 1, max = 922337203685477570 /* INT64_MAX/10-10 */; size_t i = 0; while (i < str.len && (str.ptr[i] == ' ' || str.ptr[i] == '\t')) i++; if (i < str.len && str.ptr[i] == '-') neg = -1, i++; while (i < str.len && str.ptr[i] >= '0' && str.ptr[i] <= '9') { if (result > max) return 0; result *= 10; result += (str.ptr[i] - '0'); i++; } return result * neg; } uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len) { int i; crc = ~crc; while (len--) { crc ^= *(unsigned char *) buf++; for (i = 0; i < 8; i++) crc = crc & 1 ? (crc >> 1) ^ 0xedb88320 : crc >> 1; } return ~crc; } double mg_time(void) { #if MG_ARCH == MG_ARCH_WIN32 SYSTEMTIME sysnow; FILETIME ftime; GetLocalTime(&sysnow); SystemTimeToFileTime(&sysnow, &ftime); /* * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64 * This should not cause a problems in this (21th) century * 2. Windows FILETIME is a number of 100-nanosecond intervals since January * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC, * thus, we need to convert to seconds and adjust amount (subtract 11644473600 * seconds) */ return (double) (((int64_t) ftime.dwLowDateTime + ((int64_t) ftime.dwHighDateTime << 32)) / 10000000.0) - 11644473600; #else struct timeval tv; if (gettimeofday(&tv, NULL /* tz */) != 0) return 0; return (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0); #endif /* _WIN32 */ } void mg_usleep(unsigned long usecs) { #if MG_ARCH == MG_ARCH_WIN32 Sleep(usecs / 1000); #elif MG_ARCH == MG_ARCH_ESP8266 ets_delay_us(usecs); #else usleep(usecs); #endif } unsigned long mg_millis(void) { #if MG_ARCH == MG_ARCH_WIN32 return GetTickCount(); #elif MG_ARCH == MG_ARCH_ESP32 return esp_timer_get_time() / 1000; #elif MG_ARCH == MG_ARCH_ESP8266 // return system_get_time() / 1000; return xTaskGetTickCount() * portTICK_PERIOD_MS; #elif MG_ARCH == MG_ARCH_FREERTOS return xTaskGetTickCount() * portTICK_PERIOD_MS; #else struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return (unsigned long) ((uint64_t) ts.tv_sec * 1000 + ts.tv_nsec / 1000000); #endif } #ifdef MG_ENABLE_LINES #line 1 "src/ws.c" #endif struct ws_msg { uint8_t flags; size_t header_len; size_t data_len; }; static void ws_handshake(struct mg_connection *c, const char *key, size_t key_len, const char *fmt, va_list ap) { const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; unsigned char sha[20], b64_sha[30]; char mem[128], *buf = mem; mg_sha1_ctx sha_ctx; mg_sha1_init(&sha_ctx); mg_sha1_update(&sha_ctx, (unsigned char *) key, key_len); mg_sha1_update(&sha_ctx, (unsigned char *) magic, 36); mg_sha1_final(sha, &sha_ctx); mg_base64_encode(sha, sizeof(sha), (char *) b64_sha); buf[0] = '\0'; if (fmt != NULL) mg_vasprintf(&buf, sizeof(mem), fmt, ap); mg_printf(c, "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %s\r\n" "%s\r\n", b64_sha, buf); if (buf != mem) free(buf); } static size_t ws_process(uint8_t *buf, size_t len, struct ws_msg *msg) { size_t i, n = 0, mask_len = 0; memset(msg, 0, sizeof(*msg)); if (len >= 2) { n = buf[1] & 0x7f; mask_len = buf[1] & WEBSOCKET_FLAGS_MASK_FIN ? 4 : 0; msg->flags = *(unsigned char *) buf; if (n < 126 && len >= mask_len) { msg->data_len = n; msg->header_len = 2 + mask_len; } else if (n == 126 && len >= 4 + mask_len) { msg->header_len = 4 + mask_len; msg->data_len = mg_ntohs(*(uint16_t *) &buf[2]); } else if (len >= 10 + mask_len) { msg->header_len = 10 + mask_len; msg->data_len = (int) (((uint64_t) mg_ntohl(*(uint32_t *) &buf[2])) << 32) + mg_ntohl(*(uint32_t *) &buf[6]); } } if (msg->header_len + msg->data_len > len) return 0; if (mask_len > 0) { uint8_t *p = buf + msg->header_len, *m = p - mask_len; for (i = 0; i < msg->data_len; i++) p[i] ^= m[i & 3]; } return msg->header_len + msg->data_len; } size_t mg_ws_send(struct mg_connection *c, const char *buf, size_t len, int op) { unsigned char header[10], mask[4]; size_t i, header_len = 0; header[0] = (uint8_t)(op | WEBSOCKET_FLAGS_MASK_FIN); if (len < 126) { header[1] = (unsigned char) len; header_len = 2; } else if (len < 65536) { uint16_t tmp = mg_htons((uint16_t) len); header[1] = 126; memcpy(&header[2], &tmp, sizeof(tmp)); header_len = 4; } else { uint32_t tmp; header[1] = 127; tmp = mg_htonl((uint32_t)((uint64_t) len >> 32)); memcpy(&header[2], &tmp, sizeof(tmp)); tmp = mg_htonl((uint32_t)(len & 0xffffffff)); memcpy(&header[6], &tmp, sizeof(tmp)); header_len = 10; } if (c->is_client) header[1] |= 1 << 7; // Set masking flag mg_send(c, header, header_len); if (c->is_client) { mg_random(mask, sizeof(mask)); mg_send(c, mask, sizeof(mask)); header_len += sizeof(mask); } LOG(LL_VERBOSE_DEBUG, ("WS out: %d [%.*s]", (int) len, (int) len, buf)); mg_send(c, buf, len); if (c->is_client && c->send.buf != NULL) { uint8_t *p = c->send.buf + c->send.len - len; for (i = 0; i < len; i++) p[i] ^= mask[i & 3]; } return header_len + len; } static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) { struct ws_msg msg; if (ev == MG_EV_READ) { if (!c->is_websocket && c->is_client) { int n = mg_http_get_request_len(c->recv.buf, c->recv.len); if (n < 0) { c->is_closing = 1; // Some just, not an HTTP request } else if (n > 0) { if (n < 15 || memcmp(c->recv.buf + 9, "101", 3) != 0) { LOG(LL_ERROR, ("%lu WS handshake error: %.*s", c->id, 15, c->recv.buf)); c->is_closing = 1; } else { struct mg_http_message hm; mg_http_parse((char *) c->recv.buf, c->recv.len, &hm); c->is_websocket = 1; mg_call(c, MG_EV_WS_OPEN, &hm); } mg_iobuf_delete(&c->recv, n); } else { return; // A request is not yet received } } while (ws_process(c->recv.buf, c->recv.len, &msg) > 0) { char *s = (char *) c->recv.buf + msg.header_len; struct mg_ws_message m = {{s, msg.data_len}, msg.flags}; switch (msg.flags & WEBSOCKET_FLAGS_MASK_OP) { case WEBSOCKET_OP_PING: LOG(LL_DEBUG, ("%s", "WS PONG")); mg_ws_send(c, s, msg.data_len, WEBSOCKET_OP_PONG); mg_call(c, MG_EV_WS_CTL, &m); break; case WEBSOCKET_OP_PONG: mg_call(c, MG_EV_WS_CTL, &m); break; case WEBSOCKET_OP_CLOSE: LOG(LL_ERROR, ("%lu Got WS CLOSE", c->id)); mg_call(c, MG_EV_WS_CTL, &m); c->is_closing = 1; return; default: { mg_call(c, MG_EV_WS_MSG, &m); break; } } mg_iobuf_delete(&c->recv, msg.header_len + msg.data_len); } } (void) fn_data; (void) ev_data; } struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data, const char *fmt, ...) { struct mg_connection *c = mg_connect(mgr, url, fn, fn_data); if (c != NULL) { char nonce[16], key[30], mem1[128], mem2[256], *buf1 = mem1, *buf2 = mem2; struct mg_str host = mg_url_host(url); int n1 = 0, n2 = 0; if (fmt != NULL) { va_list ap; va_start(ap, fmt); n1 = mg_vasprintf(&buf1, sizeof(mem1), fmt, ap); va_end(ap); } // Send handshake request // mg_url_host(url, host, sizeof(host)); mg_random(nonce, sizeof(nonce)); mg_base64_encode((unsigned char *) nonce, sizeof(nonce), key); // LOG(LL_DEBUG, "%p [%s]", uri, uri == NULL ? "???" : uri); n2 = mg_asprintf(&buf2, sizeof(mem2), "GET %s HTTP/1.1\r\n" "Upgrade: websocket\r\n" "Host: %.*s\r\n" "Connection: Upgrade\r\n" "%.*s" "Sec-WebSocket-Version: 13\r\n" "Sec-WebSocket-Key: %s\r\n" "\r\n", mg_url_uri(url), (int) host.len, host.ptr, n1, buf1, key); mg_send(c, buf2, n2); if (buf1 != mem1) free(buf1); if (buf2 != mem2) free(buf2); c->pfn = mg_ws_cb; c->fn_data = fn_data; } return c; } void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm, const char *fmt, ...) { struct mg_str *wskey = mg_http_get_header(hm, "Sec-WebSocket-Key"); c->pfn = mg_ws_cb; if (wskey != NULL) { va_list ap; va_start(ap, fmt); ws_handshake(c, wskey->ptr, wskey->len, fmt, ap); va_end(ap); } c->is_websocket = 1; }
255624.c
/**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2013 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /**********************************************************************/ #include "iki.h" #include <string.h> #include <math.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif /**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2013 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /**********************************************************************/ #include "iki.h" #include <string.h> #include <math.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif typedef void (*funcp)(char *, char *); extern void execute_12(char*, char *); extern void execute_13(char*, char *); extern void vhdl_transfunc_eventcallback(char*, char*, unsigned, unsigned, unsigned, char *); extern void transaction_4(char*, char*, unsigned, unsigned, unsigned); funcp funcTab[4] = {(funcp)execute_12, (funcp)execute_13, (funcp)vhdl_transfunc_eventcallback, (funcp)transaction_4}; const int NumRelocateId= 4; void relocate(char *dp) { iki_relocate(dp, "xsim.dir/Data_Memory_behav/xsim.reloc", (void **)funcTab, 4); iki_vhdl_file_variable_register(dp + 7136); iki_vhdl_file_variable_register(dp + 7192); /*Populate the transaction function pointer field in the whole net structure */ } void sensitize(char *dp) { iki_sensitize(dp, "xsim.dir/Data_Memory_behav/xsim.reloc"); } void simulate(char *dp) { iki_schedule_processes_at_time_zero(dp, "xsim.dir/Data_Memory_behav/xsim.reloc"); // Initialize Verilog nets in mixed simulation, for the cases when the value at time 0 should be propagated from the mixed language Vhdl net iki_execute_processes(); // Schedule resolution functions for the multiply driven Verilog nets that have strength // Schedule transaction functions for the singly driven Verilog nets that have strength } #include "iki_bridge.h" void relocate(char *); void sensitize(char *); void simulate(char *); extern SYSTEMCLIB_IMP_DLLSPEC void local_register_implicit_channel(int, char*); extern void implicit_HDL_SCinstatiate(); extern SYSTEMCLIB_IMP_DLLSPEC int xsim_argc_copy ; extern SYSTEMCLIB_IMP_DLLSPEC char** xsim_argv_copy ; int main(int argc, char **argv) { iki_heap_initialize("ms", "isimmm", 0, 2147483648) ; iki_set_sv_type_file_path_name("xsim.dir/Data_Memory_behav/xsim.svtype"); iki_set_crvs_dump_file_path_name("xsim.dir/Data_Memory_behav/xsim.crvsdump"); void* design_handle = iki_create_design("xsim.dir/Data_Memory_behav/xsim.mem", (void *)relocate, (void *)sensitize, (void *)simulate, 0, isimBridge_getWdbWriter(), 0, argc, argv); iki_set_rc_trial_count(100); (void) design_handle; return iki_simulate_design(); }
44895.c
/* * Copyright 2010-2016, Tarantool AUTHORS, please see AUTHORS file. * * 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 <COPYRIGHT HOLDER> ``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 * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "page.h" #include "bitset/bitset.h" extern inline size_t tt_bitset_page_alloc_size(void *(*realloc_arg)(void *ptr, size_t size)); extern inline void * tt_bitset_page_data(struct tt_bitset_page *page); extern inline void tt_bitset_page_create(struct tt_bitset_page *page); extern inline void tt_bitset_page_destroy(struct tt_bitset_page *page); extern inline size_t tt_bitset_page_first_pos(size_t pos); extern inline void tt_bitset_page_set_zeros(struct tt_bitset_page *page); extern inline void tt_bitset_page_set_ones(struct tt_bitset_page *page); extern inline void tt_bitset_page_and(struct tt_bitset_page *dst, struct tt_bitset_page *src); extern inline void tt_bitset_page_nand(struct tt_bitset_page *dst, struct tt_bitset_page *src); extern inline void tt_bitset_page_or(struct tt_bitset_page *dst, struct tt_bitset_page *src); #if defined(DEBUG) void tt_bitset_page_dump(struct tt_bitset_page *page, FILE *stream) { fprintf(stream, "Page %zu:\n", page->first_pos); char *d = bitset_page_data(page); for (int i = 0; i < BITSET_PAGE_DATA_SIZE; i++) { fprintf(stream, "%x ", *d); d++; } fprintf(stream, "\n--\n"); } #endif /* defined(DEBUG) */ static inline int page_cmp(const struct tt_bitset_page *a, const struct tt_bitset_page *b) { if (a->first_pos < b->first_pos) { return -1; } else if (a->first_pos > b->first_pos) { return 1; } else { return 0; } } rb_gen(, tt_bitset_pages_, tt_bitset_pages_t, struct tt_bitset_page, node, page_cmp)
613308.c
/***************************************************************************** Copyright (c) 2014, Intel Corp. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************** * Contents: Native high-level C interface to LAPACK function cungqr * Author: Intel Corporation * Generated November, 2011 *****************************************************************************/ #include "lapacke_utils.h" lapack_int LAPACKE_cungqr( int matrix_layout, lapack_int m, lapack_int n, lapack_int k, lapack_complex_float* a, lapack_int lda, const lapack_complex_float* tau ) { lapack_int info = 0; lapack_int lwork = -1; lapack_complex_float* work = NULL; lapack_complex_float work_query; if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { LAPACKE_xerbla( "LAPACKE_cungqr", -1 ); return -1; } #ifndef LAPACK_DISABLE_NAN_CHECK /* Optionally check input matrices for NaNs */ if( LAPACKE_cge_nancheck( matrix_layout, m, n, a, lda ) ) { return -5; } if( LAPACKE_c_nancheck( k, tau, 1 ) ) { return -7; } #endif /* Query optimal working array(s) size */ info = LAPACKE_cungqr_work( matrix_layout, m, n, k, a, lda, tau, &work_query, lwork ); if( info != 0 ) { goto exit_level_0; } lwork = LAPACK_C2INT( work_query ); /* Allocate memory for work arrays */ work = (lapack_complex_float*) LAPACKE_malloc( sizeof(lapack_complex_float) * lwork ); if( work == NULL ) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_0; } /* Call middle-level interface */ info = LAPACKE_cungqr_work( matrix_layout, m, n, k, a, lda, tau, work, lwork ); /* Release memory and exit */ LAPACKE_free( work ); exit_level_0: if( info == LAPACK_WORK_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_cungqr", info ); } return info; }
292424.c
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * * If you do not have access to either file, you may request a copy from * * [email protected]. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*------------------------------------------------------------------------- * * Created: H5checksum.c * Aug 21 2006 * Quincey Koziol * * Purpose: Internal code for computing fletcher32 checksums * *------------------------------------------------------------------------- */ /****************/ /* Module Setup */ /****************/ /***********/ /* Headers */ /***********/ #include "netcdf_filter_hdf5_build.h" /****************/ /* Local Macros */ /****************/ /* Polynomial quotient */ /* (same as the IEEE 802.3 (Ethernet) quotient) */ #define H5_CRC_QUOTIENT 0x04C11DB7 /******************/ /* Local Typedefs */ /******************/ /********************/ /* Package Typedefs */ /********************/ /********************/ /* Local Prototypes */ /********************/ /*********************/ /* Package Variables */ /*********************/ /*****************************/ /* Library Private Variables */ /*****************************/ /*******************/ /* Local Variables */ /*******************/ /* Table of CRCs of all 8-bit messages. */ static uint32_t H5_crc_table[256]; /* Flag: has the table been computed? */ static hbool_t H5_crc_table_computed = FALSE; /*------------------------------------------------------------------------- * Function: H5_checksum_fletcher32 * * Purpose: This routine provides a generic, fast checksum algorithm for * use in the library. * * Note: See the Wikipedia page for Fletcher's checksum: * http://en.wikipedia.org/wiki/Fletcher%27s_checksum * for more details, etc. * * Note #2: Per the information in RFC 3309: * (http://tools.ietf.org/html/rfc3309) * Fletcher's checksum is not reliable for small buffers. * * Note #3: The algorithm below differs from that given in the Wikipedia * page by copying the data into 'sum1' in a more portable way * and also by initializing 'sum1' and 'sum2' to 0 instead of * 0xffff (for backward compatibility reasons with earlier * HDF5 fletcher32 I/O filter routine, mostly). * * Return: 32-bit fletcher checksum of input buffer (can't fail) * * Programmer: Quincey Koziol * Monday, August 21, 2006 * *------------------------------------------------------------------------- */ uint32_t H5_checksum_fletcher32(const void *_data, size_t _len) { const uint8_t *data = (const uint8_t *)_data; /* Pointer to the data to be summed */ size_t len = _len / 2; /* Length in 16-bit words */ uint32_t sum1 = 0, sum2 = 0; FUNC_ENTER_NOAPI_NOINIT_NOERR /* Sanity check */ HDassert(_data); HDassert(_len > 0); /* Compute checksum for pairs of bytes */ /* (the magic "360" value is is the largest number of sums that can be * performed without numeric overflow) */ while (len) { size_t tlen = len > 360 ? 360 : len; len -= tlen; do { sum1 += (uint32_t)(((uint16_t)data[0]) << 8) | ((uint16_t)data[1]); data += 2; sum2 += sum1; } while (--tlen); sum1 = (sum1 & 0xffff) + (sum1 >> 16); sum2 = (sum2 & 0xffff) + (sum2 >> 16); } /* Check for odd # of bytes */ if(_len % 2) { sum1 += (uint32_t)(((uint16_t)*data) << 8); sum2 += sum1; sum1 = (sum1 & 0xffff) + (sum1 >> 16); sum2 = (sum2 & 0xffff) + (sum2 >> 16); } /* end if */ /* Second reduction step to reduce sums to 16 bits */ sum1 = (sum1 & 0xffff) + (sum1 >> 16); sum2 = (sum2 & 0xffff) + (sum2 >> 16); FUNC_LEAVE_NOAPI((sum2 << 16) | sum1) } /* end H5_checksum_fletcher32() */ /*------------------------------------------------------------------------- * Function: H5__checksum_crc_make_table * * Purpose: Compute the CRC table for the CRC checksum algorithm * * Return: none * * Programmer: Quincey Koziol * Tuesday, September 5, 2006 * *------------------------------------------------------------------------- */ static void H5__checksum_crc_make_table(void) { uint32_t c; /* Checksum for each byte value */ unsigned n, k; /* Local index variables */ FUNC_ENTER_STATIC_NOERR /* Compute the checksum for each possible byte value */ for(n = 0; n < 256; n++) { c = (uint32_t) n; for(k = 0; k < 8; k++) if(c & 1) c = H5_CRC_QUOTIENT ^ (c >> 1); else c = c >> 1; H5_crc_table[n] = c; } H5_crc_table_computed = TRUE; FUNC_LEAVE_NOAPI_VOID } /* end H5__checksum_crc_make_table() */ /*------------------------------------------------------------------------- * Function: H5__checksum_crc_update * * Purpose: Update a running CRC with the bytes buf[0..len-1]--the CRC * should be initialized to all 1's, and the transmitted value * is the 1's complement of the final running CRC (see the * H5_checksum_crc() routine below)). * * Return: 32-bit CRC checksum of input buffer (can't fail) * * Programmer: Quincey Koziol * Tuesday, September 5, 2006 * *------------------------------------------------------------------------- */ static uint32_t H5__checksum_crc_update(uint32_t crc, const uint8_t *buf, size_t len) { size_t n; /* Local index variable */ FUNC_ENTER_STATIC_NOERR /* Initialize the CRC table if necessary */ if(!H5_crc_table_computed) H5__checksum_crc_make_table(); /* Update the CRC with the results from this buffer */ for(n = 0; n < len; n++) crc = H5_crc_table[(crc ^ buf[n]) & 0xff] ^ (crc >> 8); FUNC_LEAVE_NOAPI(crc) } /* end H5__checksum_crc_update() */ /*------------------------------------------------------------------------- * Function: H5_checksum_crc * * Purpose: This routine provides a generic checksum algorithm for * use in the library. * * Note: This algorithm was based on the implementation described * in the document describing the PNG image format: * http://www.w3.org/TR/PNG/#D-CRCAppendix * * Return: 32-bit CRC checksum of input buffer (can't fail) * * Programmer: Quincey Koziol * Tuesday, September 5, 2006 * *------------------------------------------------------------------------- */ uint32_t H5_checksum_crc(const void *_data, size_t len) { FUNC_ENTER_NOAPI_NOINIT_NOERR /* Sanity check */ HDassert(_data); HDassert(len > 0); FUNC_LEAVE_NOAPI(H5__checksum_crc_update((uint32_t)0xffffffffL, (const uint8_t *)_data, len) ^ 0xffffffffL) } /* end H5_checksum_crc() */ /* ------------------------------------------------------------------------------- H5_lookup3_mix -- mix 3 32-bit values reversibly. This is reversible, so any information in (a,b,c) before mix() is still in (a,b,c) after mix(). If four pairs of (a,b,c) inputs are run through mix(), or through mix() in reverse, there are at least 32 bits of the output that are sometimes the same for one pair and different for another pair. This was tested for: * pairs that differed by one bit, by two bits, in any combination of top bits of (a,b,c), or in any combination of bottom bits of (a,b,c). * "differ" is defined as +, -, ^, or ~^. For + and -, I transformed the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. * the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that satisfy this are 4 6 8 16 19 4 9 15 3 18 27 15 14 9 3 7 17 3 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing for "differ" defined as + with a one-bit base and a two-bit delta. I used http://burtleburtle.net/bob/hash/avalanche.html to choose the operations, constants, and arrangements of the variables. This does not achieve avalanche. There are input bits of (a,b,c) that fail to affect some output bits of (a,b,c), especially of a. The most thoroughly mixed value is c, but it doesn't really even achieve avalanche in c. This allows some parallelism. Read-after-writes are good at doubling the number of bits affected, so the goal of mixing pulls in the opposite direction as the goal of parallelism. I did what I could. Rotates seem to cost as much as shifts on every machine I could lay my hands on, and rotates are much kinder to the top and bottom bits, so I used rotates. ------------------------------------------------------------------------------- */ #define H5_lookup3_rot(x,k) (((x)<<(k)) ^ ((x)>>(32-(k)))) #define H5_lookup3_mix(a,b,c) \ { \ a -= c; a ^= H5_lookup3_rot(c, 4); c += b; \ b -= a; b ^= H5_lookup3_rot(a, 6); a += c; \ c -= b; c ^= H5_lookup3_rot(b, 8); b += a; \ a -= c; a ^= H5_lookup3_rot(c,16); c += b; \ b -= a; b ^= H5_lookup3_rot(a,19); a += c; \ c -= b; c ^= H5_lookup3_rot(b, 4); b += a; \ } /* ------------------------------------------------------------------------------- H5_lookup3_final -- final mixing of 3 32-bit values (a,b,c) into c Pairs of (a,b,c) values differing in only a few bits will usually produce values of c that look totally different. This was tested for * pairs that differed by one bit, by two bits, in any combination of top bits of (a,b,c), or in any combination of bottom bits of (a,b,c). * "differ" is defined as +, -, ^, or ~^. For + and -, I transformed the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. * the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. These constants passed: 14 11 25 16 4 14 24 12 14 25 16 4 14 24 and these came close: 4 8 15 26 3 22 24 10 8 15 26 3 22 24 11 8 15 26 3 22 24 ------------------------------------------------------------------------------- */ #define H5_lookup3_final(a,b,c) \ { \ c ^= b; c -= H5_lookup3_rot(b,14); \ a ^= c; a -= H5_lookup3_rot(c,11); \ b ^= a; b -= H5_lookup3_rot(a,25); \ c ^= b; c -= H5_lookup3_rot(b,16); \ a ^= c; a -= H5_lookup3_rot(c,4); \ b ^= a; b -= H5_lookup3_rot(a,14); \ c ^= b; c -= H5_lookup3_rot(b,24); \ } /* ------------------------------------------------------------------------------- H5_checksum_lookup3() -- hash a variable-length key into a 32-bit value k : the key (the unaligned variable-length array of bytes) length : the length of the key, counting by bytes initval : can be any 4-byte value Returns a 32-bit value. Every bit of the key affects every bit of the return value. Two keys differing by one or two bits will have totally different hash values. The best hash table sizes are powers of 2. There is no need to do mod a prime (mod is sooo slow!). If you need less than 32 bits, use a bitmask. For example, if you need only 10 bits, do h = (h & hashmask(10)); In which case, the hash table should have hashsize(10) elements. If you are hashing n strings (uint8_t **)k, do it like this: for (i=0, h=0; i<n; ++i) h = H5_checksum_lookup( k[i], len[i], h); By Bob Jenkins, 2006. [email protected]. You may use this code any way you wish, private, educational, or commercial. It's free. Use for hash table lookup, or anything where one collision in 2^^32 is acceptable. Do NOT use for cryptographic purposes. ------------------------------------------------------------------------------- */ uint32_t H5_checksum_lookup3(const void *key, size_t length, uint32_t initval) { const uint8_t *k = (const uint8_t *)key; uint32_t a, b, c; /* internal state */ FUNC_ENTER_NOAPI_NOINIT_NOERR /* Sanity check */ HDassert(key); HDassert(length > 0); /* Set up the internal state */ a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; a += ((uint32_t)k[1])<<8; a += ((uint32_t)k[2])<<16; a += ((uint32_t)k[3])<<24; b += k[4]; b += ((uint32_t)k[5])<<8; b += ((uint32_t)k[6])<<16; b += ((uint32_t)k[7])<<24; c += k[8]; c += ((uint32_t)k[9])<<8; c += ((uint32_t)k[10])<<16; c += ((uint32_t)k[11])<<24; H5_lookup3_mix(a, b, c); length -= 12; k += 12; } /*-------------------------------- last block: affect all 32 bits of (c) */ switch(length) /* all the case statements fall through */ { case 12: c+=((uint32_t)k[11])<<24; H5_ATTR_FALLTHROUGH case 11: c+=((uint32_t)k[10])<<16; H5_ATTR_FALLTHROUGH case 10: c+=((uint32_t)k[9])<<8; H5_ATTR_FALLTHROUGH case 9 : c+=k[8]; H5_ATTR_FALLTHROUGH case 8 : b+=((uint32_t)k[7])<<24; H5_ATTR_FALLTHROUGH case 7 : b+=((uint32_t)k[6])<<16; H5_ATTR_FALLTHROUGH case 6 : b+=((uint32_t)k[5])<<8; H5_ATTR_FALLTHROUGH case 5 : b+=k[4]; H5_ATTR_FALLTHROUGH case 4 : a+=((uint32_t)k[3])<<24; H5_ATTR_FALLTHROUGH case 3 : a+=((uint32_t)k[2])<<16; H5_ATTR_FALLTHROUGH case 2 : a+=((uint32_t)k[1])<<8; H5_ATTR_FALLTHROUGH case 1 : a+=k[0]; break; case 0 : goto done; default: HDassert(0 && "This Should never be executed!"); } H5_lookup3_final(a, b, c); done: FUNC_LEAVE_NOAPI(c) } /* end H5_checksum_lookup3() */ /*------------------------------------------------------------------------- * Function: H5_checksum_metadata * * Purpose: Provide a more abstract routine for checksumming metadata * in a file, where the policy of which algorithm to choose * is centralized. * * Return: checksum of input buffer (can't fail) * * Programmer: Quincey Koziol * Tuesday, August 22, 2006 * *------------------------------------------------------------------------- */ uint32_t H5_checksum_metadata(const void *data, size_t len, uint32_t initval) { FUNC_ENTER_NOAPI_NOINIT_NOERR /* Sanity check */ HDassert(data); HDassert(len > 0); /* Choose the appropriate checksum routine */ /* (use Bob Jenkin's "lookup3" algorithm for all buffer sizes) */ FUNC_LEAVE_NOAPI(H5_checksum_lookup3(data, len, initval)) } /* end H5_checksum_metadata() */ /*------------------------------------------------------------------------- * Function: H5_hash_string * * Purpose: Provide a simple & fast routine for hashing strings * * Note: This algorithm is the 'djb2' algorithm described on this page: * http://www.cse.yorku.ca/~oz/hash.html * * Return: hash of input string (can't fail) * * Programmer: Quincey Koziol * Tuesday, December 11, 2007 * *------------------------------------------------------------------------- */ uint32_t H5_hash_string(const char *str) { uint32_t hash = 5381; int c; FUNC_ENTER_NOAPI_NOINIT_NOERR /* Sanity check */ HDassert(str); while((c = *str++)) hash = ((hash << 5) + hash) + (uint32_t)c; /* hash * 33 + c */ FUNC_LEAVE_NOAPI(hash) } /* end H5_hash_string() */
808757.c
/******************************************************************************* * commands.c * * The body of the library. * * NOTE This file is part of UniversalShellBuilder. * *******************************************************************************/ /**************************** * INCLUDES * ****************************/ #include "commands.h" /**************************** * CONSTANTS DEFINITION * ****************************/ /**************************** * GLOBAL VARIABLES * * (only in the scope * * of this file) * ****************************/ static int s_argc; static char** s_argv; static char* possible_options; static union _option got_options[CMD_MAX_N_OPTIONS]; /**************************** * GLOBAL VARIABLES * * (used externally) * ****************************/ int noarg; /**************************** * GENERAL FUNCTIONS * ****************************/ /* separate_args: splits a message in arguments separated by a specified char c */ unsigned separate_args_char(char *msg, char *argv[], char c) { unsigned argc = 0; while(*msg) { while(*msg == c) *msg++ = '\0'; if (*msg) argv[argc++] = msg; while(*msg && *msg != c) msg++; } return argc; } /* separate_args: splits a message in arguments separated by ' ' */ inline unsigned separate_args(char *msg, char *argv[]) { return separate_args_char(msg, argv, ' '); } /* command_name: identify the command, returns the number of the specified command name */ unsigned command_name(char *name) { unsigned number; for (number=0; number<N_COMMANDS; number++) { if (strcmp(commands[number].name, name) == 0) { break; } } return number; } /* execute_command: identifies the command from a list and executes it */ void execute_command(int argc, char* argv[]) { unsigned command_number = command_name(argv[0]); s_argc = argc; s_argv = argv; if (command_number < N_COMMANDS) { commands[command_number].function(); } else { if (!strcmp(s_argv[0], "help")) { if (s_argc > 1) { default_cmd_help(s_argv[1]); } else { default_cmd_help(NULL); } } else { default_cmd_error(CMD_ERROR_COMMAND_NOT_VALID, s_argv[0]); } } } /* arg: return a pointer to the n-th non-option argument */ char *arg(const unsigned n) { if (n>noarg) { return NULL; } return s_argv[optind+n-1]; } /* opt: check if the option was received in the arguments */ char opt(const char opt) { return opt_union(opt).value; } /* opt_content: the content of an option expecting an argument */ char *opt_content(const char opt) { return opt_union(opt).content; } /* opt_union: check if the option was received in the arguments by looking at 'got_options' and 'possible_options' */ union _option opt_union(const char opt) { char *char_ptr; union _option aux_opt, *opt_ptr; for (char_ptr=possible_options, opt_ptr=got_options; *char_ptr; char_ptr++, opt_ptr++) { while (*char_ptr == ':') char_ptr++; if (*char_ptr == opt) return *opt_ptr; } // Not found (this should never happen) #if (CMD_DEBUG) char arg_opt[2] = {0}; arg_opt[0] = opt; gprint("ERROR: "); gprint("opt could not recognize option '"); gprint(arg_opt); gprint("'" NL "is it in '"); gprint(possible_options); gprint("'?" NL); #endif aux_opt.value = FALSE; return aux_opt; } /* get_options: get every option received in the arguments and register them in 'options'. On error, print help */ int get_options(char *options) { char h_options[CMD_MAX_N_OPTIONS + CMD_MAX_N_OPTIONS_WITH_ARGS + 2]; unsigned i, j; int c; // Register globals possible_options = options; #if (CMD_DEBUG) for (i=0; options[i]; i++); if (i > CMD_MAX_N_OPTIONS+CMD_MAX_N_OPTIONS_WITH_ARGS) { gprint("ERROR: '"); gprint(options); gprint("' is too long."); gprint("Check 'CMD_MAX_N_OPTIONS' and 'CMD_MAX_N_OPTIONS_WITH_ARGS'" NL); gprint(" Error from get_options() in commands.c" NL "Called from "); gprint(argv[0]); gprint(NL); return 1; } #endif // TODO only if no 'h' in options // Copy options into a new string to have 'help' option #ifdef CMD_AUTOHELP j = 1; #else j = 0; #endif h_options[0] = 'h'; for (i=0; options[i]; i++) h_options[i+j] = options[i]; h_options[i+j] = '\0'; clean_getopt(); // Clean got_options for (i=0, j=0; options[i]; i++) { got_options[j].value = FALSE; if (options[i] != ':') j++; } // Get every option while ((c = getopt(s_argc, s_argv, h_options)) != GETOPT_DONE) { // Print help #ifdef CMD_AUTOHELP if (c == 'h') { // Print help and return default_cmd_help(s_argv[0]); return 1; // HELP } #endif // Handle errors if (c == GETOPT_NO_ARG) { h_options[0] = optopt; h_options[1] = 0; default_cmd_error(CMD_ERROR_OPTION_EXPECTS_ARG, h_options); return c; } if (c == GETOPT_INVALID ) { h_options[0] = optopt; h_options[1] = 0; default_cmd_error(CMD_ERROR_OPTION_NOT_VALID, h_options); return c; } // Everything ok, save option for (i=0, j=0; options[i]; i++) { // Look for valid options if (c == options[i]) { // Save the option got_options[j].value = TRUE; if (optarg != NULL) got_options[j].content = optarg; break; } if (options[i] != ':') j++; } } // No errors, everything ok noarg = s_argc-optind; return 0; } /**************************** * SPECIAL COMMANDS * ****************************/ /* default_cmd_help: print general help, or help about a specified command */ int default_cmd_help(char *command) { unsigned number; if (command && strcmp(command, "help")) { // If asked for help about a command, show the help #ifdef CMD_AUTOHELP if ((number=command_name(command)) < N_COMMANDS) { gprint(commands[number].help); } else #endif { default_cmd_error(CMD_ERROR_COMMAND_NOT_VALID,command); } } else { // Your system header here -> gprint(CMD_STR_PROJECT_TITLE); gprint(CMD_STR_AVAILABLE_COMMANDS); for (number = 0; number<N_COMMANDS; number++) { gprint(commands[number].name); gprint(NL); } #ifdef CMD_AUTOHELP gprint(NL CMD_STR_ADDITIONAL_HELP); #endif } return 0; } /* default_cmd_error: print error messages */ void default_cmd_error(enum _error_code error, char* arg) { #ifdef CMD_SAVE_MEMORY char error_c[6] = {'E', 'r', 'r', ' ', '0' + (char) error, 0}; gprint(error_c); gprint(NL); #else char *command = NULL; gprint(CMD_STR_ERROR_WORD); switch (error) { case CMD_ERROR_COMMAND_NOT_VALID: gprint("'"); gprint(arg); gprint("' " CMD_STR_NOT_VALID_COMMAND); break; case CMD_ERROR_OPTION_NOT_VALID: gprint("'-"); gprint(arg); gprint("' " CMD_STR_NOT_VALID_OPTION); command = s_argv[0]; break; case CMD_ERROR_OPTION_EXPECTS_ARG: gprint("'-"); gprint(arg); gprint("' " CMD_STR_ARG_EXPECTED); command = s_argv[0]; break; } gprint(NL); default_cmd_help(command); #endif }
880853.c
#include <stddef.h> #include "int.h" #include "str.h" const char *parse_sign(const char *buf, bool *pos) { const char *p = buf; if (*p == '-') { *pos = false; ++p; return p; } if (*p == '+') { ++p; } *pos = true; return p; } const char *parse_int32(const char *buf, int32_t *data, char sep) { const char *p = skip_space(buf); int32_t num = 0; bool pos; p = parse_sign(p, &pos); for (; *p != sep && !is_line_end(*p); ++p) { if (!is_space(*p)) { if (is_digit(*p)) { num = num * 10 + digit_value(*p); } else { return NULL; } } } *data = (pos ? num : -num); ++p; return p; } const char *parse_int64(const char *buf, int64_t *data, char sep) { const char *p = skip_space(buf); int64_t num = 0; bool pos; p = parse_sign(p, &pos); for (; *p != sep && !is_line_end(*p); ++p) { if (!is_space(*p)) { if (is_digit(*p)) { num = num * 10 + digit_value(*p); } else { return NULL; } } } *data = (pos ? num : -num); ++p; return p; }
153907.c
/* * Glue Code for AVX assembler versions of Serpent Cipher * * Copyright (C) 2012 Johannes Goetzfried * <[email protected]> * * Copyright © 2011-2013 Jussi Kivilinna <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * */ #include <linux/module.h> #include <linux/hardirq.h> #include <linux/types.h> #include <linux/crypto.h> #include <linux/err.h> #include <crypto/ablk_helper.h> #include <crypto/algapi.h> #include <crypto/serpent.h> #include <crypto/cryptd.h> #include <crypto/b128ops.h> #include <crypto/ctr.h> #include <crypto/lrw.h> #include <crypto/xts.h> #include <asm/xcr.h> #include <asm/xsave.h> #include <asm/crypto/serpent-avx.h> #include <asm/crypto/glue_helper.h> /* 8-way parallel cipher functions */ asmlinkage void serpent_ecb_enc_8way_avx(struct serpent_ctx *ctx, u8 *dst, const u8 *src); EXPORT_SYMBOL_GPL(serpent_ecb_enc_8way_avx); asmlinkage void serpent_ecb_dec_8way_avx(struct serpent_ctx *ctx, u8 *dst, const u8 *src); EXPORT_SYMBOL_GPL(serpent_ecb_dec_8way_avx); asmlinkage void serpent_cbc_dec_8way_avx(struct serpent_ctx *ctx, u8 *dst, const u8 *src); EXPORT_SYMBOL_GPL(serpent_cbc_dec_8way_avx); asmlinkage void serpent_ctr_8way_avx(struct serpent_ctx *ctx, u8 *dst, const u8 *src, le128 *iv); EXPORT_SYMBOL_GPL(serpent_ctr_8way_avx); asmlinkage void serpent_xts_enc_8way_avx(struct serpent_ctx *ctx, u8 *dst, const u8 *src, le128 *iv); EXPORT_SYMBOL_GPL(serpent_xts_enc_8way_avx); asmlinkage void serpent_xts_dec_8way_avx(struct serpent_ctx *ctx, u8 *dst, const u8 *src, le128 *iv); EXPORT_SYMBOL_GPL(serpent_xts_dec_8way_avx); void __serpent_crypt_ctr(void *ctx, u128 *dst, const u128 *src, le128 *iv) { be128 ctrblk; le128_to_be128(&ctrblk, iv); le128_inc(iv); __serpent_encrypt(ctx, (u8 *)&ctrblk, (u8 *)&ctrblk); u128_xor(dst, src, (u128 *)&ctrblk); } EXPORT_SYMBOL_GPL(__serpent_crypt_ctr); void serpent_xts_enc(void *ctx, u128 *dst, const u128 *src, le128 *iv) { glue_xts_crypt_128bit_one(ctx, dst, src, iv, GLUE_FUNC_CAST(__serpent_encrypt)); } EXPORT_SYMBOL_GPL(serpent_xts_enc); void serpent_xts_dec(void *ctx, u128 *dst, const u128 *src, le128 *iv) { glue_xts_crypt_128bit_one(ctx, dst, src, iv, GLUE_FUNC_CAST(__serpent_decrypt)); } EXPORT_SYMBOL_GPL(serpent_xts_dec); static const struct common_glue_ctx serpent_enc = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .ecb = GLUE_FUNC_CAST(serpent_ecb_enc_8way_avx) } }, { .num_blocks = 1, .fn_u = { .ecb = GLUE_FUNC_CAST(__serpent_encrypt) } } } }; static const struct common_glue_ctx serpent_ctr = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(serpent_ctr_8way_avx) } }, { .num_blocks = 1, .fn_u = { .ctr = GLUE_CTR_FUNC_CAST(__serpent_crypt_ctr) } } } }; static const struct common_glue_ctx serpent_enc_xts = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_enc_8way_avx) } }, { .num_blocks = 1, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_enc) } } } }; static const struct common_glue_ctx serpent_dec = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .ecb = GLUE_FUNC_CAST(serpent_ecb_dec_8way_avx) } }, { .num_blocks = 1, .fn_u = { .ecb = GLUE_FUNC_CAST(__serpent_decrypt) } } } }; static const struct common_glue_ctx serpent_dec_cbc = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(serpent_cbc_dec_8way_avx) } }, { .num_blocks = 1, .fn_u = { .cbc = GLUE_CBC_FUNC_CAST(__serpent_decrypt) } } } }; static const struct common_glue_ctx serpent_dec_xts = { .num_funcs = 2, .fpu_blocks_limit = SERPENT_PARALLEL_BLOCKS, .funcs = { { .num_blocks = SERPENT_PARALLEL_BLOCKS, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_dec_8way_avx) } }, { .num_blocks = 1, .fn_u = { .xts = GLUE_XTS_FUNC_CAST(serpent_xts_dec) } } } }; static int ecb_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ecb_crypt_128bit(&serpent_enc, desc, dst, src, nbytes); } static int ecb_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ecb_crypt_128bit(&serpent_dec, desc, dst, src, nbytes); } static int cbc_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_encrypt_128bit(GLUE_FUNC_CAST(__serpent_encrypt), desc, dst, src, nbytes); } static int cbc_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_cbc_decrypt_128bit(&serpent_dec_cbc, desc, dst, src, nbytes); } static int ctr_crypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { return glue_ctr_crypt_128bit(&serpent_ctr, desc, dst, src, nbytes); } static inline bool serpent_fpu_begin(bool fpu_enabled, unsigned int nbytes) { return glue_fpu_begin(SERPENT_BLOCK_SIZE, SERPENT_PARALLEL_BLOCKS, NULL, fpu_enabled, nbytes); } static inline void serpent_fpu_end(bool fpu_enabled) { glue_fpu_end(fpu_enabled); } struct crypt_priv { struct serpent_ctx *ctx; bool fpu_enabled; }; static void encrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes) { const unsigned int bsize = SERPENT_BLOCK_SIZE; struct crypt_priv *ctx = priv; int i; ctx->fpu_enabled = serpent_fpu_begin(ctx->fpu_enabled, nbytes); if (nbytes == bsize * SERPENT_PARALLEL_BLOCKS) { serpent_ecb_enc_8way_avx(ctx->ctx, srcdst, srcdst); return; } for (i = 0; i < nbytes / bsize; i++, srcdst += bsize) __serpent_encrypt(ctx->ctx, srcdst, srcdst); } static void decrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes) { const unsigned int bsize = SERPENT_BLOCK_SIZE; struct crypt_priv *ctx = priv; int i; ctx->fpu_enabled = serpent_fpu_begin(ctx->fpu_enabled, nbytes); if (nbytes == bsize * SERPENT_PARALLEL_BLOCKS) { serpent_ecb_dec_8way_avx(ctx->ctx, srcdst, srcdst); return; } for (i = 0; i < nbytes / bsize; i++, srcdst += bsize) __serpent_decrypt(ctx->ctx, srcdst, srcdst); } int lrw_serpent_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct serpent_lrw_ctx *ctx = crypto_tfm_ctx(tfm); int err; err = __serpent_setkey(&ctx->serpent_ctx, key, keylen - SERPENT_BLOCK_SIZE); if (err) return err; return lrw_init_table(&ctx->lrw_table, key + keylen - SERPENT_BLOCK_SIZE); } EXPORT_SYMBOL_GPL(lrw_serpent_setkey); static int lrw_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_lrw_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[SERPENT_PARALLEL_BLOCKS]; struct crypt_priv crypt_ctx = { .ctx = &ctx->serpent_ctx, .fpu_enabled = false, }; struct lrw_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .table_ctx = &ctx->lrw_table, .crypt_ctx = &crypt_ctx, .crypt_fn = encrypt_callback, }; int ret; desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; ret = lrw_crypt(desc, dst, src, nbytes, &req); serpent_fpu_end(crypt_ctx.fpu_enabled); return ret; } static int lrw_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_lrw_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); be128 buf[SERPENT_PARALLEL_BLOCKS]; struct crypt_priv crypt_ctx = { .ctx = &ctx->serpent_ctx, .fpu_enabled = false, }; struct lrw_crypt_req req = { .tbuf = buf, .tbuflen = sizeof(buf), .table_ctx = &ctx->lrw_table, .crypt_ctx = &crypt_ctx, .crypt_fn = decrypt_callback, }; int ret; desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; ret = lrw_crypt(desc, dst, src, nbytes, &req); serpent_fpu_end(crypt_ctx.fpu_enabled); return ret; } void lrw_serpent_exit_tfm(struct crypto_tfm *tfm) { struct serpent_lrw_ctx *ctx = crypto_tfm_ctx(tfm); lrw_free_table(&ctx->lrw_table); } EXPORT_SYMBOL_GPL(lrw_serpent_exit_tfm); int xts_serpent_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct serpent_xts_ctx *ctx = crypto_tfm_ctx(tfm); u32 *flags = &tfm->crt_flags; int err; /* key consists of keys of equal size concatenated, therefore * the length must be even */ if (keylen % 2) { *flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; return -EINVAL; } /* first half of xts-key is for crypt */ err = __serpent_setkey(&ctx->crypt_ctx, key, keylen / 2); if (err) return err; /* second half of xts-key is for tweak */ return __serpent_setkey(&ctx->tweak_ctx, key + keylen / 2, keylen / 2); } EXPORT_SYMBOL_GPL(xts_serpent_setkey); static int xts_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); return glue_xts_crypt_128bit(&serpent_enc_xts, desc, dst, src, nbytes, XTS_TWEAK_CAST(__serpent_encrypt), &ctx->tweak_ctx, &ctx->crypt_ctx); } static int xts_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct serpent_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); return glue_xts_crypt_128bit(&serpent_dec_xts, desc, dst, src, nbytes, XTS_TWEAK_CAST(__serpent_encrypt), &ctx->tweak_ctx, &ctx->crypt_ctx); } static struct crypto_alg serpent_algs[10] = { { .cra_name = "__ecb-serpent-avx", .cra_driver_name = "__driver-ecb-serpent-avx", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER | CRYPTO_ALG_INTERNAL, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = serpent_setkey, .encrypt = ecb_encrypt, .decrypt = ecb_decrypt, }, }, }, { .cra_name = "__cbc-serpent-avx", .cra_driver_name = "__driver-cbc-serpent-avx", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER | CRYPTO_ALG_INTERNAL, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = serpent_setkey, .encrypt = cbc_encrypt, .decrypt = cbc_decrypt, }, }, }, { .cra_name = "__ctr-serpent-avx", .cra_driver_name = "__driver-ctr-serpent-avx", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER | CRYPTO_ALG_INTERNAL, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct serpent_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = serpent_setkey, .encrypt = ctr_crypt, .decrypt = ctr_crypt, }, }, }, { .cra_name = "__lrw-serpent-avx", .cra_driver_name = "__driver-lrw-serpent-avx", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER | CRYPTO_ALG_INTERNAL, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_lrw_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_exit = lrw_serpent_exit_tfm, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE + SERPENT_BLOCK_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE + SERPENT_BLOCK_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = lrw_serpent_setkey, .encrypt = lrw_encrypt, .decrypt = lrw_decrypt, }, }, }, { .cra_name = "__xts-serpent-avx", .cra_driver_name = "__driver-xts-serpent-avx", .cra_priority = 0, .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER | CRYPTO_ALG_INTERNAL, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct serpent_xts_ctx), .cra_alignmask = 0, .cra_type = &crypto_blkcipher_type, .cra_module = THIS_MODULE, .cra_u = { .blkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE * 2, .max_keysize = SERPENT_MAX_KEY_SIZE * 2, .ivsize = SERPENT_BLOCK_SIZE, .setkey = xts_serpent_setkey, .encrypt = xts_encrypt, .decrypt = xts_decrypt, }, }, }, { .cra_name = "ecb(serpent)", .cra_driver_name = "ecb-serpent-avx", .cra_priority = 500, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "cbc(serpent)", .cra_driver_name = "cbc-serpent-avx", .cra_priority = 500, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = __ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "ctr(serpent)", .cra_driver_name = "ctr-serpent-avx", .cra_priority = 500, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = 1, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_encrypt, .geniv = "chainiv", }, }, }, { .cra_name = "lrw(serpent)", .cra_driver_name = "lrw-serpent-avx", .cra_priority = 500, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE + SERPENT_BLOCK_SIZE, .max_keysize = SERPENT_MAX_KEY_SIZE + SERPENT_BLOCK_SIZE, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, }, { .cra_name = "xts(serpent)", .cra_driver_name = "xts-serpent-avx", .cra_priority = 500, .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC, .cra_blocksize = SERPENT_BLOCK_SIZE, .cra_ctxsize = sizeof(struct async_helper_ctx), .cra_alignmask = 0, .cra_type = &crypto_ablkcipher_type, .cra_module = THIS_MODULE, .cra_init = ablk_init, .cra_exit = ablk_exit, .cra_u = { .ablkcipher = { .min_keysize = SERPENT_MIN_KEY_SIZE * 2, .max_keysize = SERPENT_MAX_KEY_SIZE * 2, .ivsize = SERPENT_BLOCK_SIZE, .setkey = ablk_set_key, .encrypt = ablk_encrypt, .decrypt = ablk_decrypt, }, }, } }; static int __init serpent_init(void) { u64 xcr0; if (!cpu_has_avx || !cpu_has_osxsave) { printk(KERN_INFO "AVX instructions are not detected.\n"); return -ENODEV; } xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK); if ((xcr0 & (XSTATE_SSE | XSTATE_YMM)) != (XSTATE_SSE | XSTATE_YMM)) { printk(KERN_INFO "AVX detected but unusable.\n"); return -ENODEV; } return crypto_register_algs(serpent_algs, ARRAY_SIZE(serpent_algs)); } static void __exit serpent_exit(void) { crypto_unregister_algs(serpent_algs, ARRAY_SIZE(serpent_algs)); } module_init(serpent_init); module_exit(serpent_exit); MODULE_DESCRIPTION("Serpent Cipher Algorithm, AVX optimized"); MODULE_LICENSE("GPL"); MODULE_ALIAS_CRYPTO("serpent");
475594.c
/****************************************************************************** * Code generated with sympy 0.7.6 * * * * See http://www.sympy.org/ for more information. * * * * This file is part of 'project' * ******************************************************************************/ #include "root_middle_prox_side_0.h" #include <math.h> double root_middle_prox_side_0() { double root_middle_prox_side_0_result; root_middle_prox_side_0_result = 0; return root_middle_prox_side_0_result; }
901722.c
/* crc32.c -- compute the CRC-32 of a data stream * Copyright (C) 1995-2003 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * Thanks to Rodney Brown <[email protected]> for his contribution of faster * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing * tables for updating the shift register in one step with three exclusive-ors * instead of four steps with four exclusive-ors. This results about a factor * of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. */ /* @(#) $Id$ */ #ifdef MAKECRCH # include <stdio.h> # ifndef DYNAMIC_CRC_TABLE # define DYNAMIC_CRC_TABLE # endif /* !DYNAMIC_CRC_TABLE */ #endif /* MAKECRCH */ #include "zutil.h" /* for STDC and FAR definitions */ #define local static /* Find a four-byte integer type for crc32_little() and crc32_big(). */ #ifndef NOBYFOUR # ifdef STDC /* need ANSI C limits.h to determine sizes */ # include <limits.h> # define BYFOUR # if (UINT_MAX == 0xffffffffUL) typedef unsigned int u4; # else # if (ULONG_MAX == 0xffffffffUL) typedef unsigned long u4; # else # if (USHRT_MAX == 0xffffffffUL) typedef unsigned short u4; # else # undef BYFOUR /* can't find a four-byte integer type! */ # endif # endif # endif # endif /* STDC */ #endif /* !NOBYFOUR */ /* Definitions for doing the crc four data bytes at a time. */ #ifdef BYFOUR # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ (((w)&0xff00)<<8)+(((w)&0xff)<<24)) local unsigned long crc32_little OF((unsigned long, const unsigned char FAR *, unsigned)); local unsigned long crc32_big OF((unsigned long, const unsigned char FAR *, unsigned)); # define TBLS 8 #else # define TBLS 1 #endif /* BYFOUR */ #ifdef DYNAMIC_CRC_TABLE local int crc_table_empty = 1; local unsigned long FAR crc_table[TBLS][256]; local void make_crc_table OF((void)); #ifdef MAKECRCH local void write_table OF((FILE *, const unsigned long FAR *)); #endif /* MAKECRCH */ /* Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. Polynomials over GF(2) are represented in binary, one bit per coefficient, with the lowest powers in the most significant bit. Then adding polynomials is just exclusive-or, and multiplying a polynomial by x is a right shift by one. If we call the above polynomial p, and represent a byte as the polynomial q, also with the lowest power in the most significant bit (so the byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, where a mod b means the remainder after dividing a by b. This calculation is done using the shift-register method of multiplying and taking the remainder. The register is initialized to zero, and for each incoming bit, x^32 is added mod p to the register if the bit is a one (where x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x (which is shifting right by one and adding x^32 mod p if the bit shifted out is a one). We start with the highest power (least significant bit) of q and repeat for all eight bits of q. The first table is simply the CRC of all possible eight bit values. This is all the information needed to generate CRCs on data a byte at a time for all combinations of CRC register values and incoming bytes. The remaining tables allow for word-at-a-time CRC calculation for both big-endian and little- endian machines, where a word is four bytes. */ local void make_crc_table() { unsigned long c; int n, k; unsigned long poly; /* polynomial exclusive-or pattern */ /* terms of polynomial defining this crc (except x^32): */ static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; /* make exclusive-or pattern from polynomial (0xedb88320UL) */ poly = 0UL; for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) poly |= 1UL << (31 - p[n]); /* generate a crc for every 8-bit value */ for (n = 0; n < 256; n++) { c = (unsigned long)n; for (k = 0; k < 8; k++) c = c & 1 ? poly ^ (c >> 1) : c >> 1; crc_table[0][n] = c; } #ifdef BYFOUR /* generate crc for each value followed by one, two, and three zeros, and then the byte reversal of those as well as the first table */ for (n = 0; n < 256; n++) { c = crc_table[0][n]; crc_table[4][n] = REV(c); for (k = 1; k < 4; k++) { c = crc_table[0][c & 0xff] ^ (c >> 8); crc_table[k][n] = c; crc_table[k + 4][n] = REV(c); } } #endif /* BYFOUR */ crc_table_empty = 0; #ifdef MAKECRCH /* write out CRC tables to crc32.h */ { FILE *out; out = fopen("crc32.h", "w"); if (out == NULL) return; fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); fprintf(out, "local const unsigned long FAR "); fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); write_table(out, crc_table[0]); # ifdef BYFOUR fprintf(out, "#ifdef BYFOUR\n"); for (k = 1; k < 8; k++) { fprintf(out, " },\n {\n"); write_table(out, crc_table[k]); } fprintf(out, "#endif\n"); # endif /* BYFOUR */ fprintf(out, " }\n};\n"); fclose(out); } #endif /* MAKECRCH */ } #ifdef MAKECRCH local void write_table(out, table) FILE *out; const unsigned long FAR *table; { int n; for (n = 0; n < 256; n++) fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); } #endif /* MAKECRCH */ #else /* !DYNAMIC_CRC_TABLE */ /* ======================================================================== * Tables of CRC-32s of all single-byte values, made by make_crc_table(). */ #include "crc32.h" #endif /* DYNAMIC_CRC_TABLE */ /* ========================================================================= * This function can be used by asm versions of crc32() */ const unsigned long FAR * ZEXPORT get_crc_table() { #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ return (const unsigned long FAR *)crc_table; } /* ========================================================================= */ #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) #define DO1_CASEIDT crc = crc_table[0][((int)crc ^ ((*buf++) | 0x20)) & 0xff] ^ (crc >> 8) #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 #define DO8_CASEIDT DO1_CASEIDT; DO1_CASEIDT; DO1_CASEIDT; DO1_CASEIDT; DO1_CASEIDT; DO1_CASEIDT; DO1_CASEIDT; DO1_CASEIDT /* ========================================================================= */ unsigned long ZEXPORT crc32(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { if (buf == Z_NULL) return 0UL; #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ #ifdef BYFOUR if (sizeof(void *) == sizeof(ptrdiff_t)) { u4 endian; endian = 1; if (*((unsigned char *)(&endian))) return crc32_little(crc, buf, len); else return crc32_big(crc, buf, len); } #endif /* BYFOUR */ crc = crc ^ 0xffffffffUL; while (len >= 8) { DO8; len -= 8; } if (len) do { DO1; } while (--len); return crc ^ 0xffffffffUL; } unsigned long ZEXPORT crc32_case_idt(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { if (buf == Z_NULL) return 0UL; crc = crc ^ 0xffffffffUL; while (len >= 8) { DO8_CASEIDT; len -= 8; } if (len) do { DO1_CASEIDT; } while (--len); return crc ^ 0xffffffffUL; } #ifdef BYFOUR /* ========================================================================= */ #define DOLIT4 c ^= *buf4++; \ c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 /* ========================================================================= */ local unsigned long crc32_little(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register u4 c; register const u4 FAR *buf4; c = (u4)crc; c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); len--; } buf4 = (const u4 FAR *)buf; while (len >= 32) { DOLIT32; len -= 32; } while (len >= 4) { DOLIT4; len -= 4; } buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); } while (--len); c = ~c; return (unsigned long)c; } /* ========================================================================= */ #define DOBIG4 c ^= *++buf4; \ c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 /* ========================================================================= */ local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register u4 c; register const u4 FAR *buf4; c = REV((u4)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const u4 FAR *)buf; buf4--; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf4++; buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(REV(c)); } #endif /* BYFOUR */
926064.c
/* Copyright (c) 2019 Peter Andersson (pelleplutt1976<at>gmail.com) */ /* MIT License (see ./LICENSE) */ #include "cli.h" #include "minio.h" #include "board.h" #include "cpu.h" #define _str(x) __str(x) #define __str(x) #x static int cli_info_app(int argc, const char **argv) { printf("target:\t%s %s/%s/%s@%s\n", _str(BUILD_INFO_TARGET_NAME), _str(BUILD_INFO_TARGET_ARCH), _str(BUILD_INFO_TARGET_FAMILY), _str(BUILD_INFO_TARGET_PROC), _str(BUILD_INFO_TARGET_BOARD)); printf("rev:\t%s %s on %s\n", _str(BUILD_INFO_GIT_COMMIT), _str(BUILD_INFO_GIT_TAG), _str(BUILD_INFO_GIT_BRANCH)) printf("build:\t%s@%s %s-%s %s\n", _str(BUILD_INFO_HOST_WHO), _str(BUILD_INFO_HOST_NAME), _str(BUILD_INFO_HOST_WHEN_DATE), _str(BUILD_INFO_HOST_WHEN_TIME), _str(BUILD_INFO_HOST_WHEN_EPOCH)); printf("cc:\t%s %s\n", _str(BUILD_INFO_CC_MACHINE), _str(BUILD_INFO_CC_VERSION)); return 0; } CLI_FUNCTION(cli_info_app, "info_app", ""); #if 0 // BUILD_INFO_TARGET_FAMILY == nrf52 // TODO this should be halified someway #include "nrf52.h" static int cli_info_arch(int argc, const char **argv) { printf("part:\t%x\n", NRF_FICR->INFO.PART); printf("var:\t%c%c%c%c\n", (NRF_FICR->INFO.VARIANT >> 24) &0xff, (NRF_FICR->INFO.VARIANT >> 16) &0xff, (NRF_FICR->INFO.VARIANT >> 8) &0xff, (NRF_FICR->INFO.VARIANT >> 0) &0xff ); printf("pack:\t%x\n", NRF_FICR->INFO.PACKAGE); printf("ram:\t%d kB\n", NRF_FICR->INFO.RAM); printf("flash:\t%d kB\n", NRF_FICR->INFO.FLASH); printf("dev-id:\t0x%08x%08x\n", NRF_FICR->DEVICEID[0], NRF_FICR->DEVICEID[1]); printf("pages:\t%d\n", NRF_FICR->CODESIZE); printf("pagesz:\t%d bytes\n", NRF_FICR->CODEPAGESIZE); return 0; } CLI_FUNCTION(cli_info_arch, "info_arch", ""); #endif
989826.c
/* market square 1 (south)*/ inherit "room/room"; reset(arg) { add_exit("south","/wizards/merak/areas/village/rooms/vgates"); add_exit("north","/wizards/merak/areas/village/rooms/msquare3"); short_desc = "Southern part of the market square"; long_desc = "You are standing on the southern part of the market \n" + "square of Chori village. The place is pretty empty,\n" + "only few merchants can be seen around selling their wares.\n" + "To the east you see an impressive looking statue of a knight\n" + "standing on the middle of the market square, while to the\n"+ "south you can see the village gates.\n"; }
612080.c
/* public domain sha224 implementation based on fips180-3 */ #include <stdint.h> #include "../sha224.h" extern void sha256_sum_n(void *, uint8_t *, int n); void sha224_init(void *ctx) { struct sha224 *s = ctx; s->len = 0; s->h[0] = 0xc1059ed8; s->h[1] = 0x367cd507; s->h[2] = 0x3070dd17; s->h[3] = 0xf70e5939; s->h[4] = 0xffc00b31; s->h[5] = 0x68581511; s->h[6] = 0x64f98fa7; s->h[7] = 0xbefa4fa4; } void sha224_sum(void *ctx, uint8_t md[SHA224_DIGEST_LENGTH]) { sha256_sum_n(ctx, md, 8); }
827628.c
#include <stdio.h> void main() { char arr[100]; int n, i; printf("Enter string : "); fgets(arr, sizeof(arr), stdin); arr[strlen(arr) - 1] = '\0'; n = strlen(arr); int difference = (int)'A' - (int)'a'; if (difference < 0) { difference = difference * -1; } for (i = 0; i < n; i++) { if ((int)arr[i] >= (int)'a' && (int)arr[i] <= (int)'z') { printf("%c", (int)arr[i] - difference); } else if ((int)arr[i] >= (int)'A' && (int)arr[i] <= (int)'Z') { printf("%c", (int)arr[i] + difference); } else { printf("%c", arr[i]); } } printf("\n\n"); }
595516.c
/* $NetBSD: gss_pseudo_random.c,v 1.1.1.2 2011/04/14 14:08:28 elric Exp $ */ /* * Copyright (c) 2007 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * 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 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 THE INSTITUTE 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 INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* Id */ #include "mech_locl.h" GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { struct _gss_context *ctx = (struct _gss_context *) context; gssapi_mech_interface m; OM_uint32 major_status; _mg_buffer_zero(prf_out); *minor_status = 0; if (ctx == NULL) { *minor_status = 0; return GSS_S_NO_CONTEXT; } m = ctx->gc_mech; if (m->gm_pseudo_random == NULL) return GSS_S_UNAVAILABLE; major_status = (*m->gm_pseudo_random)(minor_status, ctx->gc_ctx, prf_key, prf_in, desired_output_len, prf_out); if (major_status != GSS_S_COMPLETE) _gss_mg_error(m, major_status, *minor_status); return major_status; }
393268.c
// https://leetcode.com/problems/regular-expression-matching/description/ // https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html bool isMatch(char *text, char *regexp) { return matchhere(regexp, text); } int matchhere(char *regexp, char *text) { if (regexp[0] == '\0') return *text == '\0'; if (regexp[1] == '*') return matchstar(regexp[0], regexp + 2, text); if (*text != '\0' && (regexp[0] == '.' || regexp[0] == *text)) return matchhere(regexp + 1, text + 1); return 0; } int matchstar(int c, char *regexp, char *text) { do { if (matchhere(regexp, text)) return 1; } while (*text != '\0' && (*text++ == c || c == '.')); return 0; }
654835.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_05.c Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml Template File: sources-vasinks-05.tmpl.c */ /* * @description * CWE: 134 Uncontrolled Format String * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Copy a fixed string into data * Sinks: vfprintf * GoodSink: vfwprintf with a format string * BadSink : vfwprintf without a format string * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse) * * */ #include <stdarg.h> #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" /* The two variables below are not defined as "const", but are never assigned any other value, so a tool should be able to identify that reads of these will always return their initialized values. */ static int staticTrue = 1; /* true */ static int staticFalse = 0; /* false */ #ifndef OMITBAD static void badVaSinkB(wchar_t * data, ...) { { va_list args; va_start(args, data); /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ vfwprintf(stdout, data, args); va_end(args); } } void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_05_bad() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(staticTrue) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } if(staticTrue) { badVaSinkB(data, data); } } #endif /* OMITBAD */ #ifndef OMITGOOD static void goodB2G1VaSinkG(wchar_t * data, ...) { { va_list args; va_start(args, data); /* FIX: Specify the format disallowing a format string vulnerability */ vfwprintf(stdout, L"%s", args); va_end(args); } } /* goodB2G1() - use badsource and goodsink by changing the second staticTrue to staticFalse */ static void goodB2G1() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(staticTrue) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } if(staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { goodB2G1VaSinkG(data, data); } } static void goodB2G2VaSinkG(wchar_t * data, ...) { { va_list args; va_start(args, data); /* FIX: Specify the format disallowing a format string vulnerability */ vfwprintf(stdout, L"%s", args); va_end(args); } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(staticTrue) { { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } if(staticTrue) { goodB2G2VaSinkG(data, data); } } static void goodG2B1VaSinkB(wchar_t * data, ...) { { va_list args; va_start(args, data); /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ vfwprintf(stdout, data, args); va_end(args); } } /* goodG2B1() - use goodsource and badsink by changing the first staticTrue to staticFalse */ static void goodG2B1() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(staticFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a fixed string that does not contain a format specifier */ wcscpy(data, L"fixedstringtest"); } if(staticTrue) { goodG2B1VaSinkB(data, data); } } static void goodG2B2VaSinkB(wchar_t * data, ...) { { va_list args; va_start(args, data); /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ vfwprintf(stdout, data, args); va_end(args); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { wchar_t * data; wchar_t dataBuffer[100] = L""; data = dataBuffer; if(staticTrue) { /* FIX: Use a fixed string that does not contain a format specifier */ wcscpy(data, L"fixedstringtest"); } if(staticTrue) { goodG2B2VaSinkB(data, data); } } void CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_05_good() { goodG2B1(); goodG2B2(); goodB2G1(); goodB2G2(); } #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()..."); CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_05_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE134_Uncontrolled_Format_String__wchar_t_connect_socket_vfprintf_05_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
735202.c
/* This file has been autogenerated by Ivory * Compiler version 0.1.0.4 */ #include "input_tb_Decrypt_read_uart2self_monitor.h" void callback_input_tb_Decrypt_read_uart2self_handler(const struct SMACCM_DATA__UART_Packet_i *n_var0) { callback_from_smaccm_uart_2(n_var0); }