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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d90866d5701165eed2ff1c5bd1e2f20f452d6bf3 | 309 | c | C | C_programs/arrsum.c | rohit077/Let-Us-C | bc6f5f664df4613b2bd2fd7ff29b24120216f325 | [
"MIT"
] | null | null | null | C_programs/arrsum.c | rohit077/Let-Us-C | bc6f5f664df4613b2bd2fd7ff29b24120216f325 | [
"MIT"
] | null | null | null | C_programs/arrsum.c | rohit077/Let-Us-C | bc6f5f664df4613b2bd2fd7ff29b24120216f325 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main()
{
int a,b,sum;
printf("Enter the number of elements\n");
scanf("%d",&a);
int c[a];sum=0;
printf("Enter the elements\n");
for(b=0;b<a;b++){
scanf("%d",&c[b]);
}
for(b=0;b<a;b++){
sum+=c[b];
}
printf("Sum of all the elements of the array are=%d\n",sum);
return 0;
}
| 17.166667 | 61 | 0.572816 |
7f6e641b10d46feedf45b2beb8c7503fecf0b75c | 4,528 | h | C | Pods/Target Support Files/React/React-umbrella.h | anddygon/RNTest | 6b5d85c26ec0d59cc09b2ed5faab22ced0f8f2c1 | [
"MIT"
] | null | null | null | Pods/Target Support Files/React/React-umbrella.h | anddygon/RNTest | 6b5d85c26ec0d59cc09b2ed5faab22ced0f8f2c1 | [
"MIT"
] | null | null | null | Pods/Target Support Files/React/React-umbrella.h | anddygon/RNTest | 6b5d85c26ec0d59cc09b2ed5faab22ced0f8f2c1 | [
"MIT"
] | null | null | null | #ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "RCTAssert.h"
#import "RCTBridge+Private.h"
#import "RCTBridge.h"
#import "RCTBridgeDelegate.h"
#import "RCTBridgeMethod.h"
#import "RCTBridgeModule.h"
#import "RCTBundleURLProvider.h"
#import "RCTConvert.h"
#import "RCTDefines.h"
#import "RCTDisplayLink.h"
#import "RCTErrorCustomizer.h"
#import "RCTErrorInfo.h"
#import "RCTEventDispatcher.h"
#import "RCTFrameUpdate.h"
#import "RCTImageSource.h"
#import "RCTInvalidating.h"
#import "RCTJavaScriptExecutor.h"
#import "RCTJavaScriptLoader.h"
#import "RCTJSStackFrame.h"
#import "RCTKeyCommands.h"
#import "RCTLog.h"
#import "RCTModuleData.h"
#import "RCTModuleMethod.h"
#import "RCTNullability.h"
#import "RCTParserUtils.h"
#import "RCTPerformanceLogger.h"
#import "RCTRootView.h"
#import "RCTRootViewDelegate.h"
#import "RCTRootViewInternal.h"
#import "RCTTouchEvent.h"
#import "RCTTouchHandler.h"
#import "RCTURLRequestDelegate.h"
#import "RCTURLRequestHandler.h"
#import "RCTUtils.h"
#import "RCTWebSocketProxy.h"
#import "RCTWebSocketProxyDelegate.h"
#import "CSSLayout-internal.h"
#import "CSSLayout.h"
#import "CSSMacros.h"
#import "CSSNodeList.h"
#import "RCTJSCExecutor.h"
#import "RCTJSCWrapper.h"
#import "RCTAccessibilityManager.h"
#import "RCTAlertManager.h"
#import "RCTAppState.h"
#import "RCTAsyncLocalStorage.h"
#import "RCTClipboard.h"
#import "RCTDevLoadingView.h"
#import "RCTDevMenu.h"
#import "RCTEventEmitter.h"
#import "RCTExceptionsManager.h"
#import "RCTI18nManager.h"
#import "RCTI18nUtil.h"
#import "RCTKeyboardObserver.h"
#import "RCTRedBox.h"
#import "RCTSourceCode.h"
#import "RCTStatusBarManager.h"
#import "RCTTiming.h"
#import "RCTUIManager.h"
#import "RCTFPSGraph.h"
#import "RCTJSCProfiler.h"
#import "RCTMacros.h"
#import "RCTProfile.h"
#import "RCTActivityIndicatorView.h"
#import "RCTActivityIndicatorViewManager.h"
#import "RCTAnimationType.h"
#import "RCTAutoInsetsProtocol.h"
#import "RCTBorderDrawing.h"
#import "RCTBorderStyle.h"
#import "RCTComponent.h"
#import "RCTComponentData.h"
#import "RCTConvert+CoreLocation.h"
#import "RCTConvert+MapKit.h"
#import "RCTDatePicker.h"
#import "RCTDatePickerManager.h"
#import "RCTFont.h"
#import "RCTMap.h"
#import "RCTMapAnnotation.h"
#import "RCTMapManager.h"
#import "RCTMapOverlay.h"
#import "RCTModalHostView.h"
#import "RCTModalHostViewController.h"
#import "RCTModalHostViewManager.h"
#import "RCTNavigator.h"
#import "RCTNavigatorManager.h"
#import "RCTNavItem.h"
#import "RCTNavItemManager.h"
#import "RCTPicker.h"
#import "RCTPickerManager.h"
#import "RCTPointerEvents.h"
#import "RCTProgressViewManager.h"
#import "RCTRefreshControl.h"
#import "RCTRefreshControlManager.h"
#import "RCTRootShadowView.h"
#import "RCTScrollableProtocol.h"
#import "RCTScrollView.h"
#import "RCTScrollViewManager.h"
#import "RCTSegmentedControl.h"
#import "RCTSegmentedControlManager.h"
#import "RCTShadowView.h"
#import "RCTSlider.h"
#import "RCTSliderManager.h"
#import "RCTSwitch.h"
#import "RCTSwitchManager.h"
#import "RCTTabBar.h"
#import "RCTTabBarItem.h"
#import "RCTTabBarItemManager.h"
#import "RCTTabBarManager.h"
#import "RCTTextDecorationLineType.h"
#import "RCTView.h"
#import "RCTViewControllerProtocol.h"
#import "RCTViewManager.h"
#import "RCTWebView.h"
#import "RCTWebViewManager.h"
#import "RCTWrapperViewController.h"
#import "UIView+Private.h"
#import "UIView+React.h"
#import "RCTGIFImageDecoder.h"
#import "RCTImageBlurUtils.h"
#import "RCTImageCache.h"
#import "RCTImageEditingManager.h"
#import "RCTImageLoader.h"
#import "RCTImageStoreManager.h"
#import "RCTImageUtils.h"
#import "RCTImageView.h"
#import "RCTImageViewManager.h"
#import "RCTLocalAssetImageLoader.h"
#import "RCTResizeMode.h"
#import "RCTDataRequestHandler.h"
#import "RCTFileRequestHandler.h"
#import "RCTHTTPRequestHandler.h"
#import "RCTNetInfo.h"
#import "RCTNetworking.h"
#import "RCTNetworkTask.h"
#import "RCTRawTextManager.h"
#import "RCTShadowRawText.h"
#import "RCTShadowText.h"
#import "RCTText.h"
#import "RCTTextField.h"
#import "RCTTextFieldManager.h"
#import "RCTTextManager.h"
#import "RCTTextSelection.h"
#import "RCTTextView.h"
#import "RCTTextViewManager.h"
#import "RCTSRWebSocket.h"
#import "RCTWebSocketExecutor.h"
#import "RCTWebSocketManager.h"
#import "RCTWebSocketModule.h"
FOUNDATION_EXPORT double ReactVersionNumber;
FOUNDATION_EXPORT const unsigned char ReactVersionString[];
| 27.442424 | 59 | 0.790636 |
36d6a76662166d1e570afdc293252e0bcb39884a | 5,810 | h | C | Internetworking Distributed Project/Kernal/linux-3.6.3/arch/arm/plat-omap/include/plat/sdrc.h | supriyasingh01/github_basics | 8aa93f783cfe347368763ef31be5ab59fe8476a1 | [
"CC0-1.0"
] | null | null | null | Internetworking Distributed Project/Kernal/linux-3.6.3/arch/arm/plat-omap/include/plat/sdrc.h | supriyasingh01/github_basics | 8aa93f783cfe347368763ef31be5ab59fe8476a1 | [
"CC0-1.0"
] | 1 | 2022-02-16T20:50:59.000Z | 2022-02-19T21:16:04.000Z | Internetworking Distributed Project/Kernal/linux-3.6.3/arch/arm/plat-omap/include/plat/sdrc.h | supriyasingh01/github_basics | 8aa93f783cfe347368763ef31be5ab59fe8476a1 | [
"CC0-1.0"
] | null | null | null | #ifndef ____ASM_ARCH_SDRC_H
#define ____ASM_ARCH_SDRC_H
/*
* OMAP2/3 SDRC/SMS register definitions
*
* Copyright (C) 2007-2008 Texas Instruments, Inc.
* Copyright (C) 2007-2008 Nokia Corporation
*
* Tony Lindgren
* Paul Walmsley
* Richard Woodruff
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* SDRC register offsets - read/write with sdrc_{read,write}_reg() */
#define SDRC_SYSCONFIG 0x010
#define SDRC_CS_CFG 0x040
#define SDRC_SHARING 0x044
#define SDRC_ERR_TYPE 0x04C
#define SDRC_DLLA_CTRL 0x060
#define SDRC_DLLA_STATUS 0x064
#define SDRC_DLLB_CTRL 0x068
#define SDRC_DLLB_STATUS 0x06C
#define SDRC_POWER 0x070
#define SDRC_MCFG_0 0x080
#define SDRC_MR_0 0x084
#define SDRC_EMR2_0 0x08c
#define SDRC_ACTIM_CTRL_A_0 0x09c
#define SDRC_ACTIM_CTRL_B_0 0x0a0
#define SDRC_RFR_CTRL_0 0x0a4
#define SDRC_MANUAL_0 0x0a8
#define SDRC_MCFG_1 0x0B0
#define SDRC_MR_1 0x0B4
#define SDRC_EMR2_1 0x0BC
#define SDRC_ACTIM_CTRL_A_1 0x0C4
#define SDRC_ACTIM_CTRL_B_1 0x0C8
#define SDRC_RFR_CTRL_1 0x0D4
#define SDRC_MANUAL_1 0x0D8
#define SDRC_POWER_AUTOCOUNT_SHIFT 8
#define SDRC_POWER_AUTOCOUNT_MASK (0xffff << SDRC_POWER_AUTOCOUNT_SHIFT)
#define SDRC_POWER_CLKCTRL_SHIFT 4
#define SDRC_POWER_CLKCTRL_MASK (0x3 << SDRC_POWER_CLKCTRL_SHIFT)
#define SDRC_SELF_REFRESH_ON_AUTOCOUNT (0x2 << SDRC_POWER_CLKCTRL_SHIFT)
/*
* These values represent the number of memory clock cycles between
* autorefresh initiation. They assume 1 refresh per 64 ms (JEDEC), 8192
* rows per device, and include a subtraction of a 50 cycle window in the
* event that the autorefresh command is delayed due to other SDRC activity.
* The '| 1' sets the ARE field to send one autorefresh when the autorefresh
* counter reaches 0.
*
* These represent optimal values for common parts, it won't work for all.
* As long as you scale down, most parameters are still work, they just
* become sub-optimal. The RFR value goes in the opposite direction. If you
* don't adjust it down as your clock period increases the refresh interval
* will not be met. Setting all parameters for complete worst case may work,
* but may cut memory performance by 2x. Due to errata the DLLs need to be
* unlocked and their value needs run time calibration. A dynamic call is
* need for that as no single right value exists acorss production samples.
*
* Only the FULL speed values are given. Current code is such that rate
* changes must be made at DPLLoutx2. The actual value adjustment for low
* frequency operation will be handled by omap_set_performance()
*
* By having the boot loader boot up in the fastest L4 speed available likely
* will result in something which you can switch between.
*/
#define SDRC_RFR_CTRL_165MHz (0x00044c00 | 1)
#define SDRC_RFR_CTRL_133MHz (0x0003de00 | 1)
#define SDRC_RFR_CTRL_100MHz (0x0002da01 | 1)
#define SDRC_RFR_CTRL_110MHz (0x0002da01 | 1) /* Need to calc */
#define SDRC_RFR_CTRL_BYPASS (0x00005000 | 1) /* Need to calc */
/*
* SMS register access
*/
#define OMAP242X_SMS_REGADDR(reg) \
(void __iomem *)OMAP2_L3_IO_ADDRESS(OMAP2420_SMS_BASE + reg)
#define OMAP243X_SMS_REGADDR(reg) \
(void __iomem *)OMAP2_L3_IO_ADDRESS(OMAP243X_SMS_BASE + reg)
#define OMAP343X_SMS_REGADDR(reg) \
(void __iomem *)OMAP2_L3_IO_ADDRESS(OMAP343X_SMS_BASE + reg)
/* SMS register offsets - read/write with sms_{read,write}_reg() */
#define SMS_SYSCONFIG 0x010
#define SMS_ROT_CONTROL(context) (0x180 + 0x10 * context)
#define SMS_ROT_SIZE(context) (0x184 + 0x10 * context)
#define SMS_ROT_PHYSICAL_BA(context) (0x188 + 0x10 * context)
/* REVISIT: fill in other SMS registers here */
#ifndef __ASSEMBLER__
/**
* struct omap_sdrc_params - SDRC parameters for a given SDRC clock rate
* @rate: SDRC clock rate (in Hz)
* @actim_ctrla: Value to program to SDRC_ACTIM_CTRLA for this rate
* @actim_ctrlb: Value to program to SDRC_ACTIM_CTRLB for this rate
* @rfr_ctrl: Value to program to SDRC_RFR_CTRL for this rate
* @mr: Value to program to SDRC_MR for this rate
*
* This structure holds a pre-computed set of register values for the
* SDRC for a given SDRC clock rate and SDRAM chip. These are
* intended to be pre-computed and specified in an array in the board-*.c
* files. The structure is keyed off the 'rate' field.
*/
struct omap_sdrc_params {
unsigned long rate;
u32 actim_ctrla;
u32 actim_ctrlb;
u32 rfr_ctrl;
u32 mr;
};
#ifdef CONFIG_SOC_HAS_OMAP2_SDRC
void omap2_sdrc_init(struct omap_sdrc_params *sdrc_cs0,
struct omap_sdrc_params *sdrc_cs1);
#else
static inline void __init omap2_sdrc_init(struct omap_sdrc_params *sdrc_cs0,
struct omap_sdrc_params *sdrc_cs1) {};
#endif
int omap2_sdrc_get_params(unsigned long r,
struct omap_sdrc_params **sdrc_cs0,
struct omap_sdrc_params **sdrc_cs1);
void omap2_sms_save_context(void);
void omap2_sms_restore_context(void);
void omap2_sms_write_rot_control(u32 val, unsigned ctx);
void omap2_sms_write_rot_size(u32 val, unsigned ctx);
void omap2_sms_write_rot_physical_ba(u32 val, unsigned ctx);
#ifdef CONFIG_ARCH_OMAP2
struct memory_timings {
u32 m_type; /* ddr = 1, sdr = 0 */
u32 dll_mode; /* use lock mode = 1, unlock mode = 0 */
u32 slow_dll_ctrl; /* unlock mode, dll value for slow speed */
u32 fast_dll_ctrl; /* unlock mode, dll value for fast speed */
u32 base_cs; /* base chip select to use for calculations */
};
extern void omap2xxx_sdrc_init_params(u32 force_lock_to_unlock_mode);
struct omap_sdrc_params *rx51_get_sdram_timings(void);
u32 omap2xxx_sdrc_dll_is_unlocked(void);
u32 omap2xxx_sdrc_reprogram(u32 level, u32 force);
#endif /* CONFIG_ARCH_OMAP2 */
#endif /* __ASSEMBLER__ */
#endif
| 35.212121 | 77 | 0.771256 |
cfc41f7ff37a1575495f459866988c5a44988c09 | 2,172 | h | C | src/infra/es/CommandMetaData.h | huyumars/Gringofts | 9d30d166b35b2c84b432e510276dcf0dac51b494 | [
"Apache-2.0"
] | 84 | 2020-03-17T02:22:35.000Z | 2022-02-18T06:26:03.000Z | src/infra/es/CommandMetaData.h | huyumars/Gringofts | 9d30d166b35b2c84b432e510276dcf0dac51b494 | [
"Apache-2.0"
] | 47 | 2020-03-17T07:39:24.000Z | 2022-03-28T06:36:41.000Z | src/infra/es/CommandMetaData.h | huyumars/Gringofts | 9d30d166b35b2c84b432e510276dcf0dac51b494 | [
"Apache-2.0"
] | 23 | 2020-03-17T07:05:41.000Z | 2021-11-04T03:03:25.000Z | /************************************************************************
Copyright 2019-2020 eBay 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**************************************************************************/
#ifndef SRC_INFRA_ES_COMMANDMETADATA_H_
#define SRC_INFRA_ES_COMMANDMETADATA_H_
#include "../common_types.h"
#include "../grpc/RequestHandle.h"
#include "../util/TimeUtil.h"
#include "MetaData.h"
namespace gringofts {
/**
* Hold all the metadata of a #gringofts::Command instance.
* Fields in the metadata can be set after the command is created,
* e.g., Id is set when the command instance is being persisted.
*/
class CommandMetaData : public MetaData {
public:
CommandMetaData() = default;
explicit CommandMetaData(const es::CommandEntry &commandEntry) : MetaData(commandEntry) {}
~CommandMetaData() = default;
// getters
RequestHandle *getRequestHandle() const {
return mRequestHandle;
}
// setters
void setRequestHandle(RequestHandle *requestHandle) {
CommandMetaData::mRequestHandle = requestHandle;
}
void populateCommandEntry(es::CommandEntry *const commandEntry) const {
commandEntry->set_type(getType());
commandEntry->set_id(getId());
commandEntry->set_createdtimeinnanos(getCreatedTimeInNanos());
commandEntry->set_creatorid(getCreatorId());
commandEntry->set_groupid(getGroupId());
commandEntry->set_groupversion(getGroupVersion());
commandEntry->set_trackingcontext(getTrackingContext());
}
private:
/**
* To uniquely identify the corresponding request
*/
RequestHandle *mRequestHandle = nullptr;
};
} /// namespace gringofts
#endif // SRC_INFRA_ES_COMMANDMETADATA_H_
| 32.909091 | 92 | 0.706262 |
2c80442f6ee7f04670916bf5853b0cb0d4af12f7 | 15,160 | h | C | Util/OSM2ODR/src/utils/router/IntermodalRouter.h | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 5 | 2020-12-14T00:33:42.000Z | 2021-12-22T07:41:49.000Z | Util/OSM2ODR/src/utils/router/IntermodalRouter.h | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 2 | 2021-03-31T20:10:04.000Z | 2021-12-13T20:48:30.000Z | Util/OSM2ODR/src/utils/router/IntermodalRouter.h | adelbennaceur/carla | 4d6fefe73d38f0ffaef8ffafccf71245699fc5db | [
"MIT"
] | 4 | 2021-04-15T03:45:53.000Z | 2021-12-24T13:13:39.000Z | /****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2001-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file IntermodalRouter.h
/// @author Jakob Erdmann
/// @author Michael Behrisch
/// @date Mon, 03 March 2014
///
// The IntermodalRouter builds a special network and (delegates to a SUMOAbstractRouter)
/****************************************************************************/
#pragma once
#include <config.h>
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <utils/common/MsgHandler.h>
#include <utils/common/SUMOTime.h>
#include <utils/common/ToString.h>
#include <utils/iodevices/OutputDevice.h>
#include "SUMOAbstractRouter.h"
#include "DijkstraRouter.h"
#include "AStarRouter.h"
#include "IntermodalNetwork.h"
#include "EffortCalculator.h"
#include "CarEdge.h"
#include "StopEdge.h"
#include "PedestrianRouter.h"
//#define IntermodalRouter_DEBUG_ROUTES
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class IntermodalRouter
* The router for pedestrians (on a bidirectional network of sidewalks and crossings)
*/
template<class E, class L, class N, class V>
class IntermodalRouter : public SUMOAbstractRouter<E, IntermodalTrip<E, N, V> > {
public:
typedef IntermodalNetwork<E, L, N, V> Network;
private:
typedef void(*CreateNetCallback)(IntermodalRouter <E, L, N, V>&);
typedef IntermodalEdge<E, L, N, V> _IntermodalEdge;
typedef IntermodalTrip<E, N, V> _IntermodalTrip;
typedef SUMOAbstractRouter<_IntermodalEdge, _IntermodalTrip> _InternalRouter;
typedef DijkstraRouter<_IntermodalEdge, _IntermodalTrip> _InternalDijkstra;
typedef AStarRouter<_IntermodalEdge, _IntermodalTrip> _InternalAStar;
public:
struct TripItem {
TripItem(const std::string& _line = "") :
line(_line), intended(_line) {}
std::string line;
std::string vType = "";
std::string destStop = "";
std::string intended; // intended public transport vehicle id
double depart = -1.; // intended public transport departure
std::vector<const E*> edges;
double traveltime = 0.;
double cost = 0.;
double length = 0.;
double departPos = INVALID_DOUBLE;
double arrivalPos = INVALID_DOUBLE;
std::string description = "";
};
/// Constructor
IntermodalRouter(CreateNetCallback callback, const int carWalkTransfer, const std::string& routingAlgorithm,
const int routingMode = 0, EffortCalculator* calc = nullptr) :
SUMOAbstractRouter<E, _IntermodalTrip>("IntermodalRouter", true, nullptr, nullptr, false, false),
myAmClone(false), myInternalRouter(nullptr), myIntermodalNet(nullptr),
myCallback(callback), myCarWalkTransfer(carWalkTransfer), myRoutingAlgorithm(routingAlgorithm),
myRoutingMode(routingMode), myExternalEffort(calc) {
}
/// Destructor
virtual ~IntermodalRouter() {
delete myInternalRouter;
if (!myAmClone) {
delete myIntermodalNet;
}
}
SUMOAbstractRouter<E, _IntermodalTrip>* clone() {
createNet();
return new IntermodalRouter<E, L, N, V>(myIntermodalNet, myCarWalkTransfer, myRoutingAlgorithm, myRoutingMode, myExternalEffort);
}
int getCarWalkTransfer() const {
return myCarWalkTransfer;
}
/** @brief Builds the route between the given edges using the minimum effort at the given time
The definition of the effort depends on the wished routing scheme */
bool compute(const E* from, const E* to, const double departPos, const double arrivalPos,
const std::string stopID, const double speed,
const V* const vehicle, const SVCPermissions modeSet, const SUMOTime msTime,
std::vector<TripItem>& into, const double externalFactor = 0.) {
createNet();
_IntermodalTrip trip(from, to, departPos, arrivalPos, speed, msTime, 0, vehicle, modeSet, myExternalEffort, externalFactor);
std::vector<const _IntermodalEdge*> intoEdges;
//std::cout << "compute from=" << from->getID() << " to=" << to->getID() << " dPos=" << departPos << " aPos=" << arrivalPos << " stopID=" << stopID << " speed=" << speed << " veh=" << Named::getIDSecure(vehicle) << " modeSet=" << modeSet << " t=" << msTime << " iFrom=" << myIntermodalNet->getDepartEdge(from, trip.departPos)->getID() << " iTo=" << (stopID != "" ? myIntermodalNet->getStopEdge(stopID) : myIntermodalNet->getArrivalEdge(to, trip.arrivalPos))->getID() << "\n";
const bool success = myInternalRouter->compute(myIntermodalNet->getDepartEdge(from, trip.departPos),
stopID != "" ? myIntermodalNet->getStopEdge(stopID) : myIntermodalNet->getArrivalEdge(to, trip.arrivalPos),
&trip, msTime, intoEdges);
if (success) {
std::string lastLine = "";
double time = STEPS2TIME(msTime);
double effort = 0.;
double length = 0.;
const _IntermodalEdge* prev = nullptr;
for (const _IntermodalEdge* iEdge : intoEdges) {
if (iEdge->includeInRoute(false)) {
if (iEdge->getLine() == "!stop") {
if (into.size() > 0) {
// previous stage ends at stop
into.back().destStop = iEdge->getID();
if (myExternalEffort != nullptr) {
into.back().description = myExternalEffort->output(iEdge->getNumericalID());
}
if (lastLine == "!ped") {
lastLine = ""; // a stop always starts a new trip item
}
} else {
// trip starts at stop
lastLine = "";
into.push_back(TripItem("!stop"));
into.back().destStop = iEdge->getID();
}
} else {
if (iEdge->getLine() != lastLine) {
lastLine = iEdge->getLine();
if (lastLine == "!car") {
into.push_back(TripItem(vehicle->getID()));
into.back().vType = vehicle->getParameter().vtypeid;
} else if (lastLine == "!ped") {
into.push_back(TripItem());
} else {
into.push_back(TripItem(lastLine));
into.back().depart = iEdge->getIntended(time, into.back().intended);
}
into.back().departPos = iEdge->getStartPos();
}
if (into.back().edges.empty() || into.back().edges.back() != iEdge->getEdge()) {
into.back().edges.push_back(iEdge->getEdge());
into.back().arrivalPos = iEdge->getEndPos();
}
}
}
const double prevTime = time, prevEffort = effort, prevLength = length;
myInternalRouter->updateViaCost(prev, iEdge, &trip, time, effort, length);
prev = iEdge;
if (!into.empty()) {
into.back().traveltime += time - prevTime;
into.back().cost += effort - prevEffort;
into.back().length += length - prevLength;
if (into.back().depart < 0) {
into.back().depart = prevTime;
}
}
}
}
#ifdef IntermodalRouter_DEBUG_ROUTES
double time = STEPS2TIME(msTime);
for (const _IntermodalEdge* iEdge : intoEdges) {
const double edgeEffort = myInternalRouter->getEffort(iEdge, &trip, time);
time += edgeEffort;
std::cout << iEdge->getID() << "(" << iEdge->getLine() << "): " << edgeEffort << std::endl;
}
std::cout << TIME2STEPS(msTime) << " trip from " << from->getID() << " to " << (to != nullptr ? to->getID() : stopID)
<< " departPos=" << trip.departPos
<< " arrivalPos=" << trip.arrivalPos
<< " modes=" << getVehicleClassNames(modeSet)
<< " edges=" << toString(intoEdges)
// << " resultEdges=" << toString(into)
<< " time=" << time
<< "\n";
#endif
return success;
}
/** @brief Builds the route between the given edges using the minimum effort at the given time
The definition of the effort depends on the wished routing scheme */
bool compute(const E*, const E*, const _IntermodalTrip* const,
SUMOTime, std::vector<const E*>&, bool) {
throw ProcessError("Do not use this method");
}
void prohibit(const std::vector<E*>& toProhibit) {
createNet();
std::vector<_IntermodalEdge*> toProhibitPE;
for (typename std::vector<E*>::const_iterator it = toProhibit.begin(); it != toProhibit.end(); ++it) {
toProhibitPE.push_back(myIntermodalNet->getBothDirections(*it).first);
toProhibitPE.push_back(myIntermodalNet->getBothDirections(*it).second);
toProhibitPE.push_back(myIntermodalNet->getCarEdge(*it));
}
myInternalRouter->prohibit(toProhibitPE);
}
void writeNetwork(OutputDevice& dev) {
createNet();
for (_IntermodalEdge* e : myIntermodalNet->getAllEdges()) {
dev.openTag(SUMO_TAG_EDGE);
dev.writeAttr(SUMO_ATTR_ID, e->getID());
dev.writeAttr(SUMO_ATTR_LINE, e->getLine());
dev.writeAttr(SUMO_ATTR_LENGTH, e->getLength());
dev.writeAttr("successors", toString(e->getSuccessors(SVC_IGNORING)));
dev.closeTag();
}
}
void writeWeights(OutputDevice& dev) {
createNet();
_IntermodalTrip trip(nullptr, nullptr, 0., 0., DEFAULT_PEDESTRIAN_SPEED, 0, 0, nullptr, SVC_PASSENGER | SVC_BICYCLE | SVC_BUS);
for (_IntermodalEdge* e : myIntermodalNet->getAllEdges()) {
dev.openTag(SUMO_TAG_EDGE);
dev.writeAttr(SUMO_ATTR_ID, e->getID());
dev.writeAttr("traveltime", e->getTravelTime(&trip, 0.));
dev.writeAttr("effort", e->getEffort(&trip, 0.));
dev.closeTag();
}
}
Network* getNetwork() const {
return myIntermodalNet;
}
EffortCalculator* getExternalEffort() const {
return myExternalEffort;
}
private:
IntermodalRouter(Network* net, const int carWalkTransfer, const std::string& routingAlgorithm,
const int routingMode, EffortCalculator* calc) :
SUMOAbstractRouter<E, _IntermodalTrip>("IntermodalRouterClone", true, nullptr, nullptr, false, false), myAmClone(true),
myInternalRouter(new _InternalDijkstra(net->getAllEdges(), true,
gWeightsRandomFactor > 1 ? & _IntermodalEdge::getTravelTimeStaticRandomized : & _IntermodalEdge::getTravelTimeStatic)),
myIntermodalNet(net), myCarWalkTransfer(carWalkTransfer), myRoutingAlgorithm(routingAlgorithm), myRoutingMode(routingMode), myExternalEffort(calc) {}
static inline double getCombined(const _IntermodalEdge* const edge, const _IntermodalTrip* const trip, double time) {
return edge->getTravelTime(trip, time) + trip->externalFactor * trip->calc->getEffort(edge->getNumericalID());
}
inline void createNet() {
if (myIntermodalNet == nullptr) {
myIntermodalNet = new Network(E::getAllEdges(), false, myCarWalkTransfer);
myIntermodalNet->addCarEdges(E::getAllEdges());
myCallback(*this);
switch (myRoutingMode) {
case 0:
if (myRoutingAlgorithm == "astar") {
myInternalRouter = new _InternalAStar(myIntermodalNet->getAllEdges(), true,
gWeightsRandomFactor > 1 ? &_IntermodalEdge::getTravelTimeStaticRandomized : &_IntermodalEdge::getTravelTimeStatic, nullptr, true);
} else {
myInternalRouter = new _InternalDijkstra(myIntermodalNet->getAllEdges(), true,
gWeightsRandomFactor > 1 ? &_IntermodalEdge::getTravelTimeStaticRandomized : &_IntermodalEdge::getTravelTimeStatic, nullptr, false, nullptr, true);
}
break;
case 1:
myInternalRouter = new _InternalDijkstra(myIntermodalNet->getAllEdges(), true, &_IntermodalEdge::getTravelTimeAggregated, nullptr, false, nullptr, true);
break;
case 2:
myInternalRouter = new _InternalDijkstra(myIntermodalNet->getAllEdges(), true, &_IntermodalEdge::getEffortStatic, &_IntermodalEdge::getTravelTimeStatic, false, nullptr, true);
break;
case 3:
if (myExternalEffort != nullptr) {
std::vector<std::string> edgeLines;
for (const auto e : myIntermodalNet->getAllEdges()) {
edgeLines.push_back(e->getLine());
}
myExternalEffort->init(edgeLines);
}
myInternalRouter = new _InternalDijkstra(myIntermodalNet->getAllEdges(), true, &getCombined, &_IntermodalEdge::getTravelTimeStatic, false, myExternalEffort, true);
break;
}
}
}
private:
const bool myAmClone;
_InternalRouter* myInternalRouter;
Network* myIntermodalNet;
CreateNetCallback myCallback;
const int myCarWalkTransfer;
const std::string myRoutingAlgorithm;
const int myRoutingMode;
EffortCalculator* const myExternalEffort;
private:
/// @brief Invalidated assignment operator
IntermodalRouter& operator=(const IntermodalRouter& s);
};
| 48.903226 | 483 | 0.573351 |
82be6be03de54f44036aff948b9f4ca5994de1cc | 554 | h | C | JDCloudOCSDKIotlink/JDCloudOCSDKIotlink.h | jdcloud-api/jdcloud-sdk-ios-oc | 8d653a17b0a4675f8dd984b360955721cdd15702 | [
"Apache-2.0"
] | null | null | null | JDCloudOCSDKIotlink/JDCloudOCSDKIotlink.h | jdcloud-api/jdcloud-sdk-ios-oc | 8d653a17b0a4675f8dd984b360955721cdd15702 | [
"Apache-2.0"
] | null | null | null | JDCloudOCSDKIotlink/JDCloudOCSDKIotlink.h | jdcloud-api/jdcloud-sdk-ios-oc | 8d653a17b0a4675f8dd984b360955721cdd15702 | [
"Apache-2.0"
] | null | null | null |
#ifdef __OBJC__
#import<Foundation/Foundation.h>
#endif
//! Project version number for JDCloudOCSDKIotlink.
FOUNDATION_EXPORT double JDCloudOCSDKIotlinkVersionNumber;
//! Project version string for JDCloudOCSDKIotlink.
FOUNDATION_EXPORT const unsigned char JDCloudOCSDKIotlinkVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <JDCloudOCSDKIotlink/PublicHeader.h>
#import "IotlinkModel.h"
#import "IotlinkApiModel.h"
#import "IotlinkClient.h"
#import "IotlinkExecutor.h"
| 25.181818 | 144 | 0.814079 |
c9075a7f74d5d8c7edf70d53d2ea0784eb7ec973 | 6,882 | h | C | cpp_backend/inc/Eigen/src/Core/util/IndexedViewHelper.h | Etbelo/RoadNetworkValueIteration | 8d28cd0d166c9878714c1fd7682ce7e169626977 | [
"MIT"
] | 4 | 2021-11-12T08:20:09.000Z | 2022-01-06T19:37:44.000Z | cpp_backend/inc/Eigen/src/Core/util/IndexedViewHelper.h | Etbelo/RoadNetworkValueIteration | 8d28cd0d166c9878714c1fd7682ce7e169626977 | [
"MIT"
] | null | null | null | cpp_backend/inc/Eigen/src/Core/util/IndexedViewHelper.h | Etbelo/RoadNetworkValueIteration | 8d28cd0d166c9878714c1fd7682ce7e169626977 | [
"MIT"
] | null | null | null | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2017 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_INDEXED_VIEW_HELPER_H
#define EIGEN_INDEXED_VIEW_HELPER_H
namespace Eigen {
namespace internal {
struct symbolic_last_tag {};
}
/** \var last
* \ingroup Core_Module
*
* Can be used as a parameter to Eigen::seq and Eigen::seqN functions to symbolically reference the last element/row/columns
* of the underlying vector or matrix once passed to DenseBase::operator()(const RowIndices&, const ColIndices&).
*
* This symbolic placeholder supports standard arithmetic operations.
*
* A typical usage example would be:
* \code
* using namespace Eigen;
* using Eigen::last;
* VectorXd v(n);
* v(seq(2,last-2)).setOnes();
* \endcode
*
* \sa end
*/
static const symbolic::SymbolExpr<internal::symbolic_last_tag> last; // PLEASE use Eigen::last instead of Eigen::placeholders::last
/** \var lastp1
* \ingroup Core_Module
*
* Can be used as a parameter to Eigen::seq and Eigen::seqN functions to symbolically
* reference the last+1 element/row/columns of the underlying vector or matrix once
* passed to DenseBase::operator()(const RowIndices&, const ColIndices&).
*
* This symbolic placeholder supports standard arithmetic operations.
* It is essentially an alias to last+fix<1>.
*
* \sa last
*/
#ifdef EIGEN_PARSED_BY_DOXYGEN
static const auto lastp1 = last+fix<1>;
#else
// Using a FixedExpr<1> expression is important here to make sure the compiler
// can fully optimize the computation starting indices with zero overhead.
static const symbolic::AddExpr<symbolic::SymbolExpr<internal::symbolic_last_tag>,symbolic::ValueExpr<Eigen::internal::FixedInt<1> > > lastp1(last+fix<1>());
#endif
namespace internal {
// Replace symbolic last/end "keywords" by their true runtime value
inline Index eval_expr_given_size(Index x, Index /* size */) { return x; }
template<int N>
FixedInt<N> eval_expr_given_size(FixedInt<N> x, Index /*size*/) { return x; }
template<typename Derived>
Index eval_expr_given_size(const symbolic::BaseExpr<Derived> &x, Index size)
{
return x.derived().eval(last=size-1);
}
// Extract increment/step at compile time
template<typename T, typename EnableIf = void> struct get_compile_time_incr {
enum { value = UndefinedIncr };
};
// Analogue of std::get<0>(x), but tailored for our needs.
template<typename T>
EIGEN_CONSTEXPR Index first(const T& x) EIGEN_NOEXCEPT { return x.first(); }
// IndexedViewCompatibleType/makeIndexedViewCompatible turn an arbitrary object of type T into something usable by MatrixSlice
// The generic implementation is a no-op
template<typename T,int XprSize,typename EnableIf=void>
struct IndexedViewCompatibleType {
typedef T type;
};
template<typename T,typename Q>
const T& makeIndexedViewCompatible(const T& x, Index /*size*/, Q) { return x; }
//--------------------------------------------------------------------------------
// Handling of a single Index
//--------------------------------------------------------------------------------
struct SingleRange {
enum {
SizeAtCompileTime = 1
};
SingleRange(Index val) : m_value(val) {}
Index operator[](Index) const { return m_value; }
static EIGEN_CONSTEXPR Index size() EIGEN_NOEXCEPT { return 1; }
Index first() const EIGEN_NOEXCEPT { return m_value; }
Index m_value;
};
template<> struct get_compile_time_incr<SingleRange> {
enum { value = 1 }; // 1 or 0 ??
};
// Turn a single index into something that looks like an array (i.e., that exposes a .size(), and operator[](int) methods)
template<typename T, int XprSize>
struct IndexedViewCompatibleType<T,XprSize,typename internal::enable_if<internal::is_integral<T>::value>::type> {
// Here we could simply use Array, but maybe it's less work for the compiler to use
// a simpler wrapper as SingleRange
//typedef Eigen::Array<Index,1,1> type;
typedef SingleRange type;
};
template<typename T, int XprSize>
struct IndexedViewCompatibleType<T, XprSize, typename enable_if<symbolic::is_symbolic<T>::value>::type> {
typedef SingleRange type;
};
template<typename T>
typename enable_if<symbolic::is_symbolic<T>::value,SingleRange>::type
makeIndexedViewCompatible(const T& id, Index size, SpecializedType) {
return eval_expr_given_size(id,size);
}
//--------------------------------------------------------------------------------
// Handling of all
//--------------------------------------------------------------------------------
struct all_t { all_t() {} };
// Convert a symbolic 'all' into a usable range type
template<int XprSize>
struct AllRange {
enum { SizeAtCompileTime = XprSize };
AllRange(Index size = XprSize) : m_size(size) {}
EIGEN_CONSTEXPR Index operator[](Index i) const EIGEN_NOEXCEPT { return i; }
EIGEN_CONSTEXPR Index size() const EIGEN_NOEXCEPT { return m_size.value(); }
EIGEN_CONSTEXPR Index first() const EIGEN_NOEXCEPT { return 0; }
variable_if_dynamic<Index,XprSize> m_size;
};
template<int XprSize>
struct IndexedViewCompatibleType<all_t,XprSize> {
typedef AllRange<XprSize> type;
};
template<typename XprSizeType>
inline AllRange<get_fixed_value<XprSizeType>::value> makeIndexedViewCompatible(all_t , XprSizeType size, SpecializedType) {
return AllRange<get_fixed_value<XprSizeType>::value>(size);
}
template<int Size> struct get_compile_time_incr<AllRange<Size> > {
enum { value = 1 };
};
} // end namespace internal
/** \var all
* \ingroup Core_Module
* Can be used as a parameter to DenseBase::operator()(const RowIndices&, const ColIndices&) to index all rows or columns
*/
static const Eigen::internal::all_t all; // PLEASE use Eigen::all instead of Eigen::placeholders::all
namespace placeholders {
typedef symbolic::SymbolExpr<internal::symbolic_last_tag> last_t;
typedef symbolic::AddExpr<symbolic::SymbolExpr<internal::symbolic_last_tag>,symbolic::ValueExpr<Eigen::internal::FixedInt<1> > > end_t;
typedef Eigen::internal::all_t all_t;
EIGEN_DEPRECATED static const all_t all = Eigen::all; // PLEASE use Eigen::all instead of Eigen::placeholders::all
EIGEN_DEPRECATED static const last_t last = Eigen::last; // PLEASE use Eigen::last instead of Eigen::placeholders::last
EIGEN_DEPRECATED static const end_t end = Eigen::lastp1; // PLEASE use Eigen::lastp1 instead of Eigen::placeholders::end
}
} // end namespace Eigen
#endif // EIGEN_INDEXED_VIEW_HELPER_H
| 36.802139 | 157 | 0.68701 |
a936f4faa8ac6ba7391fab9ed8f17552353c1b86 | 1,768 | h | C | quic/state/QuicStreamUtilities.h | xujiasci/mvfst | eebee8dac6b98c27b5c6037371ade7884f3d847d | [
"MIT"
] | 1 | 2021-08-20T07:27:05.000Z | 2021-08-20T07:27:05.000Z | quic/state/QuicStreamUtilities.h | xujiasci/mvfst | eebee8dac6b98c27b5c6037371ade7884f3d847d | [
"MIT"
] | null | null | null | quic/state/QuicStreamUtilities.h | xujiasci/mvfst | eebee8dac6b98c27b5c6037371ade7884f3d847d | [
"MIT"
] | 1 | 2021-08-20T07:27:07.000Z | 2021-08-20T07:27:07.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
#include <quic/state/StateData.h>
namespace quic {
/**
* Returns whether the given StreamId identifies a client stream.
*/
bool isClientStream(StreamId stream);
/**
* Returns whether the given StreamId identifies a server stream.
*/
bool isServerStream(StreamId stream);
/**
* Returns whether the given StreamId identifies a unidirectional stream.
*/
bool isUnidirectionalStream(StreamId stream);
/**
* Returns whether the given StreamId identifies a bidirectional stream.
*/
bool isBidirectionalStream(StreamId stream);
/**
* Returns whether the given QuicNodeType and StreamId indicate a sending
* stream, i.e., a stream which only sends data. Note that a bidirectional
* stream is NOT considered a sending stream by this definition.
*/
bool isSendingStream(QuicNodeType nodeType, StreamId stream);
/**
* Returns whether the given QuicNodeType and StreamId indicate a receiving
* stream, i.e., a stream which only receives data. Note that a bidirectional
* stream is NOT considered a receiving stream by this definition.
*/
bool isReceivingStream(QuicNodeType nodeType, StreamId stream);
/**
* Returns whether the given QuicNodeType and StreamId indicates the stream is
* a local stream (i.e. the stream initiator matches the node type).
*/
bool isLocalStream(QuicNodeType nodeType, StreamId stream);
/**
* Returns whether the given QuicNodeType and StreamId indicates the stream is
* a remote stream (i.e. the stream initiator doesn't match the node type).
*/
bool isRemoteStream(QuicNodeType nodeType, StreamId stream);
} // namespace quic
| 29.466667 | 78 | 0.759615 |
6529bdd22d9d1eee6549753d6dac5c498d3ecc88 | 275 | h | C | examples/QtRichDataList/src/QtDemo.h | Qt-Widgets/QtExtraWidgets-Vertical-Horizontal-Line-Button-Label--List-Circular-Round-bar | 908fdf00b213baabf5ca1ab7e6c5ee48a21bc257 | [
"BSD-2-Clause"
] | 1 | 2021-01-10T06:52:27.000Z | 2021-01-10T06:52:27.000Z | examples/QtRichDataList/src/QtDemo.h | Qt-Widgets/QtExtraWidgets-Vertical-Horizontal-Line-Button-Label--List-Circular-Round-bar | 908fdf00b213baabf5ca1ab7e6c5ee48a21bc257 | [
"BSD-2-Clause"
] | null | null | null | examples/QtRichDataList/src/QtDemo.h | Qt-Widgets/QtExtraWidgets-Vertical-Horizontal-Line-Button-Label--List-Circular-Round-bar | 908fdf00b213baabf5ca1ab7e6c5ee48a21bc257 | [
"BSD-2-Clause"
] | null | null | null | #ifndef _QT_DEMO
#define _QT_DEMO
#include <QtCore>
#include <QApplication>
#include "MainWindow.h"
class QtDemo : public QApplication
{
Q_OBJECT
public:
QtDemo(int argc, char* argv[]);
~QtDemo();
void ShowUI();
private:
MainWindow window;
};
#endif | 14.473684 | 35 | 0.676364 |
653c57a35c5017f404ddf98058c790f1dea25d89 | 1,834 | h | C | AlimCap/Packetyzer/cWinpcapCapture.h | 746396173/QQCapTools | f3990dd6edf60a1c8bcc84330653481c17869e48 | [
"MIT"
] | 10 | 2019-09-29T01:47:20.000Z | 2020-05-26T14:06:02.000Z | AlimCap/Packetyzer/cWinpcapCapture.h | kuustudio/QQCapTools | f3990dd6edf60a1c8bcc84330653481c17869e48 | [
"MIT"
] | null | null | null | AlimCap/Packetyzer/cWinpcapCapture.h | kuustudio/QQCapTools | f3990dd6edf60a1c8bcc84330653481c17869e48 | [
"MIT"
] | 6 | 2020-06-23T08:37:29.000Z | 2022-02-21T16:02:44.000Z | /*
*
* Copyright (C) 2013 Anwar Mohamed <anwarelmakrahy[at]gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to Anwar Mohamed
* anwarelmakrahy[at]gmail.com
*
*/
#pragma once
#include "Packetyzer.h"
using namespace Packetyzer::Traffic::Connections;
struct NETWORK_ADAPTERS_CAPTURE
{
CHAR Name[200];
CHAR ID[200];
};
typedef void(*packet_call_handler)(LPVOID uParam, const u_char *pkt_data, unsigned int len);
class DLLEXPORT Packetyzer::Capture::cWinpcapCapture
{
//BOOL CheckAdapter(UINT id);
//BOOL InitializeAdaptersList();
void AnalyzeTraffic();
#define LINE_LEN 16
pcap_if_t *alldevs, *d;
pcap_t *fp;
int res;
struct pcap_pkthdr * PacketHeader;
const u_char * PacketData;
CHAR errbuf[PCAP_ERRBUF_SIZE];
BOOL InitializeAdapters();
public:
BOOL isReady;
HANDLE m_hSnifferEvent;
HANDLE m_hListenEvent;
BOOL CapturePackets(UINT AdapterIndex, UINT MaxNumOfPackets, const CHAR* Filter = NULL);
BOOL CapturePackets(LPVOID uParam, packet_call_handler pFunc, UINT AdapterIndex, UINT MaxNumOfPackets, const CHAR* Filter);
BOOL StopCapture();
NETWORK_ADAPTERS_CAPTURE *Adapters;
UINT nAdapters;
//cPacket* CapturedPackets;
UINT nCapturedPackets;
cTraffic Traffic;
cWinpcapCapture();
~cWinpcapCapture();
};
| 26.970588 | 124 | 0.756816 |
45b29bbbd9ba9802d388ddd58277a0e16570022a | 7,226 | h | C | sourceCode/dotNet4.6/vb/language/shared/pageheap.h | csoap/csoap.github.io | 2a8db44eb63425deff147652b65c5912f065334e | [
"Apache-2.0"
] | 5 | 2017-03-03T02:13:16.000Z | 2021-08-18T09:59:56.000Z | sourceCode/dotNet4.6/vb/language/shared/pageheap.h | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | null | null | null | sourceCode/dotNet4.6/vb/language/shared/pageheap.h | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | 4 | 2016-11-15T05:20:12.000Z | 2021-11-13T16:32:11.000Z | //-------------------------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Implements the page manager for our NorlsAllocator instances
//
//-------------------------------------------------------------------------------------------------
#pragma once
/* Page allocation heap. Allocates and frees pages
* or groups of pages. Allocation must be a multiple
* of the system page size. Memory is not zeroed.
*/
#define SPREAD_ALLOCATIONS // allocate after the previous allocation instead of looking from the
// beginning of each arena
#define PAGES_PER_ARENA 128 // 4k system page size => 128*4k = 512KB per arena
#define BIGALLOC_SIZE (128 * 1024) // more than this alloc (128KB) is not done from an arena.
#define DWORD_BIT_SHIFT 5 // log2 of bits in a DWORD.
#define BITS_DWORD (1 << DWORD_BIT_SHIFT)
#define DWORD_BIT_MASK (BITS_DWORD - 1)
extern size_t GetSystemPageSize();
class PageHeap
{
public:
enum PageArenaType
{
Normal,
LargeAllocation,
SinglePageAllocation
};
// Store information about a memory arena we allocate pages from.
struct PageArena
{
PageArena* nextArena; // the arena.
void* pages; // the pages in the arena.
size_t size; // size of the arena.
PageArenaType type; // large allocs and single page allocs have special cased codepaths
DWORD used[PAGES_PER_ARENA / BITS_DWORD]; // bit map of in-use pages in this arena.
DWORD committed[PAGES_PER_ARENA / BITS_DWORD]; // bit map of committed pages in this arena.
bool OwnsPage(const void* p) const
{
return (p >= pages && p < (BYTE*)pages + size);
}
bool IsPageCommitted (unsigned iPage) const
{
return TestPage(committed, iPage);
}
bool IsPageUsed (unsigned iPage) const
{
return TestPage(used, iPage);
}
void MarkPageUsed (unsigned iPage)
{
SetPage(used, iPage);
}
void MarkPageCommitted (unsigned iPage)
{
SetPage(committed, iPage);
}
void ClearPageUsed (unsigned iPage)
{
ClearPage(used, iPage);
}
void ClearPageCommitted (unsigned iPage)
{
ClearPage(committed, iPage);
}
bool HasUsedPages() const;
size_t GetAddressSpaceSize() const
{
return size;
}
void FreeAddressSpace();
void* AllocPages(unsigned int cPages, PageHeap& parent);
void* AllocPagesHelper(int iPage, unsigned int cPages, PageHeap& parent);
protected:
#ifdef SPREAD_ALLOCATIONS
int m_iStartNextAlloc; // used in PageArena::AllocPages
#endif
int LookForPages(unsigned int cPages, int indexPageBegin, int indexLastValidPage);
void SetPage(_Out_cap_(PAGES_PER_ARENA >> DWORD_BIT_SHIFT) DWORD bitvector[], unsigned index)
{
VSASSERT(index < PAGES_PER_ARENA, "Invalid");
bitvector[index >> DWORD_BIT_SHIFT] |= (1 << (index & DWORD_BIT_MASK));
}
bool TestPage(DWORD const bitvector[], unsigned index) const
{
VSASSERT(index < PAGES_PER_ARENA, "Invalid");
return bitvector[index >> DWORD_BIT_SHIFT] & (1 << (index & DWORD_BIT_MASK));
}
void ClearPage(_Out_cap_(PAGES_PER_ARENA >> DWORD_BIT_SHIFT) DWORD bitvector[], unsigned index)
{
VSASSERT(index < PAGES_PER_ARENA, "Invalid");
bitvector[index >> DWORD_BIT_SHIFT] &= ~(1 << (index & DWORD_BIT_MASK));
}
};
struct SinglePageArena : public PageArena
{
int freePageStack[PAGES_PER_ARENA]; // stack of free pages available in singlePageAlloc case
int topOfFreePageStack; // -1 when there are no free pages, will initially be PAGES_PER_ARENA -1
SinglePageArena();
int NumberOfFreePagesAvailable()
{
return topOfFreePageStack + 1;
}
};
PageHeap();
~PageHeap();
static void StaticInit();
void* AllocPages( _In_ size_t sz);
void FreePages(ProtectedEntityFlagsEnum entity, _Post_invalid_ void* p, size_t sz);
void FreeAllPages(bool checkLeaks = true);
// When previously committed pages are freed, they are merely marked
// as unused, not decommitted. Call this to decommit any unused pages.
bool DecommitUnusedPages();
// After all unsused pages in an arena are decommitted (by calling DecommitUnusedPages),
// the arena may be left with no used pages. In that case it can be freed,
// returning address space to the process. Call this to release any unsued arenas.
void FreeUnusedArenas();
// [....] this call first decommits unused pages and then frees unused arenas.
void ShrinkUnusedResources();
static size_t pageSize; // The system page size.
unsigned GetCurrentUseSize() const
{
return (unsigned)(m_pageCurUse * pageSize);
}
unsigned GetMaxUseSize() const
{
return (unsigned)(m_pageMaxUse * pageSize);
}
unsigned GetCurrentReserveSize() const
{
return (unsigned)(m_pageCurReserve * pageSize);
}
unsigned GetMaxReserveSize() const
{
return (unsigned)(m_pageMaxReserve * pageSize);
}
PageArena* FindArena(const void * p);
private:
CTinyLock lock; // This is the lock mechanism for thread safety.
PageArena* CreateArena(PageArenaType type, size_t sz);
template <typename T>
void RemoveArena(const T* goingAway, T*& containingArenaList, T*& containingArenaListLast);
bool DecommitUnusedPagesFromArenaList(PageArena* list);
void FreePagesHelper(ProtectedEntityFlagsEnum entity, PageArena* arena, _Post_invalid_ void* p, size_t sz);
// special case allocation/free behavior for large allocations
void * LargeAlloc(size_t sz);
void LargeFree(void * p, size_t sz);
// special case allocation/free behavior for single page allocations
void* SinglePageAlloc();
void SinglePageFree(ProtectedEntityFlagsEnum entity, _Post_invalid_ void* p);
SinglePageArena* singlePageArenaList; // List of memory arenas exclusively for single page allocs
SinglePageArena* singlePageArenaLast; // Last memory arena in list.
// used to efficiently find the arena a freed memory address belonged to
std::map<void *, SinglePageArena*> addressToSinglePageArenaMap;
// used to efficiently find an arena to make a new allocation from
std::queue<SinglePageArena*> singlePageArenasWithFreePages;
PageArena* arenaList; // List of memory arenas.
PageArena* arenaLast; // Last memory arena in list.
ProtectedEntityFlagsEnum whatIsProtected;
static int pageShift; // log2 of the page size
static bool reliableCommit; // Commit of memory protects it correctly even if already committed
size_t m_pageCurUse, m_pageMaxUse;
size_t m_pageCurReserve, m_pageMaxReserve;
};
| 33.766355 | 116 | 0.635345 |
ca789efd2dd75f2992bb37f986d6531d1341588d | 18,908 | h | C | code_reading/oceanbase-master/src/storage/ob_partition_merge_task.h | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/storage/ob_partition_merge_task.h | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | null | null | null | code_reading/oceanbase-master/src/storage/ob_partition_merge_task.h | wangcy6/weekly_read | 3a8837ee9cd957787ee1785e4066dd623e02e13a | [
"Apache-2.0"
] | 1 | 2020-10-18T12:59:31.000Z | 2020-10-18T12:59:31.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase CE is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#ifndef OB_PARTITION_MERGE_TASK_H_
#define OB_PARTITION_MERGE_TASK_H_
#include "storage/ob_storage_struct.h"
#include "share/scheduler/ob_dag_scheduler.h"
#include "lib/utility/ob_print_utils.h"
#include "common/rowkey/ob_rowkey.h"
#include "storage/ob_i_partition_report.h"
#include "storage/compaction/ob_partition_merge_util.h"
#include "storage/compaction/ob_column_checksum_calculator.h"
#include "storage/ob_partition_service.h"
#include "storage/ob_pg_partition.h"
#include "storage/ob_partition_parallel_merge_ctx.h"
namespace oceanbase {
namespace common {
class ObStoreRowkey;
}
namespace storage {
class ObSSTableMergeDag;
class ObMacroBlockMergeTask : public share::ObITask {
public:
ObMacroBlockMergeTask();
virtual ~ObMacroBlockMergeTask();
int init(const int64_t idx, storage::ObSSTableMergeCtx& ctx);
virtual int process();
int generate_next_task(ObITask*& next_task);
private:
int process_iter_to_complement(transaction::ObTransService* txs);
private:
int64_t idx_;
storage::ObSSTableMergeCtx* ctx_;
compaction::ObMacroBlockBuilder builder_;
compaction::ObMacroBlockEstimator estimator_;
compaction::ObIStoreRowProcessor* processor_;
bool is_inited_;
private:
DISALLOW_COPY_AND_ASSIGN(ObMacroBlockMergeTask);
};
// used for record output macro blocks
class ObSSTableMergeContext {
public:
ObSSTableMergeContext();
virtual ~ObSSTableMergeContext();
int init(const int64_t array_count, const bool has_lob, common::ObIArray<common::ObColumnStat*>* column_stats,
const bool merge_complement);
int add_macro_blocks(const int64_t idx, blocksstable::ObMacroBlocksWriteCtx* blocks_ctx,
blocksstable::ObMacroBlocksWriteCtx* lob_blocks_ctx, const ObSSTableMergeInfo& sstable_merge_info);
int add_bloom_filter(blocksstable::ObMacroBlocksWriteCtx& bloom_filter_blocks_ctx);
int add_column_stats(const common::ObIArray<common::ObColumnStat*>& column_stats);
int create_sstable(storage::ObCreateSSTableParamWithTable& param, storage::ObIPartitionGroupGuard& pg_guard,
ObTableHandle& table_handle);
int create_sstables(ObIArray<storage::ObCreateSSTableParamWithTable>& params,
storage::ObIPartitionGroupGuard& pg_guard, ObTablesHandle& tables_handle);
int64_t get_finish_count() const
{
return finish_count_;
}
ObSSTableMergeInfo& get_sstable_merge_info()
{
return sstable_merge_info_;
}
int64_t get_file_id() const
{
return file_id_;
}
void destroy();
int get_data_macro_block_count(int64_t& macro_block_count);
TO_STRING_KV(K_(is_inited), K_(concurrent_cnt), K_(finish_count), K_(sstable_merge_info));
private:
int add_lob_macro_blocks(const int64_t idx, blocksstable::ObMacroBlocksWriteCtx* blocks_ctx);
int new_block_write_ctx(blocksstable::ObMacroBlocksWriteCtx*& ctx);
OB_INLINE bool need_lob_macro_blocks()
{
return !lob_block_ctxs_.empty();
}
private:
bool is_inited_;
common::ObSpinLock lock_;
ObArray<blocksstable::ObMacroBlocksWriteCtx*> block_ctxs_;
// index sstable should not have lob blocks
ObArray<blocksstable::ObMacroBlocksWriteCtx*> lob_block_ctxs_;
blocksstable::ObMacroBlocksWriteCtx* bloom_filter_block_ctx_;
ObSSTableMergeInfo sstable_merge_info_;
common::ObIArray<common::ObColumnStat*>* column_stats_;
common::ObArenaAllocator allocator_;
int64_t finish_count_;
int64_t concurrent_cnt_;
bool merge_complement_;
int64_t file_id_;
};
struct ObSSTableScheduleMergeParam {
ObSSTableScheduleMergeParam();
bool is_valid() const;
OB_INLINE bool is_major_merge() const
{
return storage::is_major_merge(merge_type_);
}
OB_INLINE bool is_history_mini_minor_merge() const
{
return storage::is_history_mini_minor_merge(merge_type_);
}
OB_INLINE bool is_mini_merge() const
{
return storage::is_mini_merge(merge_type_);
}
OB_INLINE bool is_multi_version_minor_merge() const
{
return storage::is_multi_version_minor_merge(merge_type_);
}
OB_INLINE bool is_memtable_merge() const
{
return MINI_MERGE == schedule_merge_type_;
}
OB_INLINE bool is_mini_minor_merge() const
{
return storage::is_mini_minor_merge(merge_type_);
}
OB_INLINE bool is_minor_merge() const
{
return MINI_MINOR_MERGE == merge_type_ || MINOR_MERGE == merge_type_;
}
TO_STRING_KV(K_(merge_type), K_(merge_version), K_(pkey), K_(index_id), K_(schedule_merge_type), K_(pg_key));
ObMergeType merge_type_;
common::ObVersion merge_version_;
common::ObPartitionKey pkey_;
uint64_t index_id_;
ObMergeType schedule_merge_type_;
ObPartitionKey pg_key_;
};
class ObMergeParameter;
struct ObSSTableMergeCtx {
ObSSTableMergeCtx();
virtual ~ObSSTableMergeCtx();
virtual bool is_valid() const;
bool need_incremental_checksum() const
{
return checksum_method_ == blocksstable::CCM_TYPE_AND_VALUE;
}
bool need_full_checksum() const
{
return is_in_progressive_new_checksum_ || checksum_method_ == blocksstable::CCM_VALUE_ONLY || is_full_merge_;
}
bool need_rewrite_macro_block(const ObMacroBlockDesc& block_desc) const;
int get_storage_format_version(int64_t& storage_format_version) const;
int get_storage_format_work_version(int64_t& storage_format_work_version) const;
int init_parallel_merge();
int get_merge_range(int64_t parallel_idx, common::ObExtStoreRange& merge_range, common::ObIAllocator& allocator);
OB_INLINE int64_t get_concurrent_cnt() const
{
return parallel_merge_ctx_.get_concurrent_cnt();
}
ObITable::TableType get_merged_table_type() const;
storage::ObSSTableMergeContext& get_merge_context(const bool iter_complement)
{
return iter_complement ? merge_context_for_complement_minor_sstable_ : merge_context_;
}
// 1. init in dag
ObSSTableScheduleMergeParam param_;
storage::ObIPartitionReport* report_;
// 2. filled in ObPartitionStore::get_merge_tables
ObVersionRange sstable_version_range_; // version range for new sstable
int64_t create_snapshot_version_;
int64_t dump_memtable_timestamp_;
storage::ObTablesHandle tables_handle_;
storage::ObTableHandle base_table_handle_;
// 3. filled in ObPartitionStorage::get_schemas_to_merge
int64_t base_schema_version_;
const share::schema::ObTableSchema* mv_dep_table_schema_; // not null means materialized_view
const share::schema::ObTableSchema* data_table_schema_;
common::ObSEArray<share::schema::ObIndexTableStat, OB_MAX_INDEX_PER_TABLE> index_stats_;
int64_t schema_version_;
const share::schema::ObTableSchema* table_schema_; // table's schema need merge or split
share::schema::ObSchemaGetterGuard schema_guard_;
int64_t bf_rowkey_prefix_;
// 4. filled in ObPartitionStorage::cal_merge_param
bool is_full_merge_; // full merge or increment merge
int64_t stat_sampling_ratio_;
storage::ObMergeLevel merge_level_;
storage::ObMultiVersionRowInfo multi_version_row_info_;
storage::ObSSTableMergeContext merge_context_;
storage::ObSSTableMergeContext merge_context_for_complement_minor_sstable_;
int64_t progressive_merge_num_;
int64_t progressive_merge_start_version_;
// progressive_merge_end_version_ = progressive_merge_start_version_ + progressive_merge_num_
// current_round = merge_version - progressive_merge_start_version_
// int64_t concurrent_count_;
ObParallelMergeCtx parallel_merge_ctx_;
storage::ObIPartitionGroupGuard pg_guard_;
storage::ObPGPartitionGuard partition_guard_;
int64_t checksum_method_;
// 5. filled in ObPartitionStorage::prepare_merge_mv_depend_sstable
storage::ObTablesHandle mv_dep_tables_handle_; // obsoleted
// 6. inited in ObSSTableMergePrepareTask::init_estimate
common::ObArray<common::ObColumnStat*, ObIAllocator&> column_stats_;
// 7. filled in ObSSTableMergeFinishTask::update_partition_store
storage::ObTableHandle merged_table_handle_;
storage::ObTableHandle merged_complement_minor_table_handle_;
// no need init
common::ObArenaAllocator allocator_;
int32_t result_code_;
compaction::ObSSTableColumnChecksum column_checksum_;
bool is_in_progressive_new_checksum_;
int64_t backup_progressive_merge_num_;
int64_t backup_progressive_merge_start_version_;
bool is_created_index_first_merge_;
bool store_column_checksum_in_micro_;
int64_t progressive_merge_round_;
int64_t progressive_merge_step_;
bool use_new_progressive_;
bool create_sstable_for_large_snapshot_;
int64_t logical_data_version_;
common::ObLogTsRange log_ts_range_;
int64_t merge_log_ts_;
int64_t trans_table_end_log_ts_;
int64_t trans_table_timestamp_;
int64_t read_base_version_; // use for major merge
TO_STRING_KV(K_(param), K_(sstable_version_range), K_(create_snapshot_version), K_(base_schema_version),
K_(schema_version), K_(dump_memtable_timestamp), KP_(table_schema), K_(is_full_merge), K_(stat_sampling_ratio),
K_(merge_level), K_(progressive_merge_num), K_(progressive_merge_start_version), K_(parallel_merge_ctx),
K_(checksum_method), K_(result_code), KP_(data_table_schema), KP_(mv_dep_table_schema), K_(index_stats),
"tables_handle count", tables_handle_.get_count(), K_(index_stats), K_(is_in_progressive_new_checksum),
K_(store_column_checksum_in_micro), K_(progressive_merge_round), K_(progressive_merge_step),
K_(use_new_progressive), K_(tables_handle), K_(base_table_handle), K_(create_sstable_for_large_snapshot),
K_(logical_data_version), K_(log_ts_range), K_(merge_log_ts), K_(trans_table_end_log_ts),
K_(trans_table_timestamp), K_(read_base_version));
private:
DISALLOW_COPY_AND_ASSIGN(ObSSTableMergeCtx);
};
// ObMergeParamater is a sub part of ObSSTableMergeCtx
struct ObMergeParameter {
ObMergeParameter();
~ObMergeParameter()
{
reset();
}
bool is_valid() const;
void reset();
int init(ObSSTableMergeCtx& merge_ctx, const int64_t idx, const bool iter_complement);
storage::ObTablesHandle* tables_handle_;
bool is_full_merge_; // full merge or increment merge
ObMergeType merge_type_;
int64_t checksum_method_;
ObMergeLevel merge_level_;
const share::schema::ObTableSchema* table_schema_; // table's schema need merge
const share::schema::ObTableSchema* mv_dep_table_schema_; // not null means materialized_view
ObVersionRange version_range_;
compaction::ObColumnChecksumCalculator* checksum_calculator_;
bool is_iter_complement_;
OB_INLINE bool is_major_merge() const
{
return storage::is_major_merge(merge_type_);
}
OB_INLINE bool is_multi_version_minor_merge() const
{
return storage::is_multi_version_minor_merge(merge_type_);
}
OB_INLINE bool need_checksum() const
{
return storage::is_major_merge(merge_type_);
}
TO_STRING_KV(K_(is_full_merge), K_(merge_type), K_(checksum_method), K_(merge_level), KP_(table_schema),
KP_(mv_dep_table_schema), K_(version_range), KP_(checksum_calculator), KP_(tables_handle),
K_(is_iter_complement));
private:
DISALLOW_COPY_AND_ASSIGN(ObMergeParameter);
};
class ObSSTableMergePrepareTask : public share::ObITask {
public:
ObSSTableMergePrepareTask();
virtual ~ObSSTableMergePrepareTask();
int init();
virtual int process() override;
private:
int generate_merge_sstable_task();
int init_estimate(storage::ObSSTableMergeCtx& ctx);
int create_sstable_for_large_snapshot(storage::ObSSTableMergeCtx& ctx);
private:
bool is_inited_;
ObSSTableMergeDag* merge_dag_;
DISALLOW_COPY_AND_ASSIGN(ObSSTableMergePrepareTask);
};
class ObSSTableMergeFinishTask : public share::ObITask {
public:
ObSSTableMergeFinishTask();
virtual ~ObSSTableMergeFinishTask();
int init();
virtual int process() override;
private:
int get_merged_sstable_(const ObITable::TableType& type, const uint64_t table_id,
storage::ObSSTableMergeContext& merge_context, storage::ObTableHandle& table_handle, ObSSTable*& sstable);
int check_data_checksum();
int check_empty_merge_valid(storage::ObSSTableMergeCtx& ctx);
int check_macro_cnt_of_merge_table(const ObITable::TableType& type, storage::ObSSTableMergeContext& merge_context);
private:
bool is_inited_;
ObSSTableMergeDag* merge_dag_;
DISALLOW_COPY_AND_ASSIGN(ObSSTableMergeFinishTask);
};
class ObWriteCheckpointTask : public share::ObITask {
public:
ObWriteCheckpointTask();
virtual ~ObWriteCheckpointTask();
int init(int64_t frozen_version);
virtual int process() override;
private:
static const int64_t FAIL_WRITE_CHECKPOINT_ALERT_INTERVAL = 1000L * 1000L * 3600LL; // 6h
static const int64_t RETRY_WRITE_CHECKPOINT_MIN_INTERVAL = 1000L * 1000L * 300L; // 5 minutes
// Average replay time of 1 slog is 100us. Total replay time should less than 1 minute.
// So once log count exceed 50% * (60000000 / 100) = 300000, try to write a checkpoint.
static const int64_t MIN_WRITE_CHECKPOINT_LOG_CNT = 300000;
bool is_inited_;
int64_t frozen_version_;
DISALLOW_COPY_AND_ASSIGN(ObWriteCheckpointTask);
};
class ObWriteCheckpointDag : public share::ObIDag {
public:
ObWriteCheckpointDag();
virtual ~ObWriteCheckpointDag();
virtual bool operator==(const ObIDag& other) const override;
virtual int64_t hash() const override;
virtual int init(int64_t frozen_version);
virtual int64_t get_tenant_id() const override;
virtual int fill_comment(char* buf, const int64_t buf_len) const override;
virtual int64_t get_compat_mode() const override
{
return static_cast<int64_t>(share::ObWorker::CompatMode::MYSQL);
}
protected:
bool is_inited_;
int64_t frozen_version_;
DISALLOW_COPY_AND_ASSIGN(ObWriteCheckpointDag);
};
class ObSSTableMergeDag : public share::ObIDag {
public:
ObSSTableMergeDag(const ObIDagType type, const ObIDagPriority priority);
virtual ~ObSSTableMergeDag();
storage::ObSSTableMergeCtx& get_ctx()
{
return ctx_;
}
virtual bool operator==(const ObIDag& other) const override;
virtual int64_t hash() const override;
virtual int init(const ObSSTableScheduleMergeParam& param, ObIPartitionReport* report) = 0;
virtual int64_t get_tenant_id() const override
{
return ctx_.param_.pkey_.get_tenant_id();
}
virtual int fill_comment(char* buf, const int64_t buf_len) const override;
virtual int64_t get_compat_mode() const override
{
return static_cast<int64_t>(compat_mode_);
}
bool ignore_warning() override
{
return OB_NO_NEED_MERGE == dag_ret_ || OB_TABLE_IS_DELETED == dag_ret_ || OB_TENANT_HAS_BEEN_DROPPED == dag_ret_ ||
OB_PARTITION_NOT_EXIST == dag_ret_;
}
INHERIT_TO_STRING_KV("ObIDag", ObIDag, "param", ctx_.param_, "sstable_version_range", ctx_.sstable_version_range_,
"log_ts_range", ctx_.log_ts_range_);
protected:
int inner_init(const ObSSTableScheduleMergeParam& param, ObIPartitionReport* report);
bool is_inited_;
share::ObWorker::CompatMode compat_mode_;
storage::ObSSTableMergeCtx ctx_;
// merge_type\pkey\index_id is used to check if dag is equal
ObMergeType merge_type_;
common::ObPartitionKey pkey_;
uint64_t index_id_;
DISALLOW_COPY_AND_ASSIGN(ObSSTableMergeDag);
};
class ObSSTableMajorMergeDag : public ObSSTableMergeDag {
public:
ObSSTableMajorMergeDag();
virtual ~ObSSTableMajorMergeDag();
int init(const ObSSTableScheduleMergeParam& param, ObIPartitionReport* report) override;
private:
DISALLOW_COPY_AND_ASSIGN(ObSSTableMajorMergeDag);
};
class ObSSTableMiniMergeDag : public ObSSTableMergeDag {
public:
ObSSTableMiniMergeDag();
virtual ~ObSSTableMiniMergeDag();
int init(const ObSSTableScheduleMergeParam& param, ObIPartitionReport* report) override;
private:
DISALLOW_COPY_AND_ASSIGN(ObSSTableMiniMergeDag);
};
class ObSSTableMinorMergeDag : public ObSSTableMergeDag {
public:
ObSSTableMinorMergeDag();
virtual ~ObSSTableMinorMergeDag();
int init(const ObSSTableScheduleMergeParam& param, ObIPartitionReport* report) override;
private:
DISALLOW_COPY_AND_ASSIGN(ObSSTableMinorMergeDag);
};
class ObTransTableMergeDag : public share::ObIDag {
public:
ObTransTableMergeDag() : ObIDag(ObIDagType::DAG_TYPE_TRANS_TABLE_MERGE, ObIDagPriority::DAG_PRIO_TRANS_TABLE_MERGE){};
~ObTransTableMergeDag(){};
int init(const ObPartitionKey& pg_key)
{
this->pg_key_ = pg_key;
return OB_SUCCESS;
}
virtual bool operator==(const ObIDag& other) const override
{
bool is_same = true;
if (this == &other) {
} else if (get_type() != other.get_type()) {
is_same = false;
} else {
const ObTransTableMergeDag& other_dag = static_cast<const ObTransTableMergeDag&>(other);
is_same = pg_key_ == other_dag.pg_key_;
}
return is_same;
}
virtual int64_t hash() const override
{
return pg_key_.hash();
}
virtual int64_t get_tenant_id() const override
{
return pg_key_.get_tenant_id();
}
virtual int fill_comment(char* buf, const int64_t buf_len) const override;
virtual int64_t get_compat_mode() const override
{
return static_cast<int64_t>(share::ObWorker::CompatMode::MYSQL);
}
INHERIT_TO_STRING_KV("ObIDag", ObIDag, "pg_key", pg_key_);
private:
ObPartitionKey pg_key_;
DISALLOW_COPY_AND_ASSIGN(ObTransTableMergeDag);
};
class ObTransTableMergeTask : public share::ObITask {
private:
enum class SOURCE { NONE = 0, FROM_LOCAL, FROM_REMOTE, FROM_BOTH };
public:
ObTransTableMergeTask();
~ObTransTableMergeTask(){};
int init(const ObPartitionKey& pg_key, const int64_t end_log_ts, const int64_t trans_table_seq);
int init(const ObPartitionKey& pg_key, ObSSTable* sstable);
virtual int process();
int init_schema_and_writer(blocksstable::ObMacroBlockWriter& writer);
int merge_trans_table(blocksstable::ObMacroBlockWriter& writer);
int get_merged_trans_sstable(ObTableHandle& table_handle, blocksstable::ObMacroBlockWriter& writer);
private:
const int64_t SCHEMA_VERSION = 1;
private:
int update_partition_store(ObTableHandle& table_handle);
int merge_remote_with_local(blocksstable::ObMacroBlockWriter& writer);
private:
ObPartitionKey pg_key_;
common::ObArenaAllocator allocator_;
ObPartitionKey trans_table_pkey_;
blocksstable::ObDataStoreDesc desc_;
int64_t end_log_ts_;
ObTablesHandle tables_handle_;
share::schema::ObTableSchema table_schema_;
ObIPartitionGroupGuard pg_guard_;
int64_t trans_table_seq_;
bool is_inited_;
DISALLOW_COPY_AND_ASSIGN(ObTransTableMergeTask);
};
} /* namespace storage */
} /* namespace oceanbase */
#endif /* OB_PARTITION_MERGE_TASK_H_ */
| 35.144981 | 120 | 0.786175 |
a9a8c1f0da031d88838d7a4fc7bbb30cea4aace1 | 8,987 | h | C | libcxx/include/__format/format_arg.h | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | libcxx/include/__format/format_arg.h | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | libcxx/include/__format/format_arg.h | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | // -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP___FORMAT_FORMAT_ARG_H
#define _LIBCPP___FORMAT_FORMAT_ARG_H
#include <__concepts/arithmetic.h>
#include <__config>
#include <__format/format_error.h>
#include <__format/format_fwd.h>
#include <__functional_base>
#include <__variant/monostate.h>
#include <string>
#include <string_view>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
_LIBCPP_PUSH_MACROS
#include <__undef_macros>
_LIBCPP_BEGIN_NAMESPACE_STD
#if _LIBCPP_STD_VER > 17
// TODO FMT Remove this once we require compilers with proper C++20 support.
// If the compiler has no concepts support, the format header will be disabled.
// Without concepts support enable_if needs to be used and that too much effort
// to support compilers with partial C++20 support.
#if !defined(_LIBCPP_HAS_NO_CONCEPTS)
namespace __format {
/** The type stored in @ref basic_format_arg. */
enum class _LIBCPP_ENUM_VIS __arg_t : uint8_t {
__none,
__boolean,
__char_type,
__int,
__long_long,
#ifndef _LIBCPP_HAS_NO_INT128
__i128,
#endif
__unsigned,
__unsigned_long_long,
#ifndef _LIBCPP_HAS_NO_INT128
__u128,
#endif
__float,
__double,
__long_double,
__const_char_type_ptr,
__string_view,
__ptr
};
} // namespace __format
template <class _Visitor, class _Context>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_AVAILABILITY_FORMAT decltype(auto)
visit_format_arg(_Visitor&& __vis, basic_format_arg<_Context> __arg) {
switch (__arg.__type_) {
case __format::__arg_t::__none:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), monostate{});
case __format::__arg_t::__boolean:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__boolean);
case __format::__arg_t::__char_type:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__char_type);
case __format::__arg_t::__int:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__int);
case __format::__arg_t::__long_long:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__long_long);
#ifndef _LIBCPP_HAS_NO_INT128
case __format::__arg_t::__i128:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__i128);
#endif
case __format::__arg_t::__unsigned:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__unsigned);
case __format::__arg_t::__unsigned_long_long:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis),
__arg.__unsigned_long_long);
#ifndef _LIBCPP_HAS_NO_INT128
case __format::__arg_t::__u128:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__u128);
#endif
case __format::__arg_t::__float:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__float);
case __format::__arg_t::__double:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__double);
case __format::__arg_t::__long_double:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__long_double);
case __format::__arg_t::__const_char_type_ptr:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis),
__arg.__const_char_type_ptr);
case __format::__arg_t::__string_view:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__string_view);
case __format::__arg_t::__ptr:
return _VSTD::invoke(_VSTD::forward<_Visitor>(__vis), __arg.__ptr);
}
_LIBCPP_UNREACHABLE();
}
template <class _Context>
class _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT basic_format_arg {
public:
// TODO FMT Define the handle class.
class handle;
_LIBCPP_HIDE_FROM_ABI basic_format_arg() noexcept
: __type_{__format::__arg_t::__none} {}
_LIBCPP_HIDE_FROM_ABI explicit operator bool() const noexcept {
return __type_ != __format::__arg_t::__none;
}
private:
using char_type = typename _Context::char_type;
// TODO FMT Implement constrain [format.arg]/4
// Constraints: The template specialization
// typename Context::template formatter_type<T>
// meets the Formatter requirements ([formatter.requirements]). The extent
// to which an implementation determines that the specialization meets the
// Formatter requirements is unspecified, except that as a minimum the
// expression
// typename Context::template formatter_type<T>()
// .format(declval<const T&>(), declval<Context&>())
// shall be well-formed when treated as an unevaluated operand.
template <class _Ctx, class... _Args>
_LIBCPP_HIDE_FROM_ABI
_LIBCPP_AVAILABILITY_FORMAT friend __format_arg_store<_Ctx, _Args...>
_VSTD::make_format_args(const _Args&...);
template <class _Visitor, class _Ctx>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_AVAILABILITY_FORMAT friend decltype(auto)
_VSTD::visit_format_arg(_Visitor&& __vis, basic_format_arg<_Ctx> __arg);
union {
bool __boolean;
char_type __char_type;
int __int;
unsigned __unsigned;
long long __long_long;
unsigned long long __unsigned_long_long;
#ifndef _LIBCPP_HAS_NO_INT128
__int128_t __i128;
__uint128_t __u128;
#endif
float __float;
double __double;
long double __long_double;
const char_type* __const_char_type_ptr;
basic_string_view<char_type> __string_view;
const void* __ptr;
// TODO FMT Add the handle.
};
__format::__arg_t __type_;
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(bool __v) noexcept
: __boolean(__v), __type_(__format::__arg_t::__boolean) {}
template <class _Tp>
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(_Tp __v) noexcept
requires(same_as<_Tp, char_type> ||
(same_as<_Tp, char> && same_as<char_type, wchar_t>))
: __char_type(__v), __type_(__format::__arg_t::__char_type) {}
template <__libcpp_signed_integer _Tp>
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(_Tp __v) noexcept {
if constexpr (sizeof(_Tp) <= sizeof(int)) {
__int = static_cast<int>(__v);
__type_ = __format::__arg_t::__int;
} else if constexpr (sizeof(_Tp) <= sizeof(long long)) {
__long_long = static_cast<long long>(__v);
__type_ = __format::__arg_t::__long_long;
}
#ifndef _LIBCPP_HAS_NO_INT128
else if constexpr (sizeof(_Tp) == sizeof(__int128_t)) {
__i128 = __v;
__type_ = __format::__arg_t::__i128;
}
#endif
else
static_assert(sizeof(_Tp) == 0, "An unsupported signed integer was used");
}
template <__libcpp_unsigned_integer _Tp>
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(_Tp __v) noexcept {
if constexpr (sizeof(_Tp) <= sizeof(unsigned)) {
__unsigned = static_cast<unsigned>(__v);
__type_ = __format::__arg_t::__unsigned;
} else if constexpr (sizeof(_Tp) <= sizeof(unsigned long long)) {
__unsigned_long_long = static_cast<unsigned long long>(__v);
__type_ = __format::__arg_t::__unsigned_long_long;
}
#ifndef _LIBCPP_HAS_NO_INT128
else if constexpr (sizeof(_Tp) == sizeof(__int128_t)) {
__u128 = __v;
__type_ = __format::__arg_t::__u128;
}
#endif
else
static_assert(sizeof(_Tp) == 0,
"An unsupported unsigned integer was used");
}
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(float __v) noexcept
: __float(__v), __type_(__format::__arg_t::__float) {}
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(double __v) noexcept
: __double(__v), __type_(__format::__arg_t::__double) {}
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(long double __v) noexcept
: __long_double(__v), __type_(__format::__arg_t::__long_double) {}
// Note not a 'noexcept' function.
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(const char_type* __s)
: __const_char_type_ptr(__s),
__type_(__format::__arg_t::__const_char_type_ptr) {
_LIBCPP_ASSERT(__s, "Used a nullptr argument to initialize a C-string");
}
template <class _Traits>
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(
basic_string_view<char_type, _Traits> __s) noexcept
: __string_view{__s.data(), __s.size()},
__type_(__format::__arg_t::__string_view) {}
template <class _Traits, class _Allocator>
_LIBCPP_HIDE_FROM_ABI explicit basic_format_arg(
const basic_string<char_type, _Traits, _Allocator>& __s) noexcept
: __string_view{__s.data(), __s.size()},
__type_(__format::__arg_t::__string_view) {}
_LIBCPP_HIDE_FROM_ABI
explicit basic_format_arg(nullptr_t) noexcept
: __ptr(nullptr), __type_(__format::__arg_t::__ptr) {}
// TODO FMT Implement the _Tp* constructor.
};
#endif // !defined(_LIBCPP_HAS_NO_CONCEPTS)
#endif //_LIBCPP_STD_VER > 17
_LIBCPP_END_NAMESPACE_STD
_LIBCPP_POP_MACROS
#endif // _LIBCPP___FORMAT_FORMAT_ARG_H
| 34.968872 | 80 | 0.722711 |
a9b56ebe0022d51fac377a7a7816f8e0f7e60243 | 37,312 | c | C | base/boot/efi/ia64/ixpcibus.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/boot/efi/ia64/ixpcibus.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/boot/efi/ia64/ixpcibus.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1989 Microsoft Corporation
Module Name:
ixpcidat.c
Abstract:
Get/Set bus data routines for the PCI bus
Author:
Environment:
Kernel mode
Revision History:
--*/
#include "bootia64.h"
#include "arc.h"
#include "ixfwhal.h"
#include "ntconfig.h"
#include "pci.h"
//extern WCHAR rgzMultiFunctionAdapter[];
//extern WCHAR rgzConfigurationData[];
//extern WCHAR rgzIdentifier[];
//extern WCHAR rgzPCIIdentifier[];
//
// Hal specific PCI bus structures
//
typedef struct tagPCIPBUSDATA {
union {
struct {
PULONG Address;
ULONG Data;
} Type1;
struct {
PUCHAR CSE;
PUCHAR Forward;
ULONG Base;
} Type2;
} Config;
} PCIPBUSDATA, *PPCIPBUSDATA;
#define PciBitIndex(Dev,Fnc) (Fnc*32 + Dev);
#define PCI_CONFIG_TYPE(PciData) ((PciData)->HeaderType & ~PCI_MULTIFUNCTION)
#define BUSHANDLER _BUSHANDLER
#define PBUSHANDLER _PBUSHANDLER
// thunk for NtLdr
typedef struct {
ULONG NoBuses;
ULONG BusNumber;
PVOID BusData;
PCIPBUSDATA theBusData;
} BUSHANDLER, *PBUSHANDLER;
#define HalpPCIPin2Line(bus,rbus,slot,pcidata)
#define HalpPCILine2Pin(bus,rbus,slot,pcidata,pcidata2)
#define ExAllocatePool(a,l) FwAllocatePool(l)
// thunk for NtLdr
typedef ULONG (*FncConfigIO) (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
typedef VOID (*FncSync) (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PKIRQL Irql,
IN PVOID State
);
typedef VOID (*FncReleaseSync) (
IN PBUSHANDLER BusHandler,
IN KIRQL Irql
);
typedef struct {
FncSync Synchronize;
FncReleaseSync ReleaseSynchronzation;
FncConfigIO ConfigRead[3];
FncConfigIO ConfigWrite[3];
} CONFIG_HANDLER, *PCONFIG_HANDLER;
//
// Prototypes
//
ULONG
HalpGetPCIData (
IN ULONG BusNumber,
IN PCI_SLOT_NUMBER SlotNumber,
IN PVOID Buffer,
IN ULONG Offset,
IN ULONG Length
);
ULONG
HalpSetPCIData (
IN ULONG BusNumber,
IN PCI_SLOT_NUMBER SlotNumber,
IN PVOID Buffer,
IN ULONG Offset,
IN ULONG Length
);
extern ULONG
HalpGetPCIInterruptVector (
IN PBUSHANDLER BusHandler,
IN PBUSHANDLER RootHandler,
IN ULONG BusInterruptLevel,
IN ULONG BusInterruptVector,
OUT PKIRQL Irql,
OUT PKAFFINITY Affinity
);
NTSTATUS
HalpAdjustPCIResourceList (
IN PBUSHANDLER BusHandler,
IN PBUSHANDLER RootHandler,
IN OUT PIO_RESOURCE_REQUIREMENTS_LIST *pResourceList
);
NTSTATUS
HalpAssignPCISlotResources (
IN ULONG BusNumber,
IN ULONG SlotNumber,
IN OUT PCM_RESOURCE_LIST *AllocatedResources
);
VOID
HalpInitializePciBuses (
VOID
);
//VOID
//HalpPCIPin2Line (
// IN PBUSHANDLER BusHandler,
// IN PBUSHANDLER RootHandler,
// IN PCI_SLOT_NUMBER Slot,
// IN PPCI_COMMON_CONFIG PciData
// );
//
//VOID
//HalpPCILine2Pin (
// IN PBUSHANDLER BusHandler,
// IN PBUSHANDLER RootHandler,
// IN PCI_SLOT_NUMBER SlotNumber,
// IN PPCI_COMMON_CONFIG PciNewData,
// IN PPCI_COMMON_CONFIG PciOldData
// );
BOOLEAN
HalpValidPCISlot (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot
);
VOID
HalpReadPCIConfig (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PVOID Buffer,
IN ULONG Offset,
IN ULONG Length
);
VOID
HalpWritePCIConfig (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PVOID Buffer,
IN ULONG Offset,
IN ULONG Length
);
PBUSHANDLER
HalpGetPciBusHandler (
IN ULONG BusNumber
);
//-------------------------------------------------
VOID HalpPCISynchronizeType1 (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PKIRQL Irql,
IN PVOID State
);
VOID HalpPCIReleaseSynchronzationType1 (
IN PBUSHANDLER BusHandler,
IN KIRQL Irql
);
ULONG HalpPCIReadUlongType1 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIReadUcharType1 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIReadUshortType1 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIWriteUlongType1 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIWriteUcharType1 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIWriteUshortType1 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
VOID HalpPCISynchronizeType2 (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PKIRQL Irql,
IN PVOID State
);
VOID HalpPCIReleaseSynchronzationType2 (
IN PBUSHANDLER BusHandler,
IN KIRQL Irql
);
ULONG HalpPCIReadUlongType2 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIReadUcharType2 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIReadUshortType2 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIWriteUlongType2 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIWriteUcharType2 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
ULONG HalpPCIWriteUshortType2 (
IN PPCIPBUSDATA BusData,
IN PVOID State,
IN PUCHAR Buffer,
IN ULONG Offset
);
//#define DISABLE_INTERRUPTS() //_asm { cli }
//#define ENABLE_INTERRUPTS() //_asm { sti }
//
// Globals
//
ULONG PCIMaxDevice;
BUSHANDLER PCIBusHandler;
CONFIG_HANDLER PCIConfigHandlers = {
HalpPCISynchronizeType1,
HalpPCIReleaseSynchronzationType1,
{
HalpPCIReadUlongType1, // 0
HalpPCIReadUcharType1, // 1
HalpPCIReadUshortType1 // 2
},
{
HalpPCIWriteUlongType1, // 0
HalpPCIWriteUcharType1, // 1
HalpPCIWriteUshortType1 // 2
}
};
CONFIG_HANDLER PCIConfigHandlersType2 = {
HalpPCISynchronizeType2,
HalpPCIReleaseSynchronzationType2,
{
HalpPCIReadUlongType2, // 0
HalpPCIReadUcharType2, // 1
HalpPCIReadUshortType2 // 2
},
{
HalpPCIWriteUlongType2, // 0
HalpPCIWriteUcharType2, // 1
HalpPCIWriteUshortType2 // 2
}
};
UCHAR PCIDeref[4][4] = { {0,1,2,2},{1,1,1,1},{2,1,2,2},{1,1,1,1} };
VOID
HalpPCIConfig (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PUCHAR Buffer,
IN ULONG Offset,
IN ULONG Length,
IN FncConfigIO *ConfigIO
);
VOID
HalpInitializePciBus (
VOID
)
{
PPCI_REGISTRY_INFO PCIRegInfo;
PPCIPBUSDATA BusData;
PBUSHANDLER Bus;
PCONFIGURATION_COMPONENT_DATA ConfigData;
PCM_PARTIAL_RESOURCE_LIST Desc;
PCM_PARTIAL_RESOURCE_DESCRIPTOR PDesc;
ULONG i;
ULONG HwType;
Bus = &PCIBusHandler;
PCIBusHandler.BusData = &PCIBusHandler.theBusData;
PCIRegInfo = NULL; // not found
ConfigData = NULL; // start at begining
do {
ConfigData = KeFindConfigurationNextEntry (
FwConfigurationTree,
AdapterClass,
MultiFunctionAdapter,
NULL,
&ConfigData
);
if (ConfigData == NULL) {
// PCI info not found
return ;
}
if (ConfigData->ComponentEntry.Identifier == NULL ||
_stricmp (ConfigData->ComponentEntry.Identifier, "PCI") != 0) {
continue;
}
PCIRegInfo = NULL;
Desc = ConfigData->ConfigurationData;
PDesc = Desc->PartialDescriptors;
for (i = 0; i < Desc->Count; i++) {
if (PDesc->Type == CmResourceTypeDeviceSpecific) {
PCIRegInfo = (PPCI_REGISTRY_INFO) (PDesc+1);
break;
}
PDesc++;
}
} while (!PCIRegInfo) ;
//
// PCIRegInfo describes the system's PCI support as indicated
// by the BIOS.
//
HwType = PCIRegInfo->HardwareMechanism & 0xf;
switch (HwType) {
case 1:
// this is the default case
PCIMaxDevice = PCI_MAX_DEVICES;
break;
//
// Type2 does not work MP, nor does the default type2
// support more the 0xf device slots
//
case 2:
RtlMoveMemory (&PCIConfigHandlers,
&PCIConfigHandlersType2,
sizeof (PCIConfigHandlersType2));
PCIMaxDevice = 0x10;
break;
default:
// unsupport type
PCIRegInfo->NoBuses = 0;
}
PCIBusHandler.NoBuses = PCIRegInfo->NoBuses;
if (PCIRegInfo->NoBuses) {
BusData = (PPCIPBUSDATA) Bus->BusData;
switch (HwType) {
case 1:
BusData->Config.Type1.Address = (PULONG)PCI_TYPE1_ADDR_PORT;
BusData->Config.Type1.Data = PCI_TYPE1_DATA_PORT;
break;
case 2:
BusData->Config.Type2.CSE = PCI_TYPE2_CSE_PORT;
BusData->Config.Type2.Forward = PCI_TYPE2_FORWARD_PORT;
BusData->Config.Type2.Base = PCI_TYPE2_ADDRESS_BASE;
break;
}
}
}
PBUSHANDLER
HalpGetPciBusHandler (
IN ULONG BusNumber
)
{
if (PCIBusHandler.BusData == NULL) {
HalpInitializePciBus ();
}
if (BusNumber > PCIBusHandler.NoBuses) {
return NULL;
}
PCIBusHandler.BusNumber = BusNumber;
return &PCIBusHandler;
}
ULONG
HalpGetPCIData (
IN ULONG BusNumber,
IN PCI_SLOT_NUMBER Slot,
IN PUCHAR Buffer,
IN ULONG Offset,
IN ULONG Length
)
/*++
Routine Description:
The function returns the Pci bus data for a device.
Arguments:
BusNumber - Indicates which bus.
VendorSpecificDevice - The VendorID (low Word) and DeviceID (High Word)
Buffer - Supplies the space to store the data.
Length - Supplies a count in bytes of the maximum amount to return.
Return Value:
Returns the amount of data stored into the buffer.
If this PCI slot has never been set, then the configuration information
returned is zeroed.
--*/
{
PBUSHANDLER BusHandler;
PPCI_COMMON_CONFIG PciData;
UCHAR iBuffer[PCI_COMMON_HDR_LENGTH];
PPCIPBUSDATA BusData;
ULONG Len;
BusHandler = HalpGetPciBusHandler (BusNumber);
if (!BusHandler) {
return 0;
}
if (Length > sizeof (PCI_COMMON_CONFIG)) {
Length = sizeof (PCI_COMMON_CONFIG);
}
Len = 0;
PciData = (PPCI_COMMON_CONFIG) iBuffer;
if (Offset >= PCI_COMMON_HDR_LENGTH) {
//
// The user did not request any data from the common
// header. Verify the PCI device exists, then continue
// in the device specific area.
//
HalpReadPCIConfig (BusHandler, Slot, PciData, 0, sizeof(ULONG));
if (PciData->VendorID == PCI_INVALID_VENDORID) {
return 0;
}
} else {
//
// Caller requested at least some data within the
// common header. Read the whole header, effect the
// fields we need to and then copy the user's requested
// bytes from the header
//
//
// Read this PCI devices slot data
//
Len = PCI_COMMON_HDR_LENGTH;
HalpReadPCIConfig (BusHandler, Slot, PciData, 0, Len);
if (PciData->VendorID == PCI_INVALID_VENDORID) {
Len = 2; // only return invalid id
}
//
// Has this PCI device been configured?
//
BusData = (PPCIPBUSDATA) BusHandler->BusData;
HalpPCIPin2Line (BusHandler, RootHandler, Slot, PciData);
//
// Copy whatever data overlaps into the callers buffer
//
if (Len < Offset) {
// no data at caller's buffer
return 0;
}
Len -= Offset;
if (Len > Length) {
Len = Length;
}
RtlMoveMemory(Buffer, iBuffer + Offset, Len);
Offset += Len;
Buffer += Len;
Length -= Len;
}
if (Length) {
if (Offset >= PCI_COMMON_HDR_LENGTH) {
//
// The remaining Buffer comes from the Device Specific
// area - put on the kitten gloves and read from it.
//
// Specific read/writes to the PCI device specific area
// are guarenteed:
//
// Not to read/write any byte outside the area specified
// by the caller. (this may cause WORD or BYTE references
// to the area in order to read the non-dword aligned
// ends of the request)
//
// To use a WORD access if the requested length is exactly
// a WORD long & WORD aligned.
//
// To use a BYTE access if the requested length is exactly
// a BYTE long.
//
HalpReadPCIConfig (BusHandler, Slot, Buffer, Offset, Length);
Len += Length;
}
}
return Len;
}
ULONG
HalpSetPCIData (
IN ULONG BusNumber,
IN PCI_SLOT_NUMBER Slot,
IN PUCHAR Buffer,
IN ULONG Offset,
IN ULONG Length
)
/*++
Routine Description:
The function returns the Pci bus data for a device.
Arguments:
VendorSpecificDevice - The VendorID (low Word) and DeviceID (High Word)
Buffer - Supplies the space to store the data.
Length - Supplies a count in bytes of the maximum amount to return.
Return Value:
Returns the amount of data stored into the buffer.
--*/
{
PBUSHANDLER BusHandler;
PPCI_COMMON_CONFIG PciData, PciData2;
UCHAR iBuffer[PCI_COMMON_HDR_LENGTH];
UCHAR iBuffer2[PCI_COMMON_HDR_LENGTH];
PPCIPBUSDATA BusData;
ULONG Len;
BusHandler = HalpGetPciBusHandler (BusNumber);
if (!BusHandler) {
return 0;
}
if (Length > sizeof (PCI_COMMON_CONFIG)) {
Length = sizeof (PCI_COMMON_CONFIG);
}
Len = 0;
PciData = (PPCI_COMMON_CONFIG) iBuffer;
PciData2 = (PPCI_COMMON_CONFIG) iBuffer2;
if (Offset >= PCI_COMMON_HDR_LENGTH) {
//
// The user did not request any data from the common
// header. Verify the PCI device exists, then continue in
// the device specific area.
//
HalpReadPCIConfig (BusHandler, Slot, PciData, 0, sizeof(ULONG));
if (PciData->VendorID == PCI_INVALID_VENDORID) {
return 0;
}
} else {
//
// Caller requested to set at least some data within the
// common header.
//
Len = PCI_COMMON_HDR_LENGTH;
HalpReadPCIConfig (BusHandler, Slot, PciData, 0, Len);
if (PciData->VendorID == PCI_INVALID_VENDORID ||
PCI_CONFIG_TYPE (PciData) != 0) {
// no device, or header type unkown
return 0;
}
//
// Set this device as configured
//
BusData = (PPCIPBUSDATA) BusHandler->BusData;
//
// Copy COMMON_HDR values to buffer2, then overlay callers changes.
//
RtlMoveMemory (iBuffer2, iBuffer, Len);
Len -= Offset;
if (Len > Length) {
Len = Length;
}
RtlMoveMemory (iBuffer2+Offset, Buffer, Len);
// in case interrupt line or pin was editted
HalpPCILine2Pin (BusHandler, RootHandler, Slot, PciData2, PciData);
//
// Set new PCI configuration
//
HalpWritePCIConfig (BusHandler, Slot, iBuffer2+Offset, Offset, Len);
Offset += Len;
Buffer += Len;
Length -= Len;
}
if (Length) {
if (Offset >= PCI_COMMON_HDR_LENGTH) {
//
// The remaining Buffer comes from the Device Specific
// area - put on the kitten gloves and write it
//
// Specific read/writes to the PCI device specific area
// are guarenteed:
//
// Not to read/write any byte outside the area specified
// by the caller. (this may cause WORD or BYTE references
// to the area in order to read the non-dword aligned
// ends of the request)
//
// To use a WORD access if the requested length is exactly
// a WORD long & WORD aligned.
//
// To use a BYTE access if the requested length is exactly
// a BYTE long.
//
HalpWritePCIConfig (BusHandler, Slot, Buffer, Offset, Length);
Len += Length;
}
}
return Len;
}
VOID
HalpReadPCIConfig (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PVOID Buffer,
IN ULONG Offset,
IN ULONG Length
)
{
if (!HalpValidPCISlot (BusHandler, Slot)) {
//
// Invalid SlotID return no data
//
RtlFillMemory (Buffer, Length, (UCHAR) -1);
return ;
}
HalpPCIConfig (BusHandler, Slot, (PUCHAR) Buffer, Offset, Length,
PCIConfigHandlers.ConfigRead);
}
VOID
HalpWritePCIConfig (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PVOID Buffer,
IN ULONG Offset,
IN ULONG Length
)
{
if (!HalpValidPCISlot (BusHandler, Slot)) {
//
// Invalid SlotID do nothing
//
return ;
}
HalpPCIConfig (BusHandler, Slot, (PUCHAR) Buffer, Offset, Length,
PCIConfigHandlers.ConfigWrite);
}
BOOLEAN
HalpValidPCISlot (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot
)
{
PCI_SLOT_NUMBER Slot2;
UCHAR HeaderType;
ULONG i;
if (Slot.u.bits.Reserved != 0) {
return FALSE;
}
if (Slot.u.bits.DeviceNumber >= PCIMaxDevice) {
return FALSE;
}
if (Slot.u.bits.FunctionNumber == 0) {
return TRUE;
}
//
// Non zero function numbers are only supported if the
// device has the PCI_MULTIFUNCTION bit set in it's header
//
i = Slot.u.bits.DeviceNumber;
//
// Read DeviceNumber, Function zero, to determine if the
// PCI supports multifunction devices
//
Slot2 = Slot;
Slot2.u.bits.FunctionNumber = 0;
HalpReadPCIConfig (
BusHandler,
Slot2,
&HeaderType,
FIELD_OFFSET (PCI_COMMON_CONFIG, HeaderType),
sizeof (UCHAR)
);
if (!(HeaderType & PCI_MULTIFUNCTION) || HeaderType == 0xFF) {
// this device doesn't exists or doesn't support MULTIFUNCTION types
return FALSE;
}
return TRUE;
}
VOID
HalpPCIConfig (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PUCHAR Buffer,
IN ULONG Offset,
IN ULONG Length,
IN FncConfigIO *ConfigIO
)
{
KIRQL OldIrql;
ULONG i;
UCHAR State[20];
PPCIPBUSDATA BusData;
BusData = (PPCIPBUSDATA) BusHandler->BusData;
PCIConfigHandlers.Synchronize (BusHandler, Slot, &OldIrql, State);
while (Length) {
i = PCIDeref[Offset % sizeof(ULONG)][Length % sizeof(ULONG)];
i = ConfigIO[i] (BusData, State, Buffer, Offset);
Offset += i;
Buffer += i;
Length -= i;
}
PCIConfigHandlers.ReleaseSynchronzation (BusHandler, OldIrql);
}
VOID HalpPCISynchronizeType1 (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PKIRQL Irql,
IN PPCI_TYPE1_CFG_BITS PciCfg1
)
{
UNREFERENCED_PARAMETER( Irql );
//
// Initialize PciCfg1
//
PciCfg1->u.AsULONG = 0;
PciCfg1->u.bits.BusNumber = BusHandler->BusNumber;
PciCfg1->u.bits.DeviceNumber = Slot.u.bits.DeviceNumber;
PciCfg1->u.bits.FunctionNumber = Slot.u.bits.FunctionNumber;
PciCfg1->u.bits.Enable = TRUE;
//
// Synchronize with PCI type1 config space
//
//KeAcquireSpinLock (&HalpPCIConfigLock, Irql);
}
VOID HalpPCIReleaseSynchronzationType1 (
IN PBUSHANDLER BusHandler,
IN KIRQL Irql
)
{
PCI_TYPE1_CFG_BITS PciCfg1;
PPCIPBUSDATA BusData;
UNREFERENCED_PARAMETER( Irql );
//
// Disable PCI configuration space
//
PciCfg1.u.AsULONG = 0;
BusData = (PPCIPBUSDATA) BusHandler->BusData;
WRITE_PORT_ULONG (BusData->Config.Type1.Address, PciCfg1.u.AsULONG);
//
// Release spinlock
//
//KeReleaseSpinLock (&HalpPCIConfigLock, Irql);
}
ULONG
HalpPCIReadUcharType1 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE1_CFG_BITS PciCfg1,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
ULONG i;
i = Offset % sizeof(ULONG);
PciCfg1->u.bits.RegisterNumber = Offset / sizeof(ULONG);
WRITE_PORT_ULONG (BusData->Config.Type1.Address, PciCfg1->u.AsULONG);
*Buffer = READ_PORT_UCHAR ((PUCHAR)UlongToPtr((BusData->Config.Type1.Data + i)));
return sizeof (UCHAR);
}
ULONG
HalpPCIReadUshortType1 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE1_CFG_BITS PciCfg1,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
ULONG i;
i = Offset % sizeof(ULONG);
PciCfg1->u.bits.RegisterNumber = Offset / sizeof(ULONG);
WRITE_PORT_ULONG (BusData->Config.Type1.Address, PciCfg1->u.AsULONG);
*((PUSHORT) Buffer) = READ_PORT_USHORT ((PUSHORT)ULongToPtr(BusData->Config.Type1.Data + i));
return sizeof (USHORT);
}
ULONG
HalpPCIReadUlongType1 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE1_CFG_BITS PciCfg1,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
PciCfg1->u.bits.RegisterNumber = Offset / sizeof(ULONG);
WRITE_PORT_ULONG (BusData->Config.Type1.Address, PciCfg1->u.AsULONG);
*((PULONG) Buffer) = READ_PORT_ULONG ((PULONG)ULongToPtr(BusData->Config.Type1.Data));
return sizeof (ULONG);
}
ULONG
HalpPCIWriteUcharType1 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE1_CFG_BITS PciCfg1,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
ULONG i;
i = Offset % sizeof(ULONG);
PciCfg1->u.bits.RegisterNumber = Offset / sizeof(ULONG);
WRITE_PORT_ULONG (BusData->Config.Type1.Address, PciCfg1->u.AsULONG);
WRITE_PORT_UCHAR ((PUCHAR)ULongToPtr(BusData->Config.Type1.Data + i), *Buffer);
return sizeof (UCHAR);
}
ULONG
HalpPCIWriteUshortType1 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE1_CFG_BITS PciCfg1,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
ULONG i;
i = Offset % sizeof(ULONG);
PciCfg1->u.bits.RegisterNumber = Offset / sizeof(ULONG);
WRITE_PORT_ULONG (BusData->Config.Type1.Address, PciCfg1->u.AsULONG);
WRITE_PORT_USHORT ((PUSHORT)ULongToPtr(BusData->Config.Type1.Data + i), *((PUSHORT) Buffer));
return sizeof (USHORT);
}
ULONG
HalpPCIWriteUlongType1 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE1_CFG_BITS PciCfg1,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
PciCfg1->u.bits.RegisterNumber = Offset / sizeof(ULONG);
WRITE_PORT_ULONG (BusData->Config.Type1.Address, PciCfg1->u.AsULONG);
WRITE_PORT_ULONG ((PULONG)ULongToPtr(BusData->Config.Type1.Data), *((PULONG) Buffer));
return sizeof (ULONG);
}
VOID HalpPCISynchronizeType2 (
IN PBUSHANDLER BusHandler,
IN PCI_SLOT_NUMBER Slot,
IN PKIRQL Irql,
IN PPCI_TYPE2_ADDRESS_BITS PciCfg2Addr
)
{
PCI_TYPE2_CSE_BITS PciCfg2Cse;
PPCIPBUSDATA BusData;
UNREFERENCED_PARAMETER( Irql );
BusData = (PPCIPBUSDATA) BusHandler->BusData;
//
// Initialize Cfg2Addr
//
PciCfg2Addr->u.AsUSHORT = 0;
PciCfg2Addr->u.bits.Agent = (USHORT) Slot.u.bits.DeviceNumber;
PciCfg2Addr->u.bits.AddressBase = (USHORT) BusData->Config.Type2.Base;
//
// Synchronize with type2 config space - type2 config space
// remaps 4K of IO space, so we can not allow other I/Os to occur
// while using type2 config space, hence the disable_interrupts.
//
//KeAcquireSpinLock (&HalpPCIConfigLock, Irql);
//DISABLE_INTERRUPTS (); // is not MP safe
PciCfg2Cse.u.AsUCHAR = 0;
PciCfg2Cse.u.bits.Enable = TRUE;
PciCfg2Cse.u.bits.FunctionNumber = (UCHAR) Slot.u.bits.FunctionNumber;
PciCfg2Cse.u.bits.Key = 0xff;
//
// Select bus & enable type 2 configuration space
//
WRITE_PORT_UCHAR (BusData->Config.Type2.Forward, (UCHAR) BusHandler->BusNumber);
WRITE_PORT_UCHAR (BusData->Config.Type2.CSE, PciCfg2Cse.u.AsUCHAR);
}
VOID HalpPCIReleaseSynchronzationType2 (
IN PBUSHANDLER BusHandler,
IN KIRQL Irql
)
{
PCI_TYPE2_CSE_BITS PciCfg2Cse;
PPCIPBUSDATA BusData;
UNREFERENCED_PARAMETER( Irql );
//
// disable PCI configuration space
//
BusData = (PPCIPBUSDATA) BusHandler->BusData;
PciCfg2Cse.u.AsUCHAR = 0;
WRITE_PORT_UCHAR (BusData->Config.Type2.CSE, PciCfg2Cse.u.AsUCHAR);
//
// Restore interrupts, release spinlock
//
//ENABLE_INTERRUPTS ();
//KeReleaseSpinLock (&HalpPCIConfigLock, Irql);
}
ULONG
HalpPCIReadUcharType2 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE2_ADDRESS_BITS PciCfg2Addr,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
UNREFERENCED_PARAMETER( BusData );
PciCfg2Addr->u.bits.RegisterNumber = (USHORT) Offset;
*Buffer = READ_PORT_UCHAR ((PUCHAR) ((ULONGLONG)PciCfg2Addr->u.AsUSHORT));
return sizeof (UCHAR);
}
ULONG
HalpPCIReadUshortType2 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE2_ADDRESS_BITS PciCfg2Addr,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
USHORT RetVal;
UNREFERENCED_PARAMETER( BusData );
PciCfg2Addr->u.bits.RegisterNumber = (USHORT) Offset;
RetVal = READ_PORT_USHORT ((PUSHORT) ((ULONGLONG)PciCfg2Addr->u.AsUSHORT));
*Buffer = TRUNCATE_SIZE_AT_UCHAR_MAX(RetVal);
return sizeof (USHORT);
}
ULONG
HalpPCIReadUlongType2 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE2_ADDRESS_BITS PciCfg2Addr,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
ULONG RetVal;
UNREFERENCED_PARAMETER( BusData );
PciCfg2Addr->u.bits.RegisterNumber = (USHORT) Offset;
RetVal = READ_PORT_ULONG ((PULONG) ((ULONGLONG)PciCfg2Addr->u.AsUSHORT));
*Buffer = TRUNCATE_SIZE_AT_UCHAR_MAX(RetVal);
return sizeof(ULONG);
}
ULONG
HalpPCIWriteUcharType2 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE2_ADDRESS_BITS PciCfg2Addr,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
UNREFERENCED_PARAMETER( BusData );
PciCfg2Addr->u.bits.RegisterNumber = (USHORT) Offset;
WRITE_PORT_UCHAR ((PUCHAR) ((ULONGLONG)PciCfg2Addr->u.AsUSHORT), *Buffer);
return sizeof (UCHAR);
}
ULONG
HalpPCIWriteUshortType2 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE2_ADDRESS_BITS PciCfg2Addr,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
UNREFERENCED_PARAMETER( BusData );
PciCfg2Addr->u.bits.RegisterNumber = (USHORT) Offset;
WRITE_PORT_USHORT ((PUSHORT) ((ULONGLONG)PciCfg2Addr->u.AsUSHORT), *((PUSHORT) Buffer));
return sizeof (USHORT);
}
ULONG
HalpPCIWriteUlongType2 (
IN PPCIPBUSDATA BusData,
IN PPCI_TYPE2_ADDRESS_BITS PciCfg2Addr,
IN PUCHAR Buffer,
IN ULONG Offset
)
{
UNREFERENCED_PARAMETER( BusData );
PciCfg2Addr->u.bits.RegisterNumber = (USHORT) Offset;
WRITE_PORT_ULONG ((PULONG) ((ULONGLONG)PciCfg2Addr->u.AsUSHORT), *((PULONG) Buffer));
return sizeof(ULONG);
}
NTSTATUS
HalpAssignPCISlotResources (
IN ULONG BusNumber,
IN ULONG Slot,
IN OUT PCM_RESOURCE_LIST *pAllocatedResources
)
/*++
Routine Description:
Reads the targeted device to determine it's required resources.
Calls IoAssignResources to allocate them.
Sets the targeted device with it's assigned resoruces
and returns the assignments to the caller.
Arguments:
Return Value:
STATUS_SUCCESS or error
--*/
{
PBUSHANDLER BusHandler;
UCHAR buffer[PCI_COMMON_HDR_LENGTH];
UCHAR buffer2[PCI_COMMON_HDR_LENGTH];
PPCI_COMMON_CONFIG PciData, PciData2;
PCI_SLOT_NUMBER PciSlot;
ULONG i, j, length, type;
PHYSICAL_ADDRESS Address;
PCM_PARTIAL_RESOURCE_DESCRIPTOR CmDescriptor;
static PCM_RESOURCE_LIST CmResList;
BusHandler = HalpGetPciBusHandler (BusNumber);
if (!BusHandler) {
return 0;
}
*pAllocatedResources = NULL;
PciData = (PPCI_COMMON_CONFIG) buffer;
PciData2 = (PPCI_COMMON_CONFIG) buffer2;
PciSlot = *((PPCI_SLOT_NUMBER) &Slot);
BusNumber = BusHandler->BusNumber;
//
// Read the PCI device's configuration
//
HalpReadPCIConfig (BusHandler, PciSlot, PciData, 0, PCI_COMMON_HDR_LENGTH);
if (PciData->VendorID == PCI_INVALID_VENDORID) {
return STATUS_NO_SUCH_DEVICE;
}
//
// Make a copy of the device's current settings
//
RtlMoveMemory (buffer2, buffer, PCI_COMMON_HDR_LENGTH);
//
// Set resources to all bits on to see what type of resources
// are required.
//
for (j=0; j < PCI_TYPE0_ADDRESSES; j++) {
PciData->u.type0.BaseAddresses[j] = 0xFFFFFFFF;
}
PciData->u.type0.ROMBaseAddress = 0xFFFFFFFF;
PciData->Command &= ~(PCI_ENABLE_IO_SPACE | PCI_ENABLE_MEMORY_SPACE);
PciData->u.type0.ROMBaseAddress &= ~PCI_ROMADDRESS_ENABLED;
HalpWritePCIConfig (BusHandler, PciSlot, PciData, 0, PCI_COMMON_HDR_LENGTH);
HalpReadPCIConfig (BusHandler, PciSlot, PciData, 0, PCI_COMMON_HDR_LENGTH);
HalpPCIPin2Line (BusHandler, RootHandler, PciSlot, PciData);
//
// Restore the device's settings in case we don't complete
//
HalpWritePCIConfig (BusHandler, PciSlot, buffer2, 0, PCI_COMMON_HDR_LENGTH);
//
// Build a CmResource descriptor list for the device
//
if (!CmResList) {
// NtLdr pool is only allocated and never freed. Allocate the
// buffer once, and from then on just use the buffer over
CmResList = ExAllocatePool (PagedPool,
sizeof (CM_RESOURCE_LIST) +
sizeof (CM_PARTIAL_RESOURCE_DESCRIPTOR) * (PCI_TYPE0_ADDRESSES + 2)
);
}
if (!CmResList) {
return STATUS_NO_MEMORY;
}
RtlZeroMemory (CmResList,
sizeof (CM_RESOURCE_LIST) +
sizeof (CM_PARTIAL_RESOURCE_DESCRIPTOR) * (PCI_TYPE0_ADDRESSES + 2)
);
*pAllocatedResources = CmResList;
CmResList->List[0].InterfaceType = PCIBus;
CmResList->List[0].BusNumber = BusNumber;
CmDescriptor = CmResList->List[0].PartialResourceList.PartialDescriptors;
if (PciData->u.type0.InterruptPin) {
CmDescriptor->Type = CmResourceTypeInterrupt;
CmDescriptor->ShareDisposition = CmResourceShareShared;
CmDescriptor->Flags = CM_RESOURCE_INTERRUPT_LEVEL_SENSITIVE;
// in the loader interrupts aren't actually enabled, so just
// pass back the untranslated values
CmDescriptor->u.Interrupt.Level = PciData->u.type0.InterruptLine;
CmDescriptor->u.Interrupt.Vector = PciData->u.type0.InterruptLine;
CmDescriptor->u.Interrupt.Affinity = 1;
CmResList->List[0].PartialResourceList.Count++;
CmDescriptor++;
}
// clear last address index + 1
PciData->u.type0.BaseAddresses[PCI_TYPE0_ADDRESSES] = 0;
if (PciData2->u.type0.ROMBaseAddress & PCI_ROMADDRESS_ENABLED) {
// put rom address in last index+1
PciData->u.type0.BaseAddresses[PCI_TYPE0_ADDRESSES] =
PciData->u.type0.ROMBaseAddress & ~PCI_ADDRESS_IO_SPACE;
PciData2->u.type0.BaseAddresses[PCI_TYPE0_ADDRESSES] =
PciData2->u.type0.ROMBaseAddress & ~PCI_ADDRESS_IO_SPACE;
}
for (j=0; j < PCI_TYPE0_ADDRESSES + 1; j++) {
if (PciData->u.type0.BaseAddresses[j]) {
i = PciData->u.type0.BaseAddresses[j];
// scan for first set bit, that's the length & alignment
length = 1 << (i & PCI_ADDRESS_IO_SPACE ? 2 : 4);
Address.HighPart = 0;
Address.LowPart = PciData2->u.type0.BaseAddresses[j] & ~(length-1);
while (!(i & length) && length) {
length <<= 1;
}
// translate bus specific address
type = (i & PCI_ADDRESS_IO_SPACE) ? 0 : 1;
if (!HalTranslateBusAddress (
PCIBus,
BusNumber,
Address,
&type,
&Address )) {
// translation failed, skip it
continue;
}
// fill in CmDescriptor to return
if (type == 0) {
CmDescriptor->Type = CmResourceTypePort;
CmDescriptor->ShareDisposition = CmResourceShareDeviceExclusive;
CmDescriptor->Flags = CM_RESOURCE_PORT_IO;
CmDescriptor->u.Port.Length = length;
CmDescriptor->u.Port.Start = Address;
} else {
CmDescriptor->Type = CmResourceTypeMemory;
CmDescriptor->ShareDisposition = CmResourceShareDeviceExclusive;
CmDescriptor->Flags = CM_RESOURCE_MEMORY_READ_WRITE;
CmDescriptor->u.Memory.Length = length;
CmDescriptor->u.Memory.Start = Address;
if (j == PCI_TYPE0_ADDRESSES) {
// this is a ROM address
CmDescriptor->Flags = CM_RESOURCE_MEMORY_READ_ONLY;
}
}
CmResList->List[0].PartialResourceList.Count++;
CmDescriptor++;
if (i & PCI_TYPE_64BIT) {
// skip upper half of 64 bit address.
j++;
}
}
}
return STATUS_SUCCESS;
}
| 26.537696 | 98 | 0.568021 |
30c57403c71d4a73ad761a98f7e075a427762cfa | 349 | h | C | sdl1/xargon/src/include/config.h | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/xargon/src/include/config.h | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | sdl1/xargon/src/include/config.h | pdpdds/sdldualsystem | d74ea84cbea705fef62868ba8c693bf7d2555636 | [
"BSD-2-Clause"
] | null | null | null | typedef struct {
int firstthru; // Are we set up?
int joyflag0,joyxl0, joyxc0, joyxr0, joyyu0, joyyc0, joyyd0;
int x_ourmode0;
union {
int sb_exists0;
int musicflag0;
};
int vocflag0;
char pad [64];
} config;
extern config cf;
void cfg_init(int argc, char *argv[]);
int doconfig (void);
extern int nosnd;
// extern int cfgdemo;
| 19.388889 | 61 | 0.681948 |
10c306606ac8573d56bd6e4c89daa4e7e5a06355 | 7,023 | h | C | scipy/optimize/_highs/src/ipm/ipx/src/sparse_matrix.h | Ennosigaeon/scipy | 2d872f7cf2098031b9be863ec25e366a550b229c | [
"BSD-3-Clause"
] | 3 | 2021-12-15T10:06:16.000Z | 2022-02-08T19:55:58.000Z | scipy/optimize/_highs/src/ipm/ipx/src/sparse_matrix.h | Ennosigaeon/scipy | 2d872f7cf2098031b9be863ec25e366a550b229c | [
"BSD-3-Clause"
] | 44 | 2019-06-27T15:56:14.000Z | 2022-03-15T22:21:10.000Z | scipy/optimize/_highs/src/ipm/ipx/src/sparse_matrix.h | Ennosigaeon/scipy | 2d872f7cf2098031b9be863ec25e366a550b229c | [
"BSD-3-Clause"
] | 4 | 2019-07-25T01:57:45.000Z | 2021-04-29T06:54:23.000Z | // Copyright (c) 2018 ERGO-Code. See license.txt for license.
#ifndef IPX_SPARSE_MATRIX_H_
#define IPX_SPARSE_MATRIX_H_
#include <vector>
#include "ipx_internal.h"
namespace ipx {
// Sparse matrix in CSC format.
class SparseMatrix {
public:
SparseMatrix();
SparseMatrix(Int nrow, Int ncol);
SparseMatrix(Int nrow, Int ncol, Int min_capacity);
Int rows() const { return nrow_; }
Int cols() const { return colptr_.size()-1; }
Int entries() const { return colptr_.back(); }
// # entries in column j
Int entries(Int j) const { return end(j)-begin(j); }
// Maximum # entries that can be stored in the matrix.
Int capacity() const { return rowidx_.size(); }
// Increases capacity if necessary such that capacity() >= min_capacity.
// Matrix remains unchanged, pointers are invalidated.
void reserve(Int min_capacity);
// Changes matrix dimensions. Matrix becomes empty, pointers are
// invalidated.
void resize(Int nrow, Int ncol, Int min_capacity = 0);
// Identical to resize(0,0).
void clear();
// Builds matrix from data in compressed column format. The matrix data must
// be valid (no duplicates, no out of range indices, no inf/nan values);
// this is not checked. The row indices in the input matrix need not be
// sorted, but those in the output matrix will be.
void LoadFromArrays(Int nrow, Int ncol, const Int* Abegin, const Int* Aend,
const Int* Ai, const double* Ax);
Int begin(Int j) const { return colptr_[j]; }
Int end(Int j) const { return colptr_[j+1]; }
// Accesses entry at position @pos by value.
Int index(Int pos) const { return rowidx_[pos]; }
double value(Int pos) const { return values_[pos]; }
// Accesses entry at position @pos by reference.
Int& index(Int pos) { return rowidx_[pos]; }
double& value(Int pos) { return values_[pos]; }
// Accesses underlying arrays.
const Int *colptr() const { return colptr_.data(); }
const Int *rowidx() const { return rowidx_.data(); }
const double *values() const { return values_.data(); }
Int *colptr() { return colptr_.data(); }
Int *rowidx() { return rowidx_.data(); }
double *values() { return values_.data(); }
// Stores the entries in each column in increasing order of index.
void SortIndices();
// The following methods provide a queue for adding new columns to the
// matrix. Entries in the queue are not part of the matrix (so do not
// contribute to entries()).
// Appends an entry to the end of the queue.
void push_back(Int i, double x) {
rowidx_queue_.push_back(i);
values_queue_.push_back(x);
}
// Returns # entries in the queue.
Int queue_size() const { return rowidx_queue_.size(); }
// Accesses entry at position @pos in the queue by value.
Int qindex(Int pos) const { return rowidx_queue_[pos]; }
double qvalue(Int pos) const { return values_queue_[pos]; }
// Accesses entry at position @pos in the queue by reference.
Int& qindex(Int pos) { return rowidx_queue_[pos]; }
double& qvalue(Int pos) { return values_queue_[pos]; }
// Makes new column from queue. The queue becomes empty and cols()
// increases by 1.
void add_column();
// Discards queue.
void clear_queue();
private:
// Returns true if row indices are sorted.
bool IsSorted() const;
Int nrow_;
std::vector<Int> colptr_;
std::vector<Int> rowidx_;
std::vector<double> values_;
std::vector<Int> rowidx_queue_;
std::vector<double> values_queue_;
};
// Builds transpose of matrix.
SparseMatrix Transpose(const SparseMatrix& A);
// Resizes @AT as necessary and fills with the tranpose of A.
void Transpose(const SparseMatrix& A, SparseMatrix& AT);
// Returns a copy of A[:,cols].
SparseMatrix CopyColumns(const SparseMatrix& A, const std::vector<Int>& cols);
// Permutes rows in place so that row i becomes row perm[i].
void PermuteRows(SparseMatrix& A, const std::vector<Int>& perm);
// Multiplies column j by s.
inline void ScaleColumn(SparseMatrix& A, Int j, double s) {
Int p1 = A.begin(j);
Int p2 = A.end(j);
for (Int p = p1; p < p2; p++)
A.value(p) *= s;
}
// Removes diagonal entries from A. If @diag is not NULL, then it must be an
// array of dimension A.cols() that holds the diagonal of A on return. Diagonal
// entries that are not present in A are set to zero in @diag. Returns the #
// entries removed from A.
Int RemoveDiagonal(SparseMatrix& A, double* diag);
// Returns dot(A[:,j], rhs).
inline double DotColumn(const SparseMatrix& A, Int j, const Vector& rhs) {
Int p1 = A.begin(j);
Int p2 = A.end(j);
double d = 0.0;
for (Int p = p1; p < p2; p++)
d += rhs[A.index(p)] * A.value(p);
return d;
}
// Updates lhs := lhs + alpha * A[:,j].
inline void ScatterColumn(const SparseMatrix& A, Int j, double alpha,
Vector& lhs) {
Int p1 = A.begin(j);
Int p2 = A.end(j);
for (Int p = p1; p < p2; p++)
lhs[A.index(p)] += alpha * A.value(p);
}
// Updates lhs := lhs + alpha*A*rhs or lhs := lhs + alpha*A'*rhs.
// @trans: 't' or 'T' for transposed product.
void MultiplyAdd(const SparseMatrix& A, const Vector& rhs, double alpha,
Vector& lhs, char trans);
// Updates lhs := lhs + A*A'*rhs or lhs := lhs + A*D*D*A'*rhs,
// where D is diagonal matrix if @D != NULL.
void AddNormalProduct(const SparseMatrix& A, const double* D, const Vector& rhs,
Vector& lhs);
// Triangular solve with sparse matrix.
// @x: right-hand side on entry, left-hand side on return.
// @trans: 't' or 'T' for transposed system.
// @uplo: must have *uplo == 'u' or *uplo == 'U' if A is upper triangular;
// otherwise A is lower triangular.
// @unitdiag: nonzero if A has a unit diagonal that is not stored.
// Returns the # nonzeros in the solution.
Int TriangularSolve(const SparseMatrix& A, Vector& x, char trans,
const char* uplo, int unitdiag);
// Solves (L*U) x = x.
// L unit lower triangular, stored without diagonal.
// U upper triangular, diagonal element at end of column.
void ForwardSolve(const SparseMatrix& L, const SparseMatrix& U, Vector& x);
// Solves (L*U)' x = x.
// L unit lower triangular, stored without diagonal.
// U upper triangular, diagonal element at end of column.
void BackwardSolve(const SparseMatrix& L, const SparseMatrix& U, Vector& x);
// Returns the 1-norm and infinity-norm of A.
double Onenorm(const SparseMatrix& A);
double Infnorm(const SparseMatrix& A);
// Estimates the 1-norm of inverse(A).
// @A must be square and lower or upper triangular.
// @uplo: must have *uplo == 'u' or *uplo == 'U' if A is upper triangular;
// otherwise A is lower triangular.
// @unitdiag: nonzero if A has a unit diagonal that is not stored.
double NormestInverse(const SparseMatrix& A, const char* uplo, int unitdiag);
} // namespace ipx
#endif // IPX_SPARSE_MATRIX_H_
| 35.469697 | 80 | 0.660402 |
e754beba879ebc9bc0ce8266c0994674a81e94af | 4,240 | h | C | include/aby/gadgets.h | TKussel/SecureEpilinker | fd953970f43b2574e5c0b8118ef17b1ced59e400 | [
"BSL-1.0",
"MIT"
] | 7 | 2019-11-16T12:32:16.000Z | 2020-11-24T12:58:26.000Z | include/aby/gadgets.h | TKussel/SecureEpilinker | fd953970f43b2574e5c0b8118ef17b1ced59e400 | [
"BSL-1.0",
"MIT"
] | 2 | 2021-06-11T13:35:00.000Z | 2021-06-18T07:47:13.000Z | include/aby/gadgets.h | TKussel/SecureEpilinker | fd953970f43b2574e5c0b8118ef17b1ced59e400 | [
"BSL-1.0",
"MIT"
] | 2 | 2021-06-11T12:07:32.000Z | 2022-03-16T13:21:55.000Z | /**
\file sel/aby/gadgets.h
\author Sebastian Stammler <sebastian.stammler@cysec.de>
\copyright SEL - Secure EpiLinker
Copyright (C) 2018 Computational Biology & Simulation Group TU-Darmstadt
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
\brief ABY circuit gadgets
*/
#ifndef SEL_ABY_GADGETS_H
#define SEL_ABY_GADGETS_H
#pragma once
#include <functional>
#include "Share.h"
namespace sel {
template <class ShareT> struct Quotient { ShareT num, den; };
using ArithQuotient = Quotient<ArithShare>;
using BoolQuotient = Quotient<BoolShare>;
template <class ShareT>
using UnaryOp = std::function<ShareT (const ShareT&)>;
template <class ShareT>
using BinaryOp = std::function<ShareT (const ShareT&, const ShareT&)>;
template <class ShareT>
using QuotientSelector = std::function<BoolShare (const Quotient<ShareT>&, const Quotient<ShareT>&)>;
template <class ShareT>
using T2BConverter = std::function<BoolShare (const ShareT&)>;
using A2BConverter = std::function<BoolShare (const ArithShare&)>;
template <class ShareT>
using B2TConverter = std::function<ShareT (const BoolShare&)>;
using B2AConverter = std::function<ArithShare (const BoolShare&)>;
template<class ShareT>
void print_share(const Quotient<ShareT>& q, const std::string& msg);
/**
* Accumulates all values in simd_share as if it was first split and then
* binary-accumulated using op. Returns a share of same bitlen and nvals=1.
*
* More efficient than binary accumulate because share is repetitively split and
* then op applied to only two values, effectively dividing nvals by 2 in each
* iteration. If nvals is odd, remainder share is saved and later appended if
* there is another odd split.
*/
BoolShare split_accumulate(BoolShare simd_share, const BinaryOp<BoolShare>& op);
/**
* Like split_accumulate but more specific to running a selector op_select which
* returns a share with only one wire. This share is then muxed to select either
* the first or second part of a split share. The same selection process is also
* applied in parallel to target.
* Output will be saved to input references, so initial shares are overwritten.
*/
void split_select_target(BoolShare& selector, BoolShare& target,
const BinaryOp<BoolShare>& op_select);
template <class ShareT>
QuotientSelector<ShareT> make_max_selector(const T2BConverter<ShareT>& to_bool);
template <class ShareT>
QuotientSelector<ShareT> make_min_selector(const T2BConverter<ShareT>& to_bool);
template <class ShareT>
QuotientSelector<ShareT> make_max_tie_selector(const T2BConverter<ShareT>& to_bool,
const size_t den_bits = 0);
template <class ShareT>
QuotientSelector<ShareT> make_min_tie_selector(const T2BConverter<ShareT>& to_bool,
const size_t den_bits = 0);
template <class ShareT>
ShareT sum(const std::vector<ShareT>&);
BoolQuotient max_tie(const std::vector<BoolQuotient>& qs);
ArithQuotient max_tie(const std::vector<ArithQuotient>& qs,
const A2BConverter& to_bool, const B2AConverter& to_arith,
const size_t den_bits = 0);
BoolShare max(const std::vector<BoolShare>&);
BoolQuotient max(const ArithQuotient& a, const ArithQuotient& b,
const A2BConverter& to_bool);
ArithQuotient max(const ArithQuotient& a, const ArithQuotient& b,
const A2BConverter& to_bool, const B2AConverter& to_arith);
ArithQuotient max(const std::vector<ArithQuotient>& qs,
const A2BConverter& to_bool, const B2AConverter& to_arith);
BoolShare ascending_numbers_constant(BooleanCircuit* bcirc,
size_t nvals, size_t start = 0);
} // namespace sel
#endif /* end of include guard: SEL_ABY_GADGETS_H */
| 40 | 103 | 0.763443 |
a2dde3a2eb4660ce5bea75ca136cf2ffa38a8966 | 5,419 | h | C | usb/descriptor.h | soralis0912/laks | bb53c9ab6978eed594ab694a5fbfcd33c3483f08 | [
"BSD-2-Clause"
] | null | null | null | usb/descriptor.h | soralis0912/laks | bb53c9ab6978eed594ab694a5fbfcd33c3483f08 | [
"BSD-2-Clause"
] | null | null | null | usb/descriptor.h | soralis0912/laks | bb53c9ab6978eed594ab694a5fbfcd33c3483f08 | [
"BSD-2-Clause"
] | 1 | 2022-03-15T06:59:15.000Z | 2022-03-15T06:59:15.000Z | #ifndef DESCRIPTOR_H
#define DESCRIPTOR_H
#include <stdint.h>
template <typename A, typename B>
struct X {
A a;
B b;
} __attribute__((packed));
template <typename A>
constexpr A pack(A a) {
return a;
}
template <typename A, typename... R>
constexpr auto pack(A a, R... r) -> X<A, decltype(pack(r...))> {
return {a, pack(r...)};
}
struct Device_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint16_t idVendor;
uint16_t idProduct;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
uint8_t bNumConfigurations;
} __attribute__((packed));
constexpr Device_desc device_desc(
uint16_t bcdUSB,
uint8_t bDeviceClass,
uint8_t bDeviceSubClass,
uint8_t bDeviceProtocol,
uint8_t bMaxPacketSize0,
uint16_t idVendor,
uint16_t idProduct,
uint16_t bcdDevice,
uint8_t iManufacturer,
uint8_t iProduct,
uint8_t iSerialNumber,
uint8_t bNumConfigurations
) {
return {
sizeof(Device_desc),
1,
bcdUSB,
bDeviceClass,
bDeviceSubClass,
bDeviceProtocol,
bMaxPacketSize0,
idVendor,
idProduct,
bcdDevice,
iManufacturer,
iProduct,
iSerialNumber,
bNumConfigurations
};
}
struct Configuration_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationvalue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t bMaxPower;
} __attribute__((packed));
template <typename... R>
constexpr auto configuration_desc(
uint8_t bNumInterfaces,
uint8_t bConfigurationvalue,
uint8_t iConfiguration,
uint8_t bmAttributes,
uint8_t bMaxPower,
R... r
) -> decltype(pack(Configuration_desc(), r...)) {
return pack(Configuration_desc {
sizeof(Configuration_desc),
2,
sizeof(pack(Configuration_desc(), r...)),
bNumInterfaces,
bConfigurationvalue,
iConfiguration,
bmAttributes,
bMaxPower
}, r...);
}
struct Interface_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iInterface;
} __attribute__((packed));
template <typename... R>
constexpr auto interface_desc(
uint8_t bInterfaceNumber,
uint8_t bAlternateSetting,
uint8_t bNumEndpoints,
uint8_t bInterfaceClass,
uint8_t bInterfaceSubClass,
uint8_t bInterfaceProtocol,
uint8_t iInterface,
R... r
) -> decltype(pack(Interface_desc(), r...)) {
return pack(Interface_desc {
sizeof(Interface_desc),
4,
bInterfaceNumber,
bAlternateSetting,
bNumEndpoints,
bInterfaceClass,
bInterfaceSubClass,
bInterfaceProtocol,
iInterface
}, r...);
}
struct Endpoint_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
uint8_t bRefresh;
uint8_t bSynchAddress;
} __attribute__((packed));
constexpr Endpoint_desc endpoint_desc(
uint8_t bEndpointAddress,
uint8_t bmAttributes,
uint16_t wMaxPacketSize,
uint8_t bInterval,
uint8_t bRefresh = 0,
uint8_t bSynchAddress = 0
) {
return {
sizeof(Endpoint_desc),
5,
bEndpointAddress,
bmAttributes,
wMaxPacketSize,
bInterval,
bRefresh,
bSynchAddress
};
}
struct IAD_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bFirstInterface;
uint8_t bInterfaceCount;
uint8_t bFunctionClass;
uint8_t bFunctionSubClass;
uint8_t bFunctionProtocol;
uint8_t iFunction;
} __attribute__((packed));
template <typename... R>
constexpr auto iad_desc(
uint8_t bFirstInterface,
uint8_t bInterfaceCount,
uint8_t bFunctionClass,
uint8_t bFunctionSubClass,
uint8_t bFunctionProtocol,
uint8_t iFunction,
R... r
) -> decltype(pack(IAD_desc(), r...)) {
return pack(IAD_desc {
sizeof(IAD_desc),
0x0b,
bFirstInterface,
bInterfaceCount,
bFunctionClass,
bFunctionSubClass,
bFunctionProtocol,
iFunction
}, r...);
}
struct CDC_Header_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint16_t bcdCDC;
} __attribute__((packed));
constexpr CDC_Header_desc cdc_header_desc(
uint16_t bcdCDC
) {
return {
sizeof(CDC_Header_desc),
0x24,
0x00,
bcdCDC
};
}
struct CDC_Call_Management_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bmCapabilities;
uint8_t bDataInterface;
} __attribute__((packed));
constexpr CDC_Call_Management_desc cdc_call_management_desc(
uint8_t bmCapabilities,
uint8_t bDataInterface
) {
return {
sizeof(CDC_Call_Management_desc),
0x24,
0x01,
bmCapabilities,
bDataInterface
};
}
struct CDC_ACM_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bmCapabilities;
} __attribute__((packed));
constexpr CDC_ACM_desc cdc_acm_desc(
uint8_t bmCapabilities
) {
return {
sizeof(CDC_ACM_desc),
0x24,
0x02,
bmCapabilities
};
}
struct CDC_Union_desc {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bControlInterface;
uint8_t bSubordinateInterface0;
} __attribute__((packed));
constexpr CDC_Union_desc cdc_union_desc(
uint8_t bControlInterface,
uint8_t bSubordinateInterface0
) {
return {
sizeof(CDC_Union_desc),
0x24,
0x06,
bControlInterface,
bSubordinateInterface0
};
}
#endif
| 18.621993 | 64 | 0.760103 |
2ebb3441a08f711030e5722702fdd538f1a76b46 | 3,188 | h | C | pire/stub/memstreams.h | orivej/pire | 1df29444fcdff712320f9b6af6f28188838b774c | [
"MIT"
] | 212 | 2015-01-09T12:15:30.000Z | 2022-01-25T17:20:22.000Z | pire/stub/memstreams.h | orivej/pire | 1df29444fcdff712320f9b6af6f28188838b774c | [
"MIT"
] | 35 | 2015-07-28T11:50:39.000Z | 2020-09-17T20:48:43.000Z | pire/stub/memstreams.h | orivej/pire | 1df29444fcdff712320f9b6af6f28188838b774c | [
"MIT"
] | 34 | 2015-02-10T12:43:27.000Z | 2022-01-25T17:20:27.000Z | /*
* memstreams.h -- a wrapper providing istream/ostream interface
* for memory ranges.
*
* Copyright (c) 2007-2010, Dmitry Prokoptsev <dprokoptsev@gmail.com>,
* Alexander Gololobov <agololobov@gmail.com>
*
* This file is part of Pire, the Perl Incompatible
* Regular Expressions library.
*
* Pire is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pire is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
* You should have received a copy of the GNU Lesser Public License
* along with Pire. If not, see <http://www.gnu.org/licenses>.
*/
#ifndef PIRE_STUB_MEMSTREAMS_H_INCLUDED
#define PIRE_STUB_MEMSTREAMS_H_INCLUDED
#include <vector>
#include <iostream>
#include <memory.h>
namespace Pire {
class MemBuffer {
public:
MemBuffer(const std::vector<char>& buf): m_buf(&buf) {}
const char* Data() const { return m_buf->empty() ? 0 : &(*m_buf)[0]; }
size_t Size() const { return m_buf->size(); }
typedef std::vector<char>::const_iterator Iterator;
Iterator Begin() const { return m_buf->begin(); }
Iterator End() const { return m_buf->end(); }
private:
const std::vector<char>* m_buf;
};
typedef MemBuffer::Iterator BufferIterator; // For compatibility with Arcadia
class BufferOutputBase {
private:
class StreamBuf: public std::basic_streambuf<char> {
public:
MemBuffer Buf() const { return MemBuffer(buf); }
protected:
typedef std::char_traits<char> Traits;
Traits::int_type overflow(Traits::int_type x)
{
buf.push_back((char) x);
return x;
}
std::streamsize xsputn(const char* ptr, std::streamsize size)
{
buf.insert(buf.end(), ptr, ptr + size);
return size;
}
private:
std::vector<char> buf;
};
protected:
StreamBuf m_rdbuf;
public:
BufferOutputBase() { }
MemBuffer Buffer() const { return m_rdbuf.Buf(); }
};
class BufferOutput: public BufferOutputBase, public std::ostream {
public:
BufferOutput() : std::ostream(&m_rdbuf) {}
};
class MemoryInputBase {
private:
class StreamBuf: public std::basic_streambuf<char> {
public:
StreamBuf(const char* data, size_t size)
{
char* p = const_cast<char*>(data);
setg(p, p, p+size);
}
protected:
std::streamsize xsgetn(char* ptr, std::streamsize size)
{
size = std::min<std::streamsize>(size, egptr() - gptr());
memcpy(ptr, gptr(), size);
gbump(size);
return size;
}
};
protected:
StreamBuf m_rdbuf;
public:
MemoryInputBase(const char* data, size_t size): m_rdbuf(data, size) {}
};
class MemoryInput : protected MemoryInputBase, public std::istream {
public:
MemoryInput(const char* data, size_t size)
: MemoryInputBase(data, size)
, std::istream(&m_rdbuf)
{
exceptions(badbit | eofbit);
}
};
}
#endif
| 25.504 | 78 | 0.672208 |
a2eb9affce556a6616e590fc4d64c11f03ec1a52 | 978 | h | C | PrivateFrameworks/EmbeddedAcousticRecognition.framework/_EARSpeechRecognitionAudioBuffer.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | PrivateFrameworks/EmbeddedAcousticRecognition.framework/_EARSpeechRecognitionAudioBuffer.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | PrivateFrameworks/EmbeddedAcousticRecognition.framework/_EARSpeechRecognitionAudioBuffer.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/EmbeddedAcousticRecognition.framework/EmbeddedAcousticRecognition
*/
@interface _EARSpeechRecognitionAudioBuffer : NSObject {
struct shared_ptr<quasar::RecogAudioBufferBase> {
struct RecogAudioBufferBase {} *px;
struct shared_count {
struct sp_counted_base {} *pi_;
} pn;
} _buffer;
bool _cancelled;
bool _ended;
NSObject<OS_dispatch_queue> * _queue;
_EARSpeechRecognizer * _speechRecognizer;
}
- (id).cxx_construct;
- (void).cxx_destruct;
- (id)_initWithAudioBuffer:(struct shared_ptr<quasar::RecogAudioBufferBase> { struct RecogAudioBufferBase {} *x1; struct shared_count { struct sp_counted_base {} *x_2_1_1; } x2; })arg1 speechRecognizer:(id)arg2;
- (void)addAudioSampleData:(id)arg1;
- (void)addAudioSamples:(const short*)arg1 count:(unsigned long long)arg2;
- (void)cancelRecognition;
- (void)dealloc;
- (void)endAudio;
@end
| 34.928571 | 211 | 0.731084 |
264a86c78db9f018b6a613fb09695d4c0f3366cf | 81,862 | c | C | mono/mini/mini-hppa.c | slluis/mono | db8728e398d405bc1256bc2d76870c87d2e82ffc | [
"Apache-2.0"
] | 1 | 2021-08-05T04:41:05.000Z | 2021-08-05T04:41:05.000Z | mono/mini/mini-hppa.c | slluis/mono | db8728e398d405bc1256bc2d76870c87d2e82ffc | [
"Apache-2.0"
] | null | null | null | mono/mini/mini-hppa.c | slluis/mono | db8728e398d405bc1256bc2d76870c87d2e82ffc | [
"Apache-2.0"
] | 3 | 2016-10-20T19:06:51.000Z | 2022-03-20T23:28:53.000Z | /*
* mini-hppa.c: HPPA backend for the Mono code generator
*
* Copyright (c) 2007 Randolph Chung
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "mini.h"
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <unistd.h>
#include <sys/mman.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/tokentype.h>
#include <mono/utils/mono-math.h>
#include "mini-hppa.h"
#include "trace.h"
#include "cpu-hppa.h"
#define ALIGN_TO(val,align) (((val) + ((align) - 1)) & ~((align) - 1))
#define SIGNAL_STACK_SIZE (64 * 1024)
#define DEBUG(a) // a
#define DEBUG_FUNC_ENTER() // printf("Entering %s\n", __FUNCTION__)
#define DEBUG_FUNC_EXIT() // printf("Exiting %s\n", __FUNCTION__)
static const guchar
branch_b0_table [] = {
TRUE, /* OP_HPPA_BEQ */
FALSE, /* OP_HPPA_BGE */
FALSE, /* OP_HPPA_BGT */
TRUE, /* OP_HPPA_BLE */
TRUE, /* OP_HPPA_BLT */
FALSE, /* OP_HPPA_BNE */
FALSE, /* OP_HPPA_BGE_UN */
FALSE, /* OP_HPPA_BGT_UN */
TRUE, /* OP_HPPA_BLE_UN */
TRUE, /* OP_HPPA_BLT_UN */
};
static const guchar
branch_b1_table [] = {
HPPA_CMP_COND_EQ, /* OP_HPPA_BEQ */
HPPA_CMP_COND_SLT, /* OP_HPPA_BGE */
HPPA_CMP_COND_SLE, /* OP_HPPA_BGT */
HPPA_CMP_COND_SLE, /* OP_HPPA_BLE */
HPPA_CMP_COND_SLT, /* OP_HPPA_BLT */
HPPA_CMP_COND_EQ, /* OP_HPPA_BNE_UN */
HPPA_CMP_COND_ULT, /* OP_HPPA_BGE_UN */
HPPA_CMP_COND_ULE, /* OP_HPPA_BGT_UN */
HPPA_CMP_COND_ULE, /* OP_HPPA_BLE_UN */
HPPA_CMP_COND_ULT, /* OP_HPPA_BLT_UN */
};
/* Note that these are inverted from the OP_xxx, because we nullify
* the branch if the condition is met
*/
static const guchar
float_branch_table [] = {
26, /* OP_FBEQ */
11, /* OP_FBGE */
15, /* OP_FBGT */
19, /* OP_FBLE */
23, /* OP_FBLT */
4, /* OP_FBNE_UN */
8, /* OP_FBGE_UN */
13, /* OP_FBGT_UN */
17, /* OP_FBLE_UN */
20, /* OP_FBLT_UN */
};
static const guchar
float_ceq_table [] = {
26, /* OP_FCEQ */
15, /* OP_FCGT */
13, /* OP_FCGT_UN */
23, /* OP_FCLT */
21, /* OP_FCLT_UN */
};
/*
* Branches have short (14 or 17 bit) targets on HPPA. To make longer jumps,
* we will need to rely on stubs - basically we create stub structures in
* the epilogue that uses a long branch to the destination, and any short
* jumps inside a method that cannot reach the destination directly will
* branch first to the stub.
*/
typedef struct MonoOvfJump {
union {
MonoBasicBlock *bb;
const char *exception;
} data;
guint32 ip_offset;
} MonoOvfJump;
/* Create a literal 0.0 double for FNEG */
double hppa_zero = 0;
const char*
mono_arch_regname (int reg)
{
static const char * rnames[] = {
"hppa_r0", "hppa_r1", "hppa_rp", "hppa_r3", "hppa_r4",
"hppa_r5", "hppa_r6", "hppa_r7", "hppa_r8", "hppa_r9",
"hppa_r10", "hppa_r11", "hppa_r12", "hppa_r13", "hppa_r14",
"hppa_r15", "hppa_r16", "hppa_r17", "hppa_r18", "hppa_r19",
"hppa_r20", "hppa_r21", "hppa_r22", "hppa_r23", "hppa_r24",
"hppa_r25", "hppa_r26", "hppa_r27", "hppa_r28", "hppa_r29",
"hppa_sp", "hppa_r31"
};
if (reg >= 0 && reg < MONO_MAX_IREGS)
return rnames [reg];
return "unknown";
}
const char*
mono_arch_fregname (int reg)
{
static const char *rnames [] = {
"hppa_fr0", "hppa_fr1", "hppa_fr2", "hppa_fr3", "hppa_fr4",
"hppa_fr5", "hppa_fr6", "hppa_fr7", "hppa_fr8", "hppa_fr9",
"hppa_fr10", "hppa_fr11", "hppa_fr12", "hppa_fr13", "hppa_fr14",
"hppa_fr15", "hppa_fr16", "hppa_fr17", "hppa_fr18", "hppa_fr19",
"hppa_fr20", "hppa_fr21", "hppa_fr22", "hppa_fr23", "hppa_fr24",
"hppa_fr25", "hppa_fr26", "hppa_fr27", "hppa_fr28", "hppa_fr29",
"hppa_fr30", "hppa_fr31",
};
if (reg >= 0 && reg < MONO_MAX_FREGS)
return rnames [reg];
else
return "unknown";
}
/*
* Initialize the cpu to execute managed code.
*/
void
mono_arch_cpu_init (void)
{
guint32 dummy;
mono_arch_cpu_optimizazions(&dummy);
}
/*
* Initialize architecture specific code.
*/
void
mono_arch_init (void)
{
}
/*
* Cleanup architecture specific code.
*/
void
mono_arch_cleanup (void)
{
}
/*
* This function returns the optimizations supported on this cpu.
*/
guint32
mono_arch_cpu_optimizazions (guint32 *exclude_mask)
{
guint32 opts = 0;
*exclude_mask = 0;
return opts;
}
void
mono_arch_flush_icache (guint8 *code, gint size)
{
guint8* p = (guint8*)((guint32)code & ~(0x3f));
guint8* end = (guint8*)((guint32)code + size);
while (p < end) {
__asm__ __volatile__ ("fdc %%r0(%%sr3, %0)\n"
"sync\n"
"fic %%r0(%%sr3, %0)\n"
"sync\n"
: : "r"(p));
p += 32; /* can be 64 on pa20 cpus */
}
}
void
mono_arch_flush_register_windows (void)
{
/* No register windows on hppa */
}
typedef enum {
ArgInIReg,
ArgInIRegPair,
ArgInFReg,
ArgInDReg,
ArgOnStack,
} ArgStorage;
typedef struct {
gint16 offset;
gint16 size;
guint8 type;
gint8 reg;
ArgStorage storage;
} ArgInfo;
typedef struct {
int nargs;
guint32 stack_usage;
int struct_return;
ArgInfo ret;
ArgInfo sig_cookie;
ArgInfo args [1];
} CallInfo;
#define PARAM_REGS 4
#define ARGS_OFFSET 36
static void
add_parameter (CallInfo *cinfo, ArgInfo *ainfo, MonoType *type)
{
int is_fp = (type->type == MONO_TYPE_R4 || type->type == MONO_TYPE_R8);
int ofs, align;
DEBUG_FUNC_ENTER ();
ainfo->reg = -1;
ainfo->size = mono_type_size (type, &align);
ainfo->type = type->type;
if (ainfo->size <= 4) {
cinfo->stack_usage += 4;
ainfo->offset = cinfo->stack_usage - (4 - ainfo->size);
}
else if (ainfo->size <= 8)
{
cinfo->stack_usage += 8;
cinfo->stack_usage = ALIGN_TO (cinfo->stack_usage, 8);
ainfo->offset = cinfo->stack_usage - (8 - ainfo->size);
}
else
{
cinfo->stack_usage += ainfo->size;
cinfo->stack_usage = ALIGN_TO (cinfo->stack_usage, align);
ainfo->offset = cinfo->stack_usage;
}
ofs = (ALIGN_TO (ainfo->offset, 4) - ARGS_OFFSET) / 4;
if (ofs < PARAM_REGS) {
if (!is_fp) {
if (ainfo->size <= 4)
ainfo->storage = ArgInIReg;
else
ainfo->storage = ArgInIRegPair;
ainfo->reg = hppa_r26 - ofs;
} else if (type->type == MONO_TYPE_R4) {
ainfo->storage = ArgInFReg;
ainfo->reg = hppa_fr4 + ofs;
} else { /* type->type == MONO_TYPE_R8 */
ainfo->storage = ArgInDReg;
ainfo->reg = hppa_fr4 + ofs;
}
}
else {
/* frame pointer based offset */
ainfo->reg = hppa_r3;
ainfo->storage = ArgOnStack;
}
/* All offsets are negative relative to the frame pointer */
ainfo->offset = -ainfo->offset;
DEBUG_FUNC_EXIT ();
}
static void
analyze_return (CallInfo *cinfo, MonoMethodSignature *sig)
{
MonoType *type;
int align;
int size;
type = sig->ret;
size = mono_type_size (type, &align);
/* ref: mono_type_to_stind */
cinfo->ret.type = type->type;
if (type->byref) {
cinfo->ret.storage = ArgInIReg;
cinfo->ret.reg = hppa_r28;
} else {
handle_enum:
switch (type->type) {
case MONO_TYPE_VOID:
break;
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_PTR:
case MONO_TYPE_FNPTR:
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
cinfo->ret.storage = ArgInIReg;
cinfo->ret.reg = hppa_r28;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
cinfo->ret.storage = ArgInIRegPair;
cinfo->ret.reg = hppa_r28;
break;
case MONO_TYPE_R4:
cinfo->ret.storage = ArgInFReg;
cinfo->ret.reg = hppa_fr4;
break;
case MONO_TYPE_R8:
cinfo->ret.storage = ArgInDReg;
cinfo->ret.reg = hppa_fr4;
break;
case MONO_TYPE_GENERICINST:
type = &type->data.generic_class->container_class->byval_arg;
goto handle_enum;
case MONO_TYPE_VALUETYPE:
if (type->data.klass->enumtype) {
type = mono_class_enum_basetype (type->data.klass);
goto handle_enum;
}
/* Fall through */
case MONO_TYPE_TYPEDBYREF:
cinfo->struct_return = 1;
/* cinfo->ret.storage tells us how the ABI expects
* the parameter to be returned
*/
if (size <= 4) {
cinfo->ret.storage = ArgInIReg;
cinfo->ret.reg = hppa_r28;
} else if (size <= 8) {
cinfo->ret.storage = ArgInIRegPair;
cinfo->ret.reg = hppa_r28;
} else {
cinfo->ret.storage = ArgOnStack;
cinfo->ret.reg = hppa_sp;
}
/* We always allocate stack space for this because the
* arch-indep code expects us to
*/
cinfo->stack_usage += size;
cinfo->stack_usage = ALIGN_TO (cinfo->stack_usage, align);
cinfo->ret.offset = -cinfo->stack_usage;
break;
default:
g_error ("Can't handle as return value 0x%x", sig->ret->type);
}
}
}
/*
* get_call_info:
*
* Obtain information about a call according to the calling convention.
*/
static CallInfo*
get_call_info (MonoMethodSignature *sig, gboolean is_pinvoke)
{
guint32 i;
int n = sig->hasthis + sig->param_count;
CallInfo *cinfo;
MonoType *type;
MonoType ptrtype;
int dummy;
ptrtype.type = MONO_TYPE_PTR;
DEBUG_FUNC_ENTER();
cinfo = g_malloc0 (sizeof (CallInfo) + (sizeof (ArgInfo) * n));
/* The area below ARGS_OFFSET is the linkage area... */
cinfo->stack_usage = ARGS_OFFSET - 4;
/* -4, because the first argument will allocate the area it needs */
/* this */
if (sig->hasthis) {
add_parameter (cinfo, cinfo->args + 0, &ptrtype);
DEBUG (printf ("param <this>: assigned to reg %s offset %d\n", mono_arch_regname (cinfo->args[0].reg), cinfo->args[0].offset));
}
/* TODO: What to do with varargs? */
for (i = 0; i < sig->param_count; ++i) {
ArgInfo *ainfo = &cinfo->args [sig->hasthis + i];
if (sig->params [i]->byref)
type = &ptrtype;
else
type = mono_type_get_underlying_type (sig->params [i]);
add_parameter (cinfo, ainfo, type);
DEBUG (printf ("param %d: type %d size %d assigned to reg %s offset %d\n", i, type->type, mono_type_size (type, &dummy), mono_arch_regname (ainfo->reg), ainfo->offset));
}
analyze_return (cinfo, sig);
DEBUG_FUNC_EXIT();
return cinfo;
}
GList *
mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
{
GList *vars = NULL;
int i;
DEBUG_FUNC_ENTER();
for (i = 0; i < cfg->num_varinfo; i++) {
MonoInst *ins = cfg->varinfo [i];
MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
/* unused vars */
if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos)
continue;
if ((ins->flags & (MONO_INST_IS_DEAD|MONO_INST_VOLATILE|MONO_INST_INDIRECT)) ||
(ins->opcode != OP_LOCAL && ins->opcode != OP_ARG))
continue;
if (mono_is_regsize_var (ins->inst_vtype)) {
g_assert (MONO_VARINFO (cfg, i)->reg == -1);
g_assert (i == vmv->idx);
vars = mono_varlist_insert_sorted (cfg, vars, vmv, FALSE);
}
}
DEBUG_FUNC_EXIT();
return vars;
}
GList *
mono_arch_get_global_int_regs (MonoCompile *cfg)
{
GList *regs = NULL;
int i;
/* r3 is sometimes used as our frame pointer, so don't allocate it
* r19 is the GOT pointer, don't allocate it either
*/
DEBUG_FUNC_ENTER();
for (i = 4; i <= 18; i++)
regs = g_list_prepend (regs, GUINT_TO_POINTER (i));
DEBUG_FUNC_EXIT();
return regs;
}
/*
* mono_arch_regalloc_cost:
*
* Return the cost, in number of memory references, of the action of
* allocating the variable VMV into a register during global register
* allocation.
*/
guint32
mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv)
{
/* FIXME */
return 0;
}
/*
* Set var information according to the calling convention.
* The locals var stuff should most likely be split in another method.
*
* updates m->stack_offset based on the amount of stack space needed for
* local vars
*/
void
mono_arch_allocate_vars (MonoCompile *m)
{
MonoMethodSignature *sig;
MonoMethodHeader *header;
MonoInst *inst;
int i, offset, size, align, curinst;
guint32 stack_ptr;
guint rettype;
CallInfo *cinfo;
DEBUG_FUNC_ENTER();
m->flags |= MONO_CFG_HAS_SPILLUP;
header = m->header;
sig = mono_method_signature (m->method);
DEBUG (printf ("Allocating locals - incoming params:\n"));
cinfo = get_call_info (sig, FALSE);
/*
* We use the ABI calling conventions for managed code as well.
*/
if (m->flags & MONO_CFG_HAS_ALLOCA) {
stack_ptr = hppa_r4;
m->used_int_regs |= 1 << hppa_r4;
} else {
stack_ptr = hppa_sp;
}
/* Before this function is called, we would have looked at all
* calls from this method and figured out how much space is needed
* for the param area.
*
* Locals are allocated backwards, right before the param area
*/
/* TODO: in some cases we don't need the frame pointer... */
m->frame_reg = hppa_r3;
offset = m->param_area;
/* Return values can be passed back either in four ways:
* r28 is used for data <= 4 bytes (32-bit ABI)
* r28/r29 are used for data >4 && <= 8 bytes
* fr4 is used for floating point data
* data larger than 8 bytes is returned on the stack pointed to
* by r28
*
* This code needs to be in sync with how CEE_RET is handled
* in mono_method_to_ir (). In some cases when we return small
* structs, the ABI specifies that they should be returned in
* registers, but the code in mono_method_to_ir () always emits
* a memcpy for valuetype returns, so we need to make sure we
* allocate space on the stack for this copy.
*/
if (cinfo->struct_return) {
/* this is used to stash the incoming r28 pointer */
offset += sizeof (gpointer);
m->ret->opcode = OP_REGOFFSET;
m->ret->inst_basereg = stack_ptr;
m->ret->inst_offset = -offset;
} else if (sig->ret->type != MONO_TYPE_VOID) {
m->ret->opcode = OP_REGVAR;
m->ret->inst_c0 = cinfo->ret.reg;
}
curinst = m->locals_start;
for (i = curinst; i < m->num_varinfo; ++i) {
inst = m->varinfo [i];
if (inst->opcode == OP_REGVAR) {
DEBUG (printf ("allocating local %d to %s\n", i, mono_arch_regname (inst->dreg)));
continue;
}
if (inst->flags & MONO_INST_IS_DEAD)
continue;
/* inst->backend.is_pinvoke indicates native sized value types, this is used by the
* pinvoke wrappers when they call functions returning structure */
if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
else
size = mini_type_stack_size (cfg->generic_sharing_context, inst->inst_vtype, &align);
/*
* This is needed since structures containing doubles must be doubleword
* aligned.
* FIXME: Do this only if needed.
*/
if (MONO_TYPE_ISSTRUCT (inst->inst_vtype))
align = 8;
/*
* variables are accessed as negative offsets from hppa_sp
*/
inst->opcode = OP_REGOFFSET;
inst->inst_basereg = stack_ptr;
offset += size;
offset = ALIGN_TO (offset, align);
inst->inst_offset = -offset;
DEBUG (printf ("allocating local %d (size = %d) to [%s - %d]\n", i, size, mono_arch_regname (inst->inst_basereg), -inst->inst_offset));
}
if (sig->call_convention == MONO_CALL_VARARG) {
/* TODO */
}
for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
ArgInfo *ainfo = &cinfo->args [i];
inst = m->args [i];
if (inst->opcode != OP_REGVAR) {
switch (ainfo->storage) {
case ArgInIReg:
case ArgInIRegPair:
case ArgInFReg:
case ArgInDReg:
/* Currently mono requests all incoming registers
* be assigned to a stack location :-(
*/
#if 0
if (!(inst->flags & (MONO_INST_VOLATILE | MONO_INST_INDIRECT))) {
inst->opcode = OP_REGVAR;
inst->dreg = ainfo->reg;
DEBUG (printf ("param %d in register %s\n", i, mono_arch_regname (inst->dreg)));
break;
}
#endif
/* fallthrough */
case ArgOnStack:
inst->opcode = OP_REGOFFSET;
inst->inst_basereg = hppa_r3;
inst->inst_offset = ainfo->offset;
DEBUG (printf ("param %d stored on stack [%s - %d]\n", i, mono_arch_regname (hppa_r3), -inst->inst_offset));
break;
}
}
}
m->stack_offset = offset; /* Includes cfg->param_area */
g_free (cinfo);
DEBUG_FUNC_EXIT();
}
/*
* take the arguments and generate the arch-specific
* instructions to properly call the function in call.
* This includes pushing, moving arguments to the right register
* etc.
*
* sets call->stack_usage and cfg->param_area
*/
MonoCallInst*
mono_arch_call_opcode (MonoCompile *cfg, MonoBasicBlock* bb, MonoCallInst *call, int is_virtual)
{
MonoInst *arg, *in;
MonoMethodSignature *sig;
int i, n;
CallInfo *cinfo;
ArgInfo *ainfo;
DEBUG_FUNC_ENTER();
DEBUG (printf ("is_virtual = %d\n", is_virtual));
sig = call->signature;
n = sig->param_count + sig->hasthis;
DEBUG (printf ("Calling method with %d parameters\n", n));
cinfo = get_call_info (sig, sig->pinvoke);
// DEBUG
g_assert (sig->call_convention != MONO_CALL_VARARG);
for (i = 0; i < n; ++i) {
ainfo = &cinfo->args [i];
if ((sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) {
/* TODO */
}
if (is_virtual && i == 0) {
/* the argument will be attached to the call instruction */
in = call->args [i];
call->used_iregs |= 1 << ainfo->reg;
} else {
MONO_INST_NEW (cfg, arg, OP_OUTARG);
in = call->args [i];
arg->cil_code = in->cil_code;
arg->inst_left = in;
arg->inst_call = call;
arg->type = in->type;
/* prepend, we'll need to reverse them later */
arg->next = call->out_args;
call->out_args = arg;
switch (ainfo->storage) {
case ArgInIReg:
case ArgInIRegPair: {
MonoHPPAArgInfo *ai = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoHPPAArgInfo));
ai->reg = ainfo->reg;
ai->size = ainfo->size;
ai->offset = ainfo->offset;
ai->pass_in_reg = 1;
arg->backend.data = ai;
call->used_iregs |= 1 << ainfo->reg;
if (ainfo->storage == ArgInIRegPair)
call->used_iregs |= 1 << (ainfo->reg + 1);
if (ainfo->type == MONO_TYPE_VALUETYPE)
arg->opcode = OP_OUTARG_VT;
break;
}
case ArgOnStack: {
MonoHPPAArgInfo *ai = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoHPPAArgInfo));
ai->reg = hppa_sp;
ai->size = ainfo->size;
ai->offset = ainfo->offset;
ai->pass_in_reg = 0;
arg->backend.data = ai;
if (ainfo->type == MONO_TYPE_VALUETYPE)
arg->opcode = OP_OUTARG_VT;
else
arg->opcode = OP_OUTARG_MEMBASE;
call->used_iregs |= 1 << ainfo->reg;
break;
}
case ArgInFReg:
arg->backend.reg3 = ainfo->reg;
arg->opcode = OP_OUTARG_R4;
call->used_fregs |= 1 << ainfo->reg;
break;
case ArgInDReg:
arg->backend.reg3 = ainfo->reg;
arg->opcode = OP_OUTARG_R8;
call->used_fregs |= 1 << ainfo->reg;
break;
default:
NOT_IMPLEMENTED;
}
}
}
/*
* Reverse the call->out_args list.
*/
{
MonoInst *prev = NULL, *list = call->out_args, *next;
while (list) {
next = list->next;
list->next = prev;
prev = list;
list = next;
}
call->out_args = prev;
}
call->stack_usage = cinfo->stack_usage;
cfg->param_area = MAX (cfg->param_area, call->stack_usage);
cfg->param_area = ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT);
cfg->flags |= MONO_CFG_HAS_CALLS;
g_free (cinfo);
DEBUG_FUNC_EXIT();
return call;
}
void
mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb)
{
}
void
mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb)
{
DEBUG_FUNC_ENTER();
DEBUG_FUNC_EXIT();
}
static void
insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *to_insert)
{
if (ins == NULL) {
ins = bb->code;
bb->code = to_insert;
to_insert->next = ins;
} else {
to_insert->next = ins->next;
ins->next = to_insert;
}
}
#define NEW_INS(cfg,dest,op) do { \
(dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
(dest)->opcode = (op); \
insert_after_ins (bb, last_ins, (dest)); \
} while (0)
static int
map_to_reg_reg_op (int op)
{
switch (op) {
case OP_ADD_IMM:
return CEE_ADD;
case OP_SUB_IMM:
return CEE_SUB;
case OP_AND_IMM:
return CEE_AND;
case OP_COMPARE_IMM:
return OP_COMPARE;
case OP_ADDCC_IMM:
return OP_ADDCC;
case OP_ADC_IMM:
return OP_ADC;
case OP_SUBCC_IMM:
return OP_SUBCC;
case OP_SBB_IMM:
return OP_SBB;
case OP_OR_IMM:
return CEE_OR;
case OP_XOR_IMM:
return CEE_XOR;
case OP_MUL_IMM:
return CEE_MUL;
case OP_LOAD_MEMBASE:
return OP_LOAD_MEMINDEX;
case OP_LOADI4_MEMBASE:
return OP_LOADI4_MEMINDEX;
case OP_LOADU4_MEMBASE:
return OP_LOADU4_MEMINDEX;
case OP_LOADU1_MEMBASE:
return OP_LOADU1_MEMINDEX;
case OP_LOADI2_MEMBASE:
return OP_LOADI2_MEMINDEX;
case OP_LOADU2_MEMBASE:
return OP_LOADU2_MEMINDEX;
case OP_LOADI1_MEMBASE:
return OP_LOADI1_MEMINDEX;
case OP_LOADR4_MEMBASE:
return OP_LOADR4_MEMINDEX;
case OP_LOADR8_MEMBASE:
return OP_LOADR8_MEMINDEX;
case OP_STOREI1_MEMBASE_REG:
return OP_STOREI1_MEMINDEX;
case OP_STOREI2_MEMBASE_REG:
return OP_STOREI2_MEMINDEX;
case OP_STOREI4_MEMBASE_REG:
return OP_STOREI4_MEMINDEX;
case OP_STORE_MEMBASE_REG:
return OP_STORE_MEMINDEX;
case OP_STORER4_MEMBASE_REG:
return OP_STORER4_MEMINDEX;
case OP_STORER8_MEMBASE_REG:
return OP_STORER8_MEMINDEX;
case OP_STORE_MEMBASE_IMM:
return OP_STORE_MEMBASE_REG;
case OP_STOREI1_MEMBASE_IMM:
return OP_STOREI1_MEMBASE_REG;
case OP_STOREI2_MEMBASE_IMM:
return OP_STOREI2_MEMBASE_REG;
case OP_STOREI4_MEMBASE_IMM:
return OP_STOREI4_MEMBASE_REG;
}
g_assert_not_reached ();
}
/*
* Remove from the instruction list the instructions that can't be
* represented with very simple instructions with no register
* requirements.
*/
void
mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb)
{
MonoInst *ins, *next, *temp, *last_ins = NULL;
int imm;
MONO_BB_FOR_EACH_INS (bb, ins) {
loop_start:
switch (ins->opcode) {
case OP_ADD_IMM:
case OP_ADDCC_IMM:
if (!hppa_check_bits (ins->inst_imm, 11)) {
NEW_INS (cfg, temp, OP_ICONST);
temp->inst_c0 = ins->inst_imm;
temp->dreg = mono_alloc_ireg (cfg);
ins->sreg2 = temp->dreg;
ins->opcode = map_to_reg_reg_op (ins->opcode);
}
break;
case OP_SUB_IMM:
case OP_SUBCC_IMM:
if (!hppa_check_bits (ins->inst_imm, 11)) {
NEW_INS (cfg, temp, OP_ICONST);
temp->inst_c0 = ins->inst_imm;
temp->dreg = mono_alloc_ireg (cfg);
ins->sreg2 = temp->dreg;
ins->opcode = map_to_reg_reg_op (ins->opcode);
}
break;
case OP_MUL_IMM:
if (ins->inst_imm == 1) {
ins->opcode = OP_MOVE;
break;
}
if (ins->inst_imm == 0) {
ins->opcode = OP_ICONST;
ins->inst_c0 = 0;
break;
}
imm = mono_is_power_of_two (ins->inst_imm);
if (imm > 0) {
ins->opcode = OP_SHL_IMM;
ins->inst_imm = imm;
break;
}
else {
int tmp = mono_alloc_ireg (cfg);
NEW_INS (cfg, temp, OP_ICONST);
temp->inst_c0 = ins->inst_c0;
temp->dreg = tmp;
ins->opcode = CEE_MUL;
ins->sreg2 = tmp;
/* Need to rewrite the CEE_MUL too... */
goto loop_start;
}
break;
case CEE_MUL: {
int freg1 = mono_alloc_freg (cfg);
int freg2 = mono_alloc_freg (cfg);
NEW_INS(cfg, temp, OP_STORE_MEMBASE_REG);
temp->sreg1 = ins->sreg1;
temp->inst_destbasereg = hppa_sp;
temp->inst_offset = -16;
NEW_INS(cfg, temp, OP_LOADR4_MEMBASE);
temp->dreg = freg1;
temp->inst_basereg = hppa_sp;
temp->inst_offset = -16;
NEW_INS(cfg, temp, OP_STORE_MEMBASE_REG);
temp->sreg1 = ins->sreg2;
temp->inst_destbasereg = hppa_sp;
temp->inst_offset = -16;
NEW_INS(cfg, temp, OP_LOADR4_MEMBASE);
temp->dreg = freg2;
temp->inst_basereg = hppa_sp;
temp->inst_offset = -16;
NEW_INS (cfg, temp, OP_HPPA_XMPYU);
temp->dreg = freg2;
temp->sreg1 = freg1;
temp->sreg2 = freg2;
NEW_INS(cfg, temp, OP_HPPA_STORER4_RIGHT);
temp->sreg1 = freg2;
temp->inst_destbasereg = hppa_sp;
temp->inst_offset = -16;
ins->opcode = OP_LOAD_MEMBASE;
ins->inst_basereg = hppa_sp;
ins->inst_offset = -16;
}
break;
default:
break;
}
last_ins = ins;
}
bb->last_ins = last_ins;
bb->max_vreg = cfg->next_vreg;
}
void
hppa_patch (guint32 *code, const gpointer target)
{
guint32 ins = *code;
gint32 val = (gint32)target;
gint32 disp = (val - (gint32)code - 8) >> 2;
int reg1, reg2;
DEBUG (printf ("patching 0x%08x (0x%08x) to point to 0x%08x (disp = %d)\n", code, ins, val, disp));
switch (*code >> 26) {
case 0x08: /* ldil, next insn can be a ldo, ldw, or ble */
*code = *code & ~0x1fffff;
*code = *code | hppa_op_imm21 (hppa_lsel (val));
code++;
if ((*code >> 26) == 0x0D) { /* ldo */
*code = *code & ~0x3fff;
*code = *code | hppa_op_imm14 (hppa_rsel (val));
} else if ((*code >> 26) == 0x12) { /* ldw */
*code = *code & ~0x3fff;
*code = *code | hppa_op_imm14 (hppa_rsel (val));
} else if ((*code >> 26) == 0x39) { /* ble */
*code = *code & ~0x1f1ffd;
*code = *code | hppa_op_imm17 (hppa_rsel (val));
}
break;
case 0x3A: /* bl */
if (disp == 0) {
hppa_nop (code);
break;
}
if (!hppa_check_bits (disp, 17))
goto jump_overflow;
reg1 = (*code >> 21) & 0x1f;
*code = (*code & ~0x1f1ffd) | hppa_op_imm17(disp);
break;
case 0x20: /* combt */
case 0x22: /* combf */
if (!hppa_check_bits (disp >> 2, 12))
goto jump_overflow;
*code = (*code & ~0x1ffd) | hppa_op_imm12(disp);
break;
default:
g_warning ("Unpatched opcode %x\n", *code >> 26);
}
return;
jump_overflow:
g_warning ("cannot branch to target, insn is %08x, displacement is %d\n", (int)*code, (int)disp);
g_assert_not_reached ();
}
static guint32 *
emit_float_to_int (MonoCompile *cfg, guint32 *code, int dreg, int sreg, int size, gboolean is_signed)
{
/* sreg is a float, dreg is an integer reg. */
hppa_fcnvfxt (code, HPPA_FP_FMT_DBL, HPPA_FP_FMT_SGL, sreg, sreg);
hppa_fstws (code, sreg, 0, -16, hppa_sp);
hppa_ldw (code, -16, hppa_sp, dreg);
if (!is_signed) {
if (size == 1)
hppa_extru (code, dreg, 31, 8, dreg);
else if (size == 2)
hppa_extru (code, dreg, 31, 16, dreg);
} else {
if (size == 1)
hppa_extrs (code, dreg, 31, 8, dreg);
else if (size == 2)
hppa_extrs (code, dreg, 31, 16, dreg);
}
return code;
}
/* Clobbers r1, r20, r21 */
static guint32 *
emit_memcpy (guint32 *code, int doff, int dreg, int soff, int sreg, int size)
{
/* r20 is the destination */
hppa_set (code, doff, hppa_r20);
hppa_add (code, hppa_r20, dreg, hppa_r20);
/* r21 is the source */
hppa_set (code, soff, hppa_r21);
hppa_add (code, hppa_r21, sreg, hppa_r21);
while (size >= 4) {
hppa_ldw (code, 0, hppa_r21, hppa_r1);
hppa_stw (code, hppa_r1, 0, hppa_r20);
hppa_ldo (code, 4, hppa_r21, hppa_r21);
hppa_ldo (code, 4, hppa_r20, hppa_r20);
size -= 4;
}
while (size >= 2) {
hppa_ldh (code, 0, hppa_r21, hppa_r1);
hppa_sth (code, hppa_r1, 0, hppa_r20);
hppa_ldo (code, 2, hppa_r21, hppa_r21);
hppa_ldo (code, 2, hppa_r20, hppa_r20);
size -= 2;
}
while (size > 0) {
hppa_ldb (code, 0, hppa_r21, hppa_r1);
hppa_stb (code, hppa_r1, 0, hppa_r20);
hppa_ldo (code, 1, hppa_r21, hppa_r21);
hppa_ldo (code, 1, hppa_r20, hppa_r20);
size -= 1;
}
return code;
}
/*
* mono_arch_get_vcall_slot_addr:
*
* Determine the vtable slot used by a virtual call.
*/
gpointer*
mono_arch_get_vcall_slot_addr (guint8 *code8, mgreg_t *regs)
{
guint32 *code = (guint32*)((unsigned long)code8 & ~3);
DEBUG_FUNC_ENTER();
code -= 2;
/* This is the special virtual call token */
if (code [-1] != 0x34000eee) /* ldo 0x777(r0),r0 */
return NULL;
if ((code [0] >> 26) == 0x39 && /* ble */
(code [-2] >> 26) == 0x12) { /* ldw */
guint32 ldw = code [-2];
guint32 reg = (ldw >> 21) & 0x1f;
gint32 disp = ((ldw & 1) ? (-1 << 13) : 0) | ((ldw & 0x3fff) >> 1);
/* FIXME: we are not guaranteed that reg is saved in the LMF.
* In fact, it probably isn't, since it is allocated as a
* callee register. Right now just return an address; this
* is sufficient for non-AOT operation
*/
// return (gpointer)((guint8*)regs [reg] + disp);
return code;
}
else
g_assert_not_reached ();
DEBUG_FUNC_EXIT();
}
/* ins->dreg = *(ins->inst_desgbasereg + ins->inst_offset) */
#define EMIT_LOAD_MEMBASE(ins, op) do { \
if (!hppa_check_bits (ins->inst_offset, 14)) { \
hppa_set (code, ins->inst_offset, hppa_r1); \
hppa_ ## op ## x (code, hppa_r1, ins->inst_basereg, ins->dreg); \
} \
else { \
hppa_ ## op (code, ins->inst_offset, ins->inst_basereg, ins->dreg); \
} \
} while (0)
#define EMIT_COND_BRANCH_FLAGS(ins,r1,r2,b0,b1) do {\
if (b0) \
hppa_combf (code, r1, r2, b1, 2); \
else \
hppa_combt (code, r1, r2, b1, 2); \
hppa_nop (code); \
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
hppa_bl (code, 0, hppa_r0); \
hppa_nop (code); \
} while (0)
#define EMIT_COND_BRANCH(ins,r1,r2,cond) EMIT_COND_BRANCH_FLAGS(ins, r1, r2, branch_b0_table [(cond)], branch_b1_table [(cond)])
#define EMIT_FLOAT_COND_BRANCH_FLAGS(ins,r1,r2,b0) do {\
hppa_fcmp (code, HPPA_FP_FMT_DBL, b0, r1, r2); \
hppa_ftest (code, 0); \
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
hppa_bl (code, 8, hppa_r0); \
hppa_nop (code); \
} while (0)
#define EMIT_FLOAT_COND_BRANCH(ins,r1,r2,cond) EMIT_FLOAT_COND_BRANCH_FLAGS(ins, r1, r2, float_branch_table [cond])
#define EMIT_COND_SYSTEM_EXCEPTION_FLAGS(r1,r2,b0,b1,exc_name) \
do { \
MonoOvfJump *ovfj = mono_mempool_alloc (cfg->mempool, sizeof (MonoOvfJump)); \
ovfj->data.exception = (exc_name); \
ovfj->ip_offset = (guint8*)code - cfg->native_code; \
hppa_bl (code, 8, hppa_r2); \
hppa_depi (code, 0, 31, 2, hppa_r2); \
hppa_ldo (code, 8, hppa_r2, hppa_r2); \
if (b0) \
hppa_combf (code, r1, r2, b1, 2); \
else \
hppa_combt (code, r1, r2, b1, 2); \
hppa_nop (code); \
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_EXC_OVF, ovfj); \
hppa_bl (code, 0, hppa_r0); \
hppa_nop (code); \
} while (0)
#define EMIT_COND_SYSTEM_EXCEPTION(r1,r2,cond,exc_name) EMIT_COND_SYSTEM_EXCEPTION_FLAGS(r1, r2, branch_b0_table [(cond)], branch_b1_table [(cond)], (exc_name))
/* TODO: MEM_INDEX_REG - cannot be r1 */
#define MEM_INDEX_REG hppa_r31
/* *(ins->inst_destbasereg + ins->inst_offset) = ins->inst_imm */
#define EMIT_STORE_MEMBASE_IMM(ins, op) do { \
guint32 sreg; \
if (ins->inst_imm == 0) \
sreg = hppa_r0; \
else { \
hppa_set (code, ins->inst_imm, hppa_r1); \
sreg = hppa_r1; \
} \
if (!hppa_check_bits (ins->inst_offset, 14)) { \
hppa_set (code, ins->inst_offset, MEM_INDEX_REG); \
hppa_addl (code, ins->inst_destbasereg, MEM_INDEX_REG, MEM_INDEX_REG); \
hppa_ ## op (code, sreg, 0, MEM_INDEX_REG); \
} \
else { \
hppa_ ## op (code, sreg, ins->inst_offset, ins->inst_destbasereg); \
} \
} while (0)
/* *(ins->inst_destbasereg + ins->inst_offset) = ins->sreg1 */
#define EMIT_STORE_MEMBASE_REG(ins, op) do { \
if (!hppa_check_bits (ins->inst_offset, 14)) { \
hppa_set (code, ins->inst_offset, MEM_INDEX_REG); \
hppa_addl (code, ins->inst_destbasereg, MEM_INDEX_REG, MEM_INDEX_REG); \
hppa_ ## op (code, ins->sreg1, 0, MEM_INDEX_REG); \
} \
else { \
hppa_ ## op (code, ins->sreg1, ins->inst_offset, ins->inst_destbasereg); \
} \
} while (0)
void
mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
{
MonoInst *ins;
MonoCallInst *call;
guint offset;
guint32 *code = (guint32*)(cfg->native_code + cfg->code_len);
MonoInst *last_ins = NULL;
int max_len, cpos;
const char *spec;
DEBUG_FUNC_ENTER();
if (cfg->verbose_level > 2)
g_print ("[%s::%s] Basic block %d starting at offset 0x%x\n", cfg->method->klass->name, cfg->method->name, bb->block_num, bb->native_offset);
cpos = bb->max_offset;
if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
NOT_IMPLEMENTED;
}
MONO_BB_FOR_EACH_INS (bb, ins) {
guint8* code_start;
offset = (guint8*)code - cfg->native_code;
spec = ins_get_spec (ins->opcode);
max_len = ((guint8 *)spec) [MONO_INST_LEN];
if (offset > (cfg->code_size - max_len - 16)) {
cfg->code_size *= 2;
cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
code = (guint32*)(cfg->native_code + offset);
mono_jit_stats.code_reallocs++;
}
code_start = (guint8*)code;
// if (ins->cil_code)
// g_print ("cil code\n");
mono_debug_record_line_number (cfg, ins, offset);
switch (ins->opcode) {
case OP_RELAXED_NOP:
break;
case OP_STOREI1_MEMBASE_IMM:
EMIT_STORE_MEMBASE_IMM (ins, stb);
break;
case OP_STOREI2_MEMBASE_IMM:
EMIT_STORE_MEMBASE_IMM (ins, sth);
break;
case OP_STORE_MEMBASE_IMM:
case OP_STOREI4_MEMBASE_IMM:
EMIT_STORE_MEMBASE_IMM (ins, stw);
break;
case OP_STOREI1_MEMBASE_REG:
EMIT_STORE_MEMBASE_REG (ins, stb);
break;
case OP_STOREI2_MEMBASE_REG:
EMIT_STORE_MEMBASE_REG (ins, sth);
break;
case OP_STORE_MEMBASE_REG:
case OP_STOREI4_MEMBASE_REG:
EMIT_STORE_MEMBASE_REG (ins, stw);
break;
case OP_LOADU1_MEMBASE:
EMIT_LOAD_MEMBASE (ins, ldb);
break;
case OP_LOADI1_MEMBASE:
EMIT_LOAD_MEMBASE (ins, ldb);
hppa_extrs (code, ins->dreg, 31, 8, ins->dreg);
break;
case OP_LOADU2_MEMBASE:
EMIT_LOAD_MEMBASE (ins, ldh);
break;
case OP_LOADI2_MEMBASE:
EMIT_LOAD_MEMBASE (ins, ldh);
hppa_extrs (code, ins->dreg, 31, 16, ins->dreg);
break;
case OP_LOAD_MEMBASE:
case OP_LOADI4_MEMBASE:
case OP_LOADU4_MEMBASE:
EMIT_LOAD_MEMBASE (ins, ldw);
break;
case CEE_CONV_I1:
hppa_extrs (code, ins->sreg1, 31, 8, ins->dreg);
break;
case CEE_CONV_I2:
hppa_extrs (code, ins->sreg1, 31, 16, ins->dreg);
break;
case CEE_CONV_U1:
hppa_extru (code, ins->sreg1, 31, 8, ins->dreg);
break;
case CEE_CONV_U2:
hppa_extru (code, ins->sreg1, 31, 16, ins->dreg);
break;
case CEE_CONV_U:
case CEE_CONV_I4:
case CEE_CONV_U4:
case OP_MOVE:
if (ins->sreg1 != ins->dreg)
hppa_copy (code, ins->sreg1, ins->dreg);
break;
case OP_SETLRET:
hppa_copy (code, ins->sreg1 + 1, ins->dreg);
hppa_copy (code, ins->sreg1, ins->dreg + 1);
break;
case OP_BREAK:
/* break 4,8 - this is what gdb normally uses... */
*code++ = 0x00010004;
break;
case OP_ADDCC:
case CEE_ADD:
hppa_add (code, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_ADC:
hppa_addc (code, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_ADDCC_IMM:
case OP_ADD_IMM:
hppa_addi (code, ins->inst_imm, ins->sreg1, ins->dreg);
break;
case OP_ADC_IMM:
hppa_set (code, ins->inst_imm, hppa_r1);
hppa_addc (code, ins->sreg1, hppa_r1, ins->dreg);
break;
case OP_HPPA_ADD_OVF: {
MonoOvfJump *ovfj = mono_mempool_alloc (cfg->mempool, sizeof (MonoOvfJump));
hppa_bl (code, 8, hppa_r2);
hppa_depi (code, 0, 31, 2, hppa_r2);
hppa_ldo (code, 12, hppa_r2, hppa_r2);
if (ins->backend.reg3 == CEE_ADD_OVF)
hppa_add_cond (code, HPPA_ADD_COND_NSV, ins->sreg1, ins->sreg2, ins->dreg);
else
hppa_add_cond (code, HPPA_ADD_COND_NUV, ins->sreg1, ins->sreg2, ins->dreg);
ovfj->data.exception = "OverflowException";
ovfj->ip_offset = (guint8*)code - cfg->native_code;
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_EXC_OVF, ovfj);
hppa_bl_n (code, 8, hppa_r0);
break;
}
case OP_HPPA_ADDC_OVF: {
MonoOvfJump *ovfj = mono_mempool_alloc (cfg->mempool, sizeof (MonoOvfJump));
hppa_bl (code, 8, hppa_r2);
hppa_depi (code, 0, 31, 2, hppa_r2);
hppa_ldo (code, 12, hppa_r2, hppa_r2);
if (ins->backend.reg3 == OP_LADD_OVF)
hppa_addc_cond (code, HPPA_ADD_COND_NSV, ins->sreg1, ins->sreg2, ins->dreg);
else
hppa_addc_cond (code, HPPA_ADD_COND_NUV, ins->sreg1, ins->sreg2, ins->dreg);
ovfj->data.exception = "OverflowException";
ovfj->ip_offset = (guint8*)code - cfg->native_code;
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_EXC_OVF, ovfj);
hppa_bl_n (code, 8, hppa_r0);
break;
}
case OP_SUBCC:
case CEE_SUB:
hppa_sub (code, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_SUBCC_IMM:
case OP_SUB_IMM:
hppa_addi (code, -ins->inst_imm, ins->sreg1, ins->dreg);
break;
case OP_SBB:
hppa_subb (code, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_SBB_IMM:
hppa_set (code, ins->inst_imm, hppa_r1);
hppa_subb (code, ins->sreg1, hppa_r1, ins->dreg);
break;
case OP_HPPA_SUB_OVF: {
MonoOvfJump *ovfj = mono_mempool_alloc (cfg->mempool, sizeof (MonoOvfJump));
hppa_bl (code, 8, hppa_r2);
hppa_depi (code, 0, 31, 2, hppa_r2);
hppa_ldo (code, 12, hppa_r2, hppa_r2);
hppa_sub_cond (code, HPPA_SUB_COND_NSV, ins->sreg1, ins->sreg2, ins->dreg);
ovfj->data.exception = "OverflowException";
ovfj->ip_offset = (guint8*)code - cfg->native_code;
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_EXC_OVF, ovfj);
hppa_bl_n (code, 8, hppa_r0);
break;
}
case OP_HPPA_SUBB_OVF: {
MonoOvfJump *ovfj = mono_mempool_alloc (cfg->mempool, sizeof (MonoOvfJump));
hppa_bl (code, 8, hppa_r2);
hppa_depi (code, 0, 31, 2, hppa_r2);
hppa_ldo (code, 12, hppa_r2, hppa_r2);
hppa_subb_cond (code, HPPA_SUB_COND_NSV, ins->sreg1, ins->sreg2, ins->dreg);
ovfj->data.exception = "OverflowException";
ovfj->ip_offset = (guint8*)code - cfg->native_code;
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_EXC_OVF, ovfj);
hppa_bl_n (code, 8, hppa_r0);
break;
}
case CEE_AND:
hppa_and (code, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_AND_IMM:
hppa_set (code, ins->inst_imm, hppa_r1);
hppa_and (code, ins->sreg1, hppa_r1, ins->dreg);
break;
case CEE_OR:
hppa_or (code, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_OR_IMM:
hppa_set (code, ins->inst_imm, hppa_r1);
hppa_or (code, ins->sreg1, hppa_r1, ins->dreg);
break;
case CEE_XOR:
hppa_xor (code, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_XOR_IMM:
hppa_set (code, ins->inst_imm, hppa_r1);
hppa_xor (code, ins->sreg1, hppa_r1, ins->dreg);
break;
case CEE_SHL:
if (ins->sreg1 != ins->dreg) {
hppa_shl (code, ins->sreg1, ins->sreg2, ins->dreg);
}
else {
hppa_copy (code, ins->sreg1, hppa_r1);
hppa_shl (code, hppa_r1, ins->sreg2, ins->dreg);
}
break;
case OP_SHL_IMM:
case OP_ISHL_IMM:
g_assert (ins->inst_imm < 32);
if (ins->sreg1 != ins->dreg) {
hppa_zdep (code, ins->sreg1, 31-ins->inst_imm, 32-ins->inst_imm, ins->dreg);
}
else {
hppa_copy (code, ins->sreg1, hppa_r1);
hppa_zdep (code, hppa_r1, 31-ins->inst_imm, 32-ins->inst_imm, ins->dreg);
}
break;
case CEE_SHR:
if (ins->sreg1 != ins->dreg) {
hppa_shr (code, ins->sreg1, ins->sreg2, ins->dreg);
}
else {
hppa_copy (code, ins->sreg1, hppa_r1);
hppa_shr (code, hppa_r1, ins->sreg2, ins->dreg);
}
break;
case OP_SHR_IMM:
g_assert (ins->inst_imm < 32);
if (ins->sreg1 != ins->dreg) {
hppa_extrs (code, ins->sreg1, 31-ins->inst_imm, 32-ins->inst_imm, ins->dreg);
}
else {
hppa_copy (code, ins->sreg1, hppa_r1);
hppa_extrs (code, hppa_r1, 31-ins->inst_imm, 32-ins->inst_imm, ins->dreg);
}
break;
case OP_SHR_UN_IMM:
g_assert (ins->inst_imm < 32);
if (ins->sreg1 != ins->dreg) {
hppa_extru (code, ins->sreg1, 31-ins->inst_imm, 32-ins->inst_imm, ins->dreg);
}
else {
hppa_copy (code, ins->sreg1, hppa_r1);
hppa_extru (code, hppa_r1, 31-ins->inst_imm, 32-ins->inst_imm, ins->dreg);
}
break;
case CEE_SHR_UN:
if (ins->sreg1 != ins->dreg) {
hppa_lshr (code, ins->sreg1, ins->sreg2, ins->dreg);
}
else {
hppa_copy (code, ins->sreg1, hppa_r1);
hppa_lshr (code, hppa_r1, ins->sreg2, ins->dreg);
}
break;
case CEE_NOT:
hppa_not (code, ins->sreg1, ins->dreg);
break;
case CEE_NEG:
hppa_subi (code, 0, ins->sreg1, ins->dreg);
break;
case CEE_MUL:
case OP_MUL_IMM:
/* Should have been rewritten using xmpyu */
g_assert_not_reached ();
case OP_ICONST:
if ((ins->inst_c0 > 0 && ins->inst_c0 >= (1 << 13)) ||
(ins->inst_c0 < 0 && ins->inst_c0 < -(1 << 13))) {
hppa_ldil (code, hppa_lsel (ins->inst_c0), ins->dreg);
hppa_ldo (code, hppa_rsel (ins->inst_c0), ins->dreg, ins->dreg);
} else {
hppa_ldo (code, ins->inst_c0, hppa_r0, ins->dreg);
}
break;
case OP_AOTCONST:
g_assert_not_reached ();
/*
mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
hppa_set_template (code, ins->dreg);
*/
g_warning ("unimplemented opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
NOT_IMPLEMENTED;
break;
case OP_FMOVE:
if (ins->sreg1 != ins->dreg)
hppa_fcpy (code, HPPA_FP_FMT_DBL, ins->sreg1, ins->dreg);
break;
case OP_HPPA_OUTARG_R4CONST:
hppa_set (code, (unsigned int)ins->inst_p0, hppa_r1);
hppa_fldwx (code, hppa_r0, hppa_r1, ins->dreg, 0);
break;
case OP_HPPA_OUTARG_REGOFFSET:
hppa_ldo (code, ins->inst_offset, ins->inst_basereg, ins->dreg);
break;
case OP_JMP:
/*
* Keep in sync with mono_arch_emit_epilog
*/
g_assert (!cfg->method->save_lmf);
mono_add_patch_info (cfg, (guint8*) code - cfg->native_code, MONO_PATCH_INFO_METHOD_JUMP, ins->inst_p0);
hppa_bl (code, 8, hppa_r0);
break;
case OP_CHECK_THIS:
/* ensure ins->sreg1 is not NULL */
hppa_ldw (code, 0, ins->sreg1, hppa_r1);
break;
case OP_ARGLIST:
break;
case OP_FCALL:
case OP_LCALL:
case OP_VCALL:
case OP_VOIDCALL:
case OP_CALL:
call = (MonoCallInst*)ins;
if (ins->flags & MONO_INST_HAS_METHOD)
mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_METHOD, call->method);
else
mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_ABS, call->fptr);
hppa_ldil (code, 0, hppa_r1);
hppa_ldo (code, 0, hppa_r1, hppa_r1);
/*
* We may have loaded an actual function address, or
* it might be a plabel. Check to see if the plabel
* bit is set, and load the actual fptr from it if
* needed
*/
hppa_bb_n (code, HPPA_BIT_COND_MSB_CLR, hppa_r1, 30, 2);
hppa_depi (code, 0, 31, 2, hppa_r1);
hppa_ldw (code, 4, hppa_r1, hppa_r19);
hppa_ldw (code, 0, hppa_r1, hppa_r1);
hppa_ble (code, 0, hppa_r1);
hppa_copy (code, hppa_r31, hppa_r2);
if (call->signature->ret->type == MONO_TYPE_R4)
hppa_fcnvff (code, HPPA_FP_FMT_SGL, HPPA_FP_FMT_DBL, hppa_fr4, hppa_fr4);
break;
case OP_FCALL_REG:
case OP_LCALL_REG:
case OP_VCALL_REG:
case OP_VOIDCALL_REG:
case OP_CALL_REG:
call = (MonoCallInst*)ins;
g_assert (!call->virtual);
hppa_copy (code, ins->sreg1, hppa_r1);
hppa_bb_n (code, HPPA_BIT_COND_MSB_CLR, hppa_r1, 30, 2);
hppa_depi (code, 0, 31, 2, hppa_r1);
hppa_ldw (code, 4, hppa_r1, hppa_r19);
hppa_ldw (code, 0, hppa_r1, hppa_r1);
hppa_ble (code, 0, hppa_r1);
hppa_copy (code, hppa_r31, hppa_r2);
if (call->signature->ret->type == MONO_TYPE_R4)
hppa_fcnvff (code, HPPA_FP_FMT_SGL, HPPA_FP_FMT_DBL, hppa_fr4, hppa_fr4);
break;
case OP_FCALL_MEMBASE:
case OP_LCALL_MEMBASE:
case OP_VCALL_MEMBASE:
case OP_VOIDCALL_MEMBASE:
case OP_CALL_MEMBASE:
call = (MonoCallInst*)ins;
/* jump to ins->inst_sreg1 + ins->inst_offset */
hppa_ldw (code, ins->inst_offset, ins->sreg1, hppa_r1);
/* For virtual calls, emit a special token that can
* be used by get_vcall_slot_addr
*/
if (call->virtual)
hppa_ldo (code, 0x777, hppa_r0, hppa_r0);
hppa_ble (code, 0, hppa_r1);
hppa_copy (code, hppa_r31, hppa_r2);
break;
case OP_LOCALLOC: {
guint32 size_reg;
/* Keep alignment */
hppa_ldo (code, MONO_ARCH_LOCALLOC_ALIGNMENT - 1, ins->sreg1, ins->dreg);
hppa_depi (code, 0, 31, 6, ins->dreg);
hppa_copy (code, hppa_sp, hppa_r1);
hppa_addl (code, ins->dreg, hppa_sp, hppa_sp);
hppa_copy (code, hppa_r1, ins->dreg);
if (ins->flags & MONO_INST_INIT) {
hppa_stw (code, hppa_r0, 0, hppa_r1);
hppa_combt (code, hppa_r1, hppa_sp, HPPA_CMP_COND_ULT, -3);
hppa_ldo (code, 4, hppa_r1, hppa_r1);
}
break;
}
case OP_THROW:
hppa_copy (code, ins->sreg1, hppa_r26);
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD,
(gpointer)"mono_arch_throw_exception");
hppa_ldil (code, 0, hppa_r1);
hppa_ldo (code, 0, hppa_r1, hppa_r1);
hppa_ble (code, 0, hppa_r1);
hppa_copy (code, hppa_r31, hppa_r2);
/* should never return */
*code++ = 0xffeeddcc;
break;
case OP_RETHROW:
hppa_copy (code, ins->sreg1, hppa_r26);
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD,
(gpointer)"mono_arch_rethrow_exception");
hppa_ldil (code, 0, hppa_r1);
hppa_ldo (code, 0, hppa_r1, hppa_r1);
hppa_ble (code, 0, hppa_r1);
hppa_copy (code, hppa_r31, hppa_r2);
/* should never return */
*code++ = 0xffeeddcc;
break;
case OP_START_HANDLER:
if (hppa_check_bits (ins->inst_left->inst_offset, 14))
hppa_stw (code, hppa_r2, ins->inst_left->inst_offset, ins->inst_left->inst_basereg);
else {
hppa_set (code, ins->inst_left->inst_offset, hppa_r1);
hppa_addl (code, ins->inst_left->inst_basereg, hppa_r1, hppa_r1);
hppa_stw (code, hppa_r2, 0, hppa_r1);
}
break;
case OP_ENDFILTER:
if (ins->sreg1 != hppa_r26)
hppa_copy (code, ins->sreg1, hppa_r26);
if (hppa_check_bits (ins->inst_left->inst_offset, 14))
hppa_ldw (code, ins->inst_left->inst_offset, ins->inst_left->inst_basereg, hppa_r2);
else {
hppa_set (code, ins->inst_left->inst_offset, hppa_r1);
hppa_ldwx (code, hppa_r1, ins->inst_left->inst_basereg, hppa_r2);
}
hppa_bv (code, hppa_r0, hppa_r2);
hppa_nop (code);
break;
case OP_ENDFINALLY:
if (hppa_check_bits (ins->inst_left->inst_offset, 14))
hppa_ldw (code, ins->inst_left->inst_offset, ins->inst_left->inst_basereg, hppa_r1);
else {
hppa_set (code, ins->inst_left->inst_offset, hppa_r1);
hppa_ldwx (code, hppa_r1, ins->inst_left->inst_basereg, hppa_r1);
}
hppa_bv (code, hppa_r0, hppa_r1);
hppa_nop (code);
break;
case OP_CALL_HANDLER:
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
hppa_bl (code, 0, hppa_r2);
hppa_nop (code);
break;
case OP_LABEL:
ins->inst_c0 = (guint8*)code - cfg->native_code;
break;
case OP_BR: {
guint32 target;
DEBUG (printf ("target: %p, next: %p, curr: %p, last: %p\n", ins->inst_target_bb, bb->next_bb, ins, bb->last_ins));
mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb);
hppa_bl (code, 8, hppa_r0);
/* TODO: if the branch is too long, we may need to
* use a long-branch sequence:
* hppa_ldil (code, 0, hppa_r1);
* hppa_ldo (code, 0, hppa_r1, hppa_r1);
* hppa_bv (code, hppa_r0, hppa_r1);
*/
hppa_nop (code);
break;
}
case OP_BR_REG:
hppa_bv (code, hppa_r0, ins->sreg1);
hppa_nop(code);
break;
case OP_SWITCH: {
int i;
max_len += 8 * GPOINTER_TO_INT (ins->klass);
if (offset > (cfg->code_size - max_len - 16)) {
cfg->code_size += max_len;
cfg->code_size *= 2;
cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
code = cfg->native_code + offset;
code_start = (guint8*)code;
}
hppa_blr (code, ins->sreg1, hppa_r0);
hppa_nop (code);
for (i = 0; i < GPOINTER_TO_INT (ins->klass); ++i) {
*code++ = 0xdeadbeef;
*code++ = 0xdeadbeef;
}
break;
}
/* comclr is cool :-) */
case OP_HPPA_CEQ:
hppa_comclr_cond (code, HPPA_SUB_COND_NE, ins->sreg1, ins->sreg2, ins->dreg);
hppa_ldo (code, 1, hppa_r0, ins->dreg);
break;
case OP_HPPA_CLT:
hppa_comclr_cond (code, HPPA_SUB_COND_SGE, ins->sreg1, ins->sreg2, ins->dreg);
hppa_ldo (code, 1, hppa_r0, ins->dreg);
break;
case OP_HPPA_CLT_UN:
hppa_comclr_cond (code, HPPA_SUB_COND_UGE, ins->sreg1, ins->sreg2, ins->dreg);
hppa_ldo (code, 1, hppa_r0, ins->dreg);
break;
case OP_HPPA_CGT:
hppa_comclr_cond (code, HPPA_SUB_COND_SLE, ins->sreg1, ins->sreg2, ins->dreg);
hppa_ldo (code, 1, hppa_r0, ins->dreg);
break;
case OP_HPPA_CGT_UN:
hppa_comclr_cond (code, HPPA_SUB_COND_ULE, ins->sreg1, ins->sreg2, ins->dreg);
hppa_ldo (code, 1, hppa_r0, ins->dreg);
break;
case OP_CEQ:
case OP_CLT:
case OP_CLT_UN:
case OP_CGT:
case OP_CGT_UN:
case OP_COND_EXC_EQ:
case OP_COND_EXC_NE_UN:
case OP_COND_EXC_LT:
case OP_COND_EXC_LT_UN:
case OP_COND_EXC_GT:
case OP_COND_EXC_GT_UN:
case OP_COND_EXC_GE:
case OP_COND_EXC_GE_UN:
case OP_COND_EXC_LE:
case OP_COND_EXC_LE_UN:
case OP_COND_EXC_OV:
case OP_COND_EXC_NO:
case OP_COND_EXC_C:
case OP_COND_EXC_NC:
case OP_COND_EXC_IOV:
case OP_COND_EXC_IC:
case CEE_BEQ:
case CEE_BNE_UN:
case CEE_BLT:
case CEE_BLT_UN:
case CEE_BGT:
case CEE_BGT_UN:
case CEE_BGE:
case CEE_BGE_UN:
case CEE_BLE:
case CEE_BLE_UN:
case OP_COMPARE:
case OP_LCOMPARE:
case OP_ICOMPARE:
case OP_COMPARE_IMM:
case OP_ICOMPARE_IMM:
g_warning ("got opcode %s in %s(), should be reduced\n", mono_inst_name (ins->opcode), __FUNCTION__);
g_assert_not_reached ();
break;
case OP_HPPA_BEQ:
case OP_HPPA_BNE:
case OP_HPPA_BLT:
case OP_HPPA_BLT_UN:
case OP_HPPA_BGT:
case OP_HPPA_BGT_UN:
case OP_HPPA_BGE:
case OP_HPPA_BGE_UN:
case OP_HPPA_BLE:
case OP_HPPA_BLE_UN:
EMIT_COND_BRANCH (ins, ins->sreg1, ins->sreg2, ins->opcode - OP_HPPA_BEQ);
break;
case OP_HPPA_COND_EXC_EQ:
case OP_HPPA_COND_EXC_GE:
case OP_HPPA_COND_EXC_GT:
case OP_HPPA_COND_EXC_LE:
case OP_HPPA_COND_EXC_LT:
case OP_HPPA_COND_EXC_NE_UN:
case OP_HPPA_COND_EXC_GE_UN:
case OP_HPPA_COND_EXC_GT_UN:
case OP_HPPA_COND_EXC_LE_UN:
case OP_HPPA_COND_EXC_LT_UN:
EMIT_COND_SYSTEM_EXCEPTION (ins->sreg1, ins->sreg2, ins->opcode - OP_HPPA_COND_EXC_EQ, ins->inst_p1);
break;
case OP_HPPA_COND_EXC_OV:
case OP_HPPA_COND_EXC_NO:
case OP_HPPA_COND_EXC_C:
case OP_HPPA_COND_EXC_NC:
NOT_IMPLEMENTED;
/* floating point opcodes */
case OP_R8CONST:
hppa_set (code, (unsigned int)ins->inst_p0, hppa_r1);
hppa_flddx (code, hppa_r0, hppa_r1, ins->dreg);
break;
case OP_R4CONST:
hppa_set (code, (unsigned int)ins->inst_p0, hppa_r1);
hppa_fldwx (code, hppa_r0, hppa_r1, hppa_fr31, 0);
hppa_fcnvff (code, HPPA_FP_FMT_SGL, HPPA_FP_FMT_DBL, hppa_fr31, ins->dreg);
break;
case OP_STORER8_MEMBASE_REG:
hppa_set (code, ins->inst_offset, hppa_r1);
hppa_fstdx (code, ins->sreg1, hppa_r1, ins->inst_destbasereg);
break;
case OP_LOADR8_MEMBASE:
hppa_set (code, ins->inst_offset, hppa_r1);
hppa_flddx (code, hppa_r1, ins->inst_basereg, ins->dreg);
break;
case OP_STORER4_MEMBASE_REG:
hppa_fcnvff (code, HPPA_FP_FMT_DBL, HPPA_FP_FMT_SGL, ins->sreg1, hppa_fr31);
if (hppa_check_bits (ins->inst_offset, 5)) {
hppa_fstws (code, hppa_fr31, 0, ins->inst_offset, ins->inst_destbasereg);
} else {
hppa_set (code, ins->inst_offset, hppa_r1);
hppa_fstwx (code, hppa_fr31, 0, hppa_r1, ins->inst_destbasereg);
}
break;
case OP_HPPA_STORER4_LEFT:
case OP_HPPA_STORER4_RIGHT:
if (hppa_check_bits (ins->inst_offset, 5)) {
hppa_fstws (code, ins->sreg1, (ins->opcode == OP_HPPA_STORER4_RIGHT), ins->inst_offset, ins->inst_destbasereg);
} else {
hppa_set (code, ins->inst_offset, hppa_r1);
hppa_fstwx (code, ins->sreg1, (ins->opcode == OP_HPPA_STORER4_RIGHT), hppa_r1, ins->inst_destbasereg);
}
break;
case OP_LOADR4_MEMBASE:
if (hppa_check_bits (ins->inst_offset, 5)) {
hppa_fldws (code, ins->inst_offset, ins->inst_basereg, hppa_fr31, 0);
} else {
hppa_set (code, ins->inst_offset, hppa_r1);
hppa_fldwx (code, hppa_r1, ins->inst_basereg, hppa_fr31, 0);
}
hppa_fcnvff (code, HPPA_FP_FMT_SGL, HPPA_FP_FMT_DBL, hppa_fr31, ins->dreg);
break;
case OP_HPPA_LOADR4_LEFT:
case OP_HPPA_LOADR4_RIGHT:
if (hppa_check_bits (ins->inst_offset, 5)) {
hppa_fldws (code, ins->inst_offset, ins->inst_basereg, ins->dreg, (ins->opcode == OP_HPPA_LOADR4_RIGHT));
} else {
hppa_set (code, ins->inst_offset, hppa_r1);
hppa_fldwx (code, hppa_r1, ins->inst_basereg, ins->dreg, (ins->opcode == OP_HPPA_LOADR4_RIGHT));
}
break;
case CEE_CONV_R4:
hppa_stw (code, ins->sreg1, -16, hppa_sp);
hppa_fldws (code, -16, hppa_sp, hppa_fr31, 0);
hppa_fcnvxf (code, HPPA_FP_FMT_SGL, HPPA_FP_FMT_SGL, hppa_fr31, ins->dreg);
hppa_fcnvff (code, HPPA_FP_FMT_SGL, HPPA_FP_FMT_DBL, ins->dreg, ins->dreg);
break;
case OP_FCONV_TO_R4:
/* reduce precision */
hppa_fcnvff (code, HPPA_FP_FMT_DBL, HPPA_FP_FMT_SGL, ins->sreg1, ins->dreg);
hppa_fcnvff (code, HPPA_FP_FMT_SGL, HPPA_FP_FMT_DBL, ins->dreg, ins->dreg);
break;
case OP_HPPA_SETF4REG:
hppa_fcnvff (code, HPPA_FP_FMT_DBL, HPPA_FP_FMT_SGL, ins->sreg1, ins->dreg);
break;
case CEE_CONV_R8:
hppa_stw (code, ins->sreg1, -16, hppa_sp);
hppa_fldws (code, -16, hppa_sp, hppa_fr31, 0);
hppa_fcnvxf (code, HPPA_FP_FMT_SGL, HPPA_FP_FMT_DBL, hppa_fr31, ins->dreg);
break;
case OP_FCONV_TO_I1:
code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, TRUE);
break;
case OP_FCONV_TO_U1:
code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, FALSE);
break;
case OP_FCONV_TO_I2:
code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, TRUE);
break;
case OP_FCONV_TO_U2:
code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, FALSE);
break;
case OP_FCONV_TO_I4:
case OP_FCONV_TO_I:
code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, TRUE);
break;
case OP_FCONV_TO_U4:
case OP_FCONV_TO_U:
code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, FALSE);
break;
case OP_FCONV_TO_I8:
case OP_FCONV_TO_U8:
g_assert_not_reached ();
/* Implemented as helper calls */
break;
case OP_LCONV_TO_R_UN:
g_assert_not_reached ();
/* Implemented as helper calls */
break;
case OP_LCONV_TO_OVF_I:
NOT_IMPLEMENTED;
break;
case OP_FADD:
hppa_fadd (code, HPPA_FP_FMT_DBL, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_FSUB:
hppa_fsub (code, HPPA_FP_FMT_DBL, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_FMUL:
hppa_fmul (code, HPPA_FP_FMT_DBL, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_FDIV:
hppa_fdiv (code, HPPA_FP_FMT_DBL, ins->sreg1, ins->sreg2, ins->dreg);
break;
case OP_FREM:
NOT_IMPLEMENTED;
break;
case OP_FCOMPARE:
g_assert_not_reached();
break;
case OP_FCEQ:
case OP_FCLT:
case OP_FCLT_UN:
case OP_FCGT:
case OP_FCGT_UN:
hppa_fcmp (code, HPPA_FP_FMT_DBL, float_ceq_table [ins->opcode - OP_FCEQ], ins->sreg1, ins->sreg2);
hppa_ftest (code, 0);
hppa_bl (code, 12, hppa_r0);
hppa_ldo (code, 1, hppa_r0, ins->dreg);
hppa_ldo (code, 0, hppa_r0, ins->dreg);
break;
case OP_FBEQ:
case OP_FBLT:
case OP_FBGT:
case OP_FBGE:
case OP_FBLE:
case OP_FBNE_UN:
case OP_FBLT_UN:
case OP_FBGT_UN:
case OP_FBGE_UN:
case OP_FBLE_UN:
EMIT_FLOAT_COND_BRANCH (ins, ins->sreg1, ins->sreg2, ins->opcode - OP_FBEQ);
break;
case OP_CKFINITE:
case OP_MEMORY_BARRIER:
break;
case OP_HPPA_XMPYU:
hppa_xmpyu (code, ins->sreg1, ins->sreg2, ins->dreg);
break;
default:
g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
g_assert_not_reached ();
}
if ((((guint8*)code) - code_start) > max_len) {
g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %d)",
mono_inst_name (ins->opcode), max_len, ((guint8*)code) - code_start);
g_assert_not_reached ();
}
cpos += max_len;
last_ins = ins;
}
cfg->code_len = (guint8*)code - cfg->native_code;
DEBUG_FUNC_EXIT();
}
void
mono_arch_register_lowlevel_calls (void)
{
}
void
mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, MonoCodeManager *dyn_code_mp, gboolean run_cctors)
{
MonoJumpInfo *patch_info;
DEBUG_FUNC_ENTER();
/* FIXME: Move part of this to arch independent code */
for (patch_info = ji; patch_info; patch_info = patch_info->next) {
unsigned char *ip = patch_info->ip.i + code;
gpointer target;
target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors);
DEBUG (printf ("patch_info->type = %d, target = %p\n", patch_info->type, target));
switch (patch_info->type) {
case MONO_PATCH_INFO_NONE:
case MONO_PATCH_INFO_BB_OVF:
case MONO_PATCH_INFO_EXC_OVF:
continue;
case MONO_PATCH_INFO_IP:
hppa_patch ((guint32 *)ip, ip);
continue;
case MONO_PATCH_INFO_CLASS_INIT: {
break;
}
case MONO_PATCH_INFO_METHOD_JUMP: {
break;
}
case MONO_PATCH_INFO_SWITCH: {
int i;
gpointer *table = (gpointer *)target;
ip += 8;
for (i = 0; i < patch_info->data.table->table_size; i++) {
DEBUG (printf ("Patching switch table, table[%d] = %p\n", i, table[i]));
hppa_ldil (ip, hppa_lsel (table [i]), hppa_r1);
hppa_be_n (ip, hppa_rsel (table [i]), hppa_r1);
}
continue;
}
default:
break;
}
hppa_patch ((guint32 *)ip, target);
}
DEBUG_FUNC_EXIT();
}
void*
mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
{
guint32 *code = (guint32*)p;
DEBUG_FUNC_ENTER();
hppa_set (code, cfg->method, hppa_r26);
hppa_copy (code, hppa_r0, hppa_r25); /* NULL sp for now */
hppa_set (code, func, hppa_r1);
hppa_depi (code, 0, 31, 2, hppa_r1);
hppa_ldw (code, 0, hppa_r1, hppa_r1);
hppa_ble (code, 0, hppa_r1);
hppa_copy (code, hppa_r31, hppa_r2);
DEBUG_FUNC_EXIT();
return code;
}
enum {
SAVE_NONE,
SAVE_STRUCT,
SAVE_ONE,
SAVE_TWO,
SAVE_FP
};
void*
mono_arch_instrument_epilog_full (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments, gboolean preserve_argument_registers)
{
guint32 *code = (guint32*)p;
DEBUG_FUNC_ENTER();
#if 0
int save_mode = SAVE_NONE;
MonoMethod *method = cfg->method;
switch (mono_type_get_underlying_type (mono_method_signature (method)->ret)->type) {
case MONO_TYPE_VOID:
/* special case string .ctor icall */
if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
save_mode = SAVE_ONE;
else
save_mode = SAVE_NONE;
break;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
#ifdef SPARCV9
save_mode = SAVE_ONE;
#else
save_mode = SAVE_TWO;
#endif
break;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
save_mode = SAVE_FP;
break;
case MONO_TYPE_VALUETYPE:
save_mode = SAVE_STRUCT;
break;
default:
save_mode = SAVE_ONE;
break;
}
/* Save the result to the stack and also put it into the output registers */
switch (save_mode) {
case SAVE_TWO:
/* V8 only */
sparc_st_imm (code, sparc_i0, sparc_fp, 68);
sparc_st_imm (code, sparc_i0, sparc_fp, 72);
sparc_mov_reg_reg (code, sparc_i0, sparc_o1);
sparc_mov_reg_reg (code, sparc_i1, sparc_o2);
break;
case SAVE_ONE:
sparc_sti_imm (code, sparc_i0, sparc_fp, ARGS_OFFSET);
sparc_mov_reg_reg (code, sparc_i0, sparc_o1);
break;
case SAVE_FP:
#ifdef SPARCV9
sparc_stdf_imm (code, sparc_f0, sparc_fp, ARGS_OFFSET);
#else
sparc_stdf_imm (code, sparc_f0, sparc_fp, 72);
sparc_ld_imm (code, sparc_fp, 72, sparc_o1);
sparc_ld_imm (code, sparc_fp, 72 + 4, sparc_o2);
#endif
break;
case SAVE_STRUCT:
#ifdef SPARCV9
sparc_mov_reg_reg (code, sparc_i0, sparc_o1);
#else
sparc_ld_imm (code, sparc_fp, 64, sparc_o1);
#endif
break;
case SAVE_NONE:
default:
break;
}
sparc_set (code, cfg->method, sparc_o0);
mono_add_patch_info (cfg, (guint8*)code - cfg->native_code, MONO_PATCH_INFO_ABS, func);
EMIT_CALL ();
/* Restore result */
switch (save_mode) {
case SAVE_TWO:
sparc_ld_imm (code, sparc_fp, 68, sparc_i0);
sparc_ld_imm (code, sparc_fp, 72, sparc_i0);
break;
case SAVE_ONE:
sparc_ldi_imm (code, sparc_fp, ARGS_OFFSET, sparc_i0);
break;
case SAVE_FP:
sparc_lddf_imm (code, sparc_fp, ARGS_OFFSET, sparc_f0);
break;
case SAVE_NONE:
default:
break;
}
#endif
DEBUG_FUNC_EXIT();
return code;
}
/*
* The HPPA stack frame should look like this:
*
* ---------------------
* incoming params area
* ---------------------
* linkage area size = ARGS_OFFSET
* --------------------- fp = psp
* HPPA_STACK_LMF_OFFSET
* ---------------------
* MonoLMF structure or saved registers
* -------------------
* locals size = cfg->stack_offset - cfg->param_area
* ---------------------
* params area size = cfg->param_area - ARGS_OFFSET (aligned)
* ---------------------
* callee linkage area size = ARGS_OFFSET
* --------------------- sp
*/
guint8 *
mono_arch_emit_prolog (MonoCompile *cfg)
{
MonoMethod *method = cfg->method;
MonoBasicBlock *bb;
MonoMethodSignature *sig;
MonoInst *inst;
int alloc_size, pos, max_offset, i;
guint8 *code;
CallInfo *cinfo;
int tracing = 0;
int lmf_offset = 0;
DEBUG_FUNC_ENTER();
if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
tracing = 1;
sig = mono_method_signature (method);
cfg->code_size = 512 + sig->param_count * 20;
code = cfg->native_code = g_malloc (cfg->code_size);
/* TODO: enable tail call optimization */
if (1 || cfg->flags & MONO_CFG_HAS_CALLS) {
hppa_stw (code, hppa_r2, -20, hppa_sp);
}
/* locals area */
pos = HPPA_STACK_LMF_OFFSET;
/* figure out how much space we need for spilling */
if (!method->save_lmf) {
/* spill callee-save registers */
guint32 mask = cfg->used_int_regs & MONO_ARCH_CALLEE_SAVED_REGS;
for (i = 0; i < 32; i++) {
if ((1 << i) & mask)
pos += sizeof (gulong);
}
} else {
lmf_offset = pos;
pos += sizeof (MonoLMF);
}
alloc_size = ALIGN_TO (pos + cfg->stack_offset, MONO_ARCH_FRAME_ALIGNMENT);
g_assert ((alloc_size & (MONO_ARCH_FRAME_ALIGNMENT - 1)) == 0);
cfg->stack_usage = alloc_size;
if (alloc_size) {
hppa_copy (code, hppa_r3, hppa_r1);
hppa_copy (code, hppa_sp, hppa_r3);
if (hppa_check_bits (alloc_size, 14))
hppa_stwm (code, hppa_r1, alloc_size, hppa_sp);
else {
hppa_stwm (code, hppa_r1, 8100, hppa_sp);
hppa_addil (code, hppa_lsel (alloc_size - 8100), hppa_sp);
hppa_ldo (code, hppa_rsel (alloc_size - 8100), hppa_r1, hppa_sp);
}
}
/* compute max_offset in order to use short forward jumps
* we always do it on hppa because the immediate displacement
* for jumps is small
*/
max_offset = 0;
for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
MonoInst *ins = bb->code;
bb->max_offset = max_offset;
if (cfg->prof_options & MONO_PROFILE_COVERAGE)
max_offset += 6;
MONO_BB_FOR_EACH_INS (bb, ins)
max_offset += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
}
DEBUG (printf ("Incoming arguments: \n"));
cinfo = get_call_info (sig, sig->pinvoke);
/* We do this first so that we don't have to worry about the LMF-
* saving code clobbering r28
*/
if (cinfo->struct_return)
hppa_stw (code, hppa_r28, cfg->ret->inst_offset, hppa_sp);
/* Save the LMF or the spilled registers */
pos = HPPA_STACK_LMF_OFFSET;
if (!method->save_lmf) {
/* spill callee-save registers */
guint32 mask = cfg->used_int_regs & MONO_ARCH_CALLEE_SAVED_REGS;
for (i = 0; i < 32; i++) {
if ((1 << i) & mask) {
if (i == hppa_r3) {
hppa_ldw (code, 0, hppa_r3, hppa_r1);
hppa_stw (code, hppa_r1, pos, hppa_r3);
} else
hppa_stw (code, i, pos, hppa_r3);
pos += sizeof (gulong);
}
}
} else {
int ofs = lmf_offset + G_STRUCT_OFFSET (MonoLMF, regs);
int reg;
hppa_ldw (code, 0, hppa_r3, hppa_r1);
hppa_stw (code, hppa_r1, ofs, hppa_r3);
ofs += sizeof (gulong);
for (reg = 4; reg < 32; reg++) {
if (HPPA_IS_SAVED_GREG (reg)) {
hppa_stw (code, reg, ofs, hppa_r3);
ofs += sizeof (gulong);
}
}
/* We shouldn't need to save the FP regs.... */
ofs = ALIGN_TO (ofs, sizeof(double));
hppa_set (code, ofs, hppa_r1);
for (reg = 0; reg < 32; reg++) {
if (HPPA_IS_SAVED_FREG (reg)) {
hppa_fstdx (code, reg, hppa_r1, hppa_r3);
hppa_ldo (code, sizeof(double), hppa_r1, hppa_r1);
}
}
/* We also spill the arguments onto the stack, because
* the call to hppa_get_lmf_addr below can clobber them
*
* This goes in the param area that is always allocated
*/
ofs = -36;
for (reg = hppa_r26; reg >= hppa_r23; reg--) {
hppa_stw (code, reg, ofs, hppa_sp);
ofs -= 4;
}
}
if (cfg->flags & MONO_CFG_HAS_ALLOCA)
hppa_copy (code, hppa_r30, hppa_r4);
if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
hppa_set (code, cfg->domain, hppa_r26);
mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD, (gpointer)"mono_jit_thread_attach");
hppa_ldil (code, 0, hppa_r1);
hppa_ldo (code, 0, hppa_r1, hppa_r1);
hppa_depi (code, 0, 31, 2, hppa_r1);
hppa_ldw (code, 0, hppa_r1, hppa_r1);
hppa_ble (code, 0, hppa_r1);
hppa_copy (code, hppa_r31, hppa_r2);
}
if (method->save_lmf) {
mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD,
(gpointer)"mono_get_lmf_addr");
hppa_ldil (code, 0, hppa_r1);
hppa_ldo (code, 0, hppa_r1, hppa_r1);
hppa_depi (code, 0, 31, 2, hppa_r1);
hppa_ldw (code, 0, hppa_r1, hppa_r1);
hppa_ble (code, 0, hppa_r1);
hppa_copy (code, hppa_r31, hppa_r2);
/* lmf_offset is the offset from the previous stack pointer,
* The pointer to the struct is put in hppa_r22 (new_lmf).
* The callee-saved registers are already in the MonoLMF
* structure
*/
/* hppa_r22 = new_lmf (on the stack) */
hppa_ldo (code, lmf_offset, hppa_r3, hppa_r22);
/* lmf_offset is the offset from the previous stack pointer,
*/
hppa_stw (code, hppa_r28, G_STRUCT_OFFSET(MonoLMF, lmf_addr), hppa_r22);
/* new_lmf->previous_lmf = *lmf_addr */
hppa_ldw (code, 0, hppa_r28, hppa_r1);
hppa_stw (code, hppa_r1, G_STRUCT_OFFSET(MonoLMF, previous_lmf), hppa_r22);
/* *(lmf_addr) = r22 */
hppa_stw (code, hppa_r22, 0, hppa_r28);
hppa_set (code, method, hppa_r1);
hppa_stw (code, hppa_r1, G_STRUCT_OFFSET(MonoLMF, method), hppa_r22);
hppa_stw (code, hppa_sp, G_STRUCT_OFFSET(MonoLMF, ebp), hppa_r22);
mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_IP, NULL);
hppa_ldil (code, 0, hppa_r1);
hppa_ldo (code, 0, hppa_r1, hppa_r1);
hppa_stw (code, hppa_r1, G_STRUCT_OFFSET(MonoLMF, eip), hppa_r22);
/* Now reload the arguments from the stack */
hppa_ldw (code, -36, hppa_sp, hppa_r26);
hppa_ldw (code, -40, hppa_sp, hppa_r25);
hppa_ldw (code, -44, hppa_sp, hppa_r24);
hppa_ldw (code, -48, hppa_sp, hppa_r23);
}
/* load arguments allocated to register from the stack */
pos = 0;
for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
ArgInfo *ainfo = cinfo->args + i;
inst = cfg->args [pos];
if (inst->opcode == OP_REGVAR) {
/* Want the argument in a register */
switch (ainfo->storage) {
case ArgInIReg:
if (ainfo->reg != inst->dreg)
hppa_copy (code, ainfo->reg, inst->dreg);
DEBUG (printf ("Argument %d assigned to register %s\n", pos, mono_arch_regname (inst->dreg)));
break;
case ArgInIRegPair:
if (ainfo->reg != inst->dreg) {
hppa_copy (code, ainfo->reg, inst->dreg);
hppa_copy (code, ainfo->reg + 1, inst->dreg + 1);
}
DEBUG (printf ("Argument %d assigned to register %s, %s\n", pos, mono_arch_regname (inst->dreg), mono_arch_regname (inst->dreg + 1)));
break;
case ArgInFReg:
if (ainfo->reg != inst->dreg)
hppa_fcpy (code, HPPA_FP_FMT_SGL, ainfo->reg, inst->dreg);
DEBUG (printf ("Argument %d assigned to single register %s\n", pos, mono_arch_fregname (inst->dreg)));
break;
case ArgInDReg:
if (ainfo->reg != inst->dreg)
hppa_fcpy (code, HPPA_FP_FMT_DBL, ainfo->reg, inst->dreg);
DEBUG (printf ("Argument %d assigned to double register %s\n", pos, mono_arch_fregname (inst->dreg)));
break;
case ArgOnStack:
switch (ainfo->size) {
case 1:
hppa_ldb (code, ainfo->offset, hppa_r3, inst->dreg);
break;
case 2:
hppa_ldh (code, ainfo->offset, hppa_r3, inst->dreg);
break;
case 4:
hppa_ldw (code, ainfo->offset, hppa_r3, inst->dreg);
break;
default:
g_assert_not_reached ();
}
DEBUG (printf ("Argument %d loaded from the stack [%s - %d]\n", pos, mono_arch_regname (hppa_r3), -ainfo->offset));
break;
default:
g_assert_not_reached ();
}
}
else {
/* Want the argument on the stack */
switch (ainfo->storage)
{
case ArgInIReg: {
int off, reg;
DEBUG (printf ("Argument %d stored from register %s to stack [%s + %d]\n", pos, mono_arch_regname (ainfo->reg), mono_arch_regname (inst->inst_basereg), inst->inst_offset));
if (hppa_check_bits (inst->inst_offset, 14)) {
off = inst->inst_offset;
reg = inst->inst_basereg;
}
else {
hppa_set (code, inst->inst_offset, hppa_r1);
hppa_add (code, hppa_r1, inst->inst_basereg, hppa_r1);
off = 0;
reg = hppa_r1;
}
switch (ainfo->size)
{
case 1:
hppa_stb (code, ainfo->reg, off, reg);
break;
case 2:
hppa_sth (code, ainfo->reg, off, reg);
break;
case 4:
hppa_stw (code, ainfo->reg, off, reg);
break;
default:
g_assert_not_reached ();
}
break;
}
case ArgInIRegPair:
DEBUG (printf ("Argument %d stored from register (%s,%s) to stack [%s + %d]\n", pos, mono_arch_regname (ainfo->reg), mono_arch_regname (ainfo->reg+1), mono_arch_regname (inst->inst_basereg), inst->inst_offset));
if (hppa_check_bits (inst->inst_offset + 4, 14)) {
hppa_stw (code, ainfo->reg, inst->inst_offset, inst->inst_basereg);
hppa_stw (code, ainfo->reg + 1, inst->inst_offset + 4, inst->inst_basereg);
}
else {
hppa_ldo (code, inst->inst_offset, inst->inst_basereg, hppa_r1);
hppa_stw (code, ainfo->reg, 0, hppa_r1);
hppa_stw (code, ainfo->reg + 1, 4, hppa_r1);
}
break;
case ArgInFReg:
DEBUG (printf ("Argument %d (float) stored from register %s to stack [%s + %d]\n", pos, mono_arch_fregname (ainfo->reg), mono_arch_regname (inst->inst_basereg), inst->inst_offset));
hppa_ldo (code, inst->inst_offset, inst->inst_basereg, hppa_r1);
hppa_fstwx (code, ainfo->reg, 0, hppa_r0, hppa_r1);
break;
case ArgInDReg:
DEBUG (printf ("Argument %d (double) stored from register %s to stack [%s + %d]\n", pos, mono_arch_fregname (ainfo->reg), mono_arch_regname (inst->inst_basereg), inst->inst_offset));
hppa_ldo (code, inst->inst_offset, inst->inst_basereg, hppa_r1);
hppa_fstdx (code, ainfo->reg, hppa_r0, hppa_r1);
break;
case ArgOnStack:
DEBUG (printf ("Argument %d copied from [%s - %d] to [%s + %d] (size=%d)\n", pos, mono_arch_regname (hppa_r3), -ainfo->offset, mono_arch_regname (inst->inst_basereg), inst->inst_offset, ainfo->size));
if (inst->inst_offset != ainfo->offset ||
inst->inst_basereg != hppa_r3)
code = emit_memcpy (code, inst->inst_offset, inst->inst_basereg, ainfo->offset, hppa_r3, ainfo->size);
break;
default:
g_assert_not_reached ();
}
}
pos++;
}
if (tracing)
code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
if (getenv("HPPA_BREAK")) {
*(guint32*)code = 0x00010004;
code += 4;
}
cfg->code_len = code - cfg->native_code;
g_assert (cfg->code_len < cfg->code_size);
g_free (cinfo);
DEBUG_FUNC_EXIT();
return code;
}
void
mono_arch_emit_epilog (MonoCompile *cfg)
{
MonoMethod *method = cfg->method;
MonoMethodSignature *sig;
guint32 *code;
int max_epilog_size = 16 + 20 * 4;
int pos;
DEBUG_FUNC_ENTER();
sig = mono_method_signature (cfg->method);
if (cfg->method->save_lmf)
max_epilog_size += 128;
if (mono_jit_trace_calls != NULL)
max_epilog_size += 50;
if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
max_epilog_size += 50;
while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) {
cfg->code_size *= 2;
cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
mono_jit_stats.code_reallocs++;
}
code = (guint32*)(cfg->native_code + cfg->code_len);
if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
pos = HPPA_STACK_LMF_OFFSET;
if (cfg->method->save_lmf) {
int reg;
hppa_ldo (code, pos, hppa_r3, hppa_r22);
hppa_ldw (code, G_STRUCT_OFFSET(MonoLMF, previous_lmf), hppa_r22, hppa_r21);
hppa_ldw (code, G_STRUCT_OFFSET(MonoLMF, lmf_addr), hppa_r22, hppa_r20);
hppa_stw (code, hppa_r21, G_STRUCT_OFFSET(MonoLMF, previous_lmf), hppa_r20);
pos += G_STRUCT_OFFSET(MonoLMF, regs) + sizeof (gulong);
/* We skip the restore of r3 here, it is restored from the
* stack anyway. This makes the code a bit easier.
*/
for (reg = 4; reg < 31; reg++) {
if (HPPA_IS_SAVED_GREG (reg)) {
hppa_ldw (code, pos, hppa_r3, reg);
pos += sizeof(gulong);
}
}
pos = ALIGN_TO (pos, sizeof (double));
hppa_set (code, pos, hppa_r1);
for (reg = 0; reg < 31; reg++) {
if (HPPA_IS_SAVED_FREG (reg)) {
hppa_flddx (code, hppa_r1, hppa_r3, reg);
hppa_ldo (code, sizeof (double), hppa_r1, hppa_r1);
pos += sizeof (double);
}
}
} else {
guint32 mask = cfg->used_int_regs & MONO_ARCH_CALLEE_SAVED_REGS;
int i;
for (i = 0; i < 32; i++) {
if (i == hppa_r3)
continue;
if ((1 << i) & mask) {
hppa_ldw (code, pos, hppa_r3, i);
pos += sizeof (gulong);
}
}
}
if (sig->ret->type != MONO_TYPE_VOID &&
mono_type_to_stind (sig->ret) == CEE_STOBJ) {
CallInfo *cinfo = get_call_info (sig, sig->pinvoke);
switch (cinfo->ret.storage) {
case ArgInIReg:
hppa_ldw (code, cfg->ret->inst_offset, hppa_sp, hppa_r28);
hppa_ldw (code, 0, hppa_r28, hppa_r28);
break;
case ArgInIRegPair:
hppa_ldw (code, cfg->ret->inst_offset, hppa_sp, hppa_r28);
hppa_ldw (code, 4, hppa_r28, hppa_r29);
hppa_ldw (code, 0, hppa_r28, hppa_r28);
break;
case ArgOnStack:
/* Nothing to do */
break;
default:
g_assert_not_reached ();
}
g_free (cinfo);
}
if (1 || cfg->flags & MONO_CFG_HAS_CALLS)
hppa_ldw (code, -20, hppa_r3, hppa_r2);
hppa_ldo (code, 64, hppa_r3, hppa_sp);
hppa_bv (code, hppa_r0, hppa_r2);
hppa_ldwm (code, -64, hppa_sp, hppa_r3);
cfg->code_len = (guint8*)code - cfg->native_code;
g_assert (cfg->code_len < cfg->code_size);
DEBUG_FUNC_EXIT();
}
/* remove once throw_exception_by_name is eliminated */
static int
exception_id_by_name (const char *name)
{
if (strcmp (name, "IndexOutOfRangeException") == 0)
return MONO_EXC_INDEX_OUT_OF_RANGE;
if (strcmp (name, "OverflowException") == 0)
return MONO_EXC_OVERFLOW;
if (strcmp (name, "ArithmeticException") == 0)
return MONO_EXC_ARITHMETIC;
if (strcmp (name, "DivideByZeroException") == 0)
return MONO_EXC_DIVIDE_BY_ZERO;
if (strcmp (name, "InvalidCastException") == 0)
return MONO_EXC_INVALID_CAST;
if (strcmp (name, "NullReferenceException") == 0)
return MONO_EXC_NULL_REF;
if (strcmp (name, "ArrayTypeMismatchException") == 0)
return MONO_EXC_ARRAY_TYPE_MISMATCH;
g_error ("Unknown intrinsic exception %s\n", name);
return 0;
}
void
mono_arch_emit_exceptions (MonoCompile *cfg)
{
MonoJumpInfo *patch_info;
int i;
guint8 *code;
const guint8* exc_throw_pos [MONO_EXC_INTRINS_NUM] = {NULL};
guint8 exc_throw_found [MONO_EXC_INTRINS_NUM] = {0};
int max_epilog_size = 50;
DEBUG_FUNC_ENTER();
/* count the number of exception infos */
/*
* make sure we have enough space for exceptions
*/
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_BB_OVF:
g_assert_not_reached ();
break;
case MONO_PATCH_INFO_EXC_OVF: {
const MonoOvfJump *ovfj = patch_info->data.target;
max_epilog_size += 8;
i = exception_id_by_name (ovfj->data.exception);
if (!exc_throw_found [i]) {
max_epilog_size += 24;
exc_throw_found [i] = TRUE;
}
break;
}
case MONO_PATCH_INFO_EXC:
i = exception_id_by_name (patch_info->data.target);
if (!exc_throw_found [i]) {
max_epilog_size += 24;
exc_throw_found [i] = TRUE;
}
break;
default:
break;
}
}
while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) {
cfg->code_size *= 2;
cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
mono_jit_stats.code_reallocs++;
}
code = cfg->native_code + cfg->code_len;
/* add code to raise exceptions */
for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
switch (patch_info->type) {
case MONO_PATCH_INFO_BB_OVF: {
/* TODO */
break;
}
case MONO_PATCH_INFO_EXC_OVF: {
const MonoOvfJump *ovfj = patch_info->data.target;
MonoJumpInfo *newji;
unsigned char *ip = patch_info->ip.i + cfg->native_code;
unsigned char *stub = code;
/* Patch original call, point it at the stub */
hppa_patch ((guint32 *)ip, code);
/* Write the stub */
/* SUBTLE: this has to be PIC, because the code block
* can be relocated
*/
hppa_bl_n (code, 8, hppa_r0);
hppa_nop (code);
/* Add a patch info to patch the stub to point to the exception code */
newji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
newji->type = MONO_PATCH_INFO_EXC;
newji->ip.i = stub - cfg->native_code;
newji->data.target = ovfj->data.exception;
newji->next = patch_info->next;
patch_info->next = newji;
break;
}
case MONO_PATCH_INFO_EXC: {
unsigned char *ip = patch_info->ip.i + cfg->native_code;
i = exception_id_by_name (patch_info->data.target);
if (exc_throw_pos [i]) {
hppa_patch ((guint32 *)ip, exc_throw_pos [i]);
patch_info->type = MONO_PATCH_INFO_NONE;
break;
} else {
exc_throw_pos [i] = code;
}
hppa_patch ((guint32 *)ip, code);
hppa_set (code, patch_info->data.target, hppa_r26);
patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
patch_info->data.name = "mono_arch_throw_exception_by_name";
patch_info->ip.i = code - cfg->native_code;
/* Assume the caller has set r2, we can't set it
* here based on ip, because the caller may
* be relocated (also the "ip" may be from an overflow
* stub)
*/
hppa_ldil (code, 0, hppa_r1);
hppa_ldo (code, 0, hppa_r1, hppa_r1);
hppa_bv (code, hppa_r0, hppa_r1);
hppa_nop (code);
break;
}
default:
/* do nothing */
break;
}
}
cfg->code_len = code - cfg->native_code;
g_assert (cfg->code_len < cfg->code_size);
DEBUG_FUNC_EXIT();
}
#ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
#error "--with-sigaltstack=yes not supported on hppa"
#endif
void
mono_arch_setup_jit_tls_data (MonoJitTlsData *tls)
{
}
void
mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
{
}
void
mono_arch_emit_this_vret_args (MonoCompile *cfg, MonoCallInst *inst, int this_reg, int this_type, int vt_reg)
{
/* add the this argument */
if (this_reg != -1) {
MonoInst *this;
MONO_INST_NEW (cfg, this, OP_MOVE);
this->type = this_type;
this->sreg1 = this_reg;
this->dreg = mono_alloc_ireg (cfg);
mono_bblock_add_inst (cfg->cbb, this);
mono_call_inst_add_outarg_reg (cfg, inst, this->dreg, hppa_r26, FALSE);
}
if (vt_reg != -1) {
MonoInst *vtarg;
MONO_INST_NEW (cfg, vtarg, OP_MOVE);
vtarg->type = STACK_MP;
vtarg->sreg1 = vt_reg;
vtarg->dreg = mono_alloc_ireg (cfg);
mono_bblock_add_inst (cfg->cbb, vtarg);
mono_call_inst_add_outarg_reg (cfg, inst, vtarg->dreg, hppa_r28, FALSE);
}
}
MonoInst*
mono_arch_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
{
MonoInst *ins = NULL;
DEBUG_FUNC_ENTER();
DEBUG_FUNC_EXIT();
return ins;
}
/*
* mono_arch_get_argument_info:
* @csig: a method signature
* @param_count: the number of parameters to consider
* @arg_info: an array to store the result infos
*
* Gathers information on parameters such as size, alignment and
* padding. arg_info should be large enought to hold param_count + 1 entries.
*
* Returns the size of the activation frame.
*/
int
mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info)
{
int k, align;
CallInfo *cinfo;
ArgInfo *ainfo;
DEBUG_FUNC_ENTER();
cinfo = get_call_info (csig, FALSE);
if (csig->hasthis) {
ainfo = &cinfo->args [0];
arg_info [0].offset = ainfo->offset;
}
for (k = 0; k < param_count; k++) {
ainfo = &cinfo->args [k + csig->hasthis];
arg_info [k + 1].offset = ainfo->offset;
arg_info [k + 1].size = mono_type_size (csig->params [k], &align);
}
g_free (cinfo);
DEBUG_FUNC_EXIT();
}
gboolean
mono_arch_print_tree (MonoInst *tree, int arity)
{
return 0;
}
MonoInst* mono_arch_get_domain_intrinsic (MonoCompile* cfg)
{
return NULL;
}
gpointer
mono_arch_context_get_int_reg (MonoContext *ctx, int reg)
{
/* FIXME: implement */
g_assert_not_reached ();
}
| 27.882153 | 215 | 0.671191 |
312503fb96f9bfaa08407b62127f611081ec4db7 | 20,502 | c | C | uboot/cmd/tpm.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 31 | 2018-01-16T17:11:44.000Z | 2022-03-16T13:51:24.000Z | uboot/cmd/tpm.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 1 | 2021-04-29T09:08:08.000Z | 2021-05-08T07:57:06.000Z | uboot/cmd/tpm.c | bingchunjin/1806_SDK | d5ed0258fc22f60e00ec025b802d175f33da6e41 | [
"MIT"
] | 30 | 2018-05-02T08:43:27.000Z | 2022-01-23T03:25:54.000Z | /*
* Copyright (c) 2013 The Chromium OS Authors.
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <command.h>
#include <dm.h>
#include <malloc.h>
#include <tpm.h>
#include <asm/unaligned.h>
#include <linux/string.h>
/* Useful constants */
enum {
DIGEST_LENGTH = 20,
/* max lengths, valid for RSA keys <= 2048 bits */
TPM_PUBKEY_MAX_LENGTH = 288,
};
/**
* Print a byte string in hexdecimal format, 16-bytes per line.
*
* @param data byte string to be printed
* @param count number of bytes to be printed
*/
static void print_byte_string(uint8_t *data, size_t count)
{
int i, print_newline = 0;
for (i = 0; i < count; i++) {
printf(" %02x", data[i]);
print_newline = (i % 16 == 15);
if (print_newline)
putc('\n');
}
/* Avoid duplicated newline at the end */
if (!print_newline)
putc('\n');
}
/**
* Convert a text string of hexdecimal values into a byte string.
*
* @param bytes text string of hexdecimal values with no space
* between them
* @param data output buffer for byte string. The caller has to make
* sure it is large enough for storing the output. If
* NULL is passed, a large enough buffer will be allocated,
* and the caller must free it.
* @param count_ptr output variable for the length of byte string
* @return pointer to output buffer
*/
static void *parse_byte_string(char *bytes, uint8_t *data, size_t *count_ptr)
{
char byte[3];
size_t count, length;
int i;
if (!bytes)
return NULL;
length = strlen(bytes);
count = length / 2;
if (!data)
data = malloc(count);
if (!data)
return NULL;
byte[2] = '\0';
for (i = 0; i < length; i += 2) {
byte[0] = bytes[i];
byte[1] = bytes[i + 1];
data[i / 2] = (uint8_t)simple_strtoul(byte, NULL, 16);
}
if (count_ptr)
*count_ptr = count;
return data;
}
/**
* report_return_code() - Report any error and return failure or success
*
* @param return_code TPM command return code
* @return value of enum command_ret_t
*/
static int report_return_code(int return_code)
{
if (return_code) {
printf("Error: %d\n", return_code);
return CMD_RET_FAILURE;
} else {
return CMD_RET_SUCCESS;
}
}
/**
* Return number of values defined by a type string.
*
* @param type_str type string
* @return number of values of type string
*/
static int type_string_get_num_values(const char *type_str)
{
return strlen(type_str);
}
/**
* Return total size of values defined by a type string.
*
* @param type_str type string
* @return total size of values of type string, or 0 if type string
* contains illegal type character.
*/
static size_t type_string_get_space_size(const char *type_str)
{
size_t size;
for (size = 0; *type_str; type_str++) {
switch (*type_str) {
case 'b':
size += 1;
break;
case 'w':
size += 2;
break;
case 'd':
size += 4;
break;
default:
return 0;
}
}
return size;
}
/**
* Allocate a buffer large enough to hold values defined by a type
* string. The caller has to free the buffer.
*
* @param type_str type string
* @param count pointer for storing size of buffer
* @return pointer to buffer or NULL on error
*/
static void *type_string_alloc(const char *type_str, uint32_t *count)
{
void *data;
size_t size;
size = type_string_get_space_size(type_str);
if (!size)
return NULL;
data = malloc(size);
if (data)
*count = size;
return data;
}
/**
* Pack values defined by a type string into a buffer. The buffer must have
* large enough space.
*
* @param type_str type string
* @param values text strings of values to be packed
* @param data output buffer of values
* @return 0 on success, non-0 on error
*/
static int type_string_pack(const char *type_str, char * const values[],
uint8_t *data)
{
size_t offset;
uint32_t value;
for (offset = 0; *type_str; type_str++, values++) {
value = simple_strtoul(values[0], NULL, 0);
switch (*type_str) {
case 'b':
data[offset] = value;
offset += 1;
break;
case 'w':
put_unaligned_be16(value, data + offset);
offset += 2;
break;
case 'd':
put_unaligned_be32(value, data + offset);
offset += 4;
break;
default:
return -1;
}
}
return 0;
}
/**
* Read values defined by a type string from a buffer, and write these values
* to environment variables.
*
* @param type_str type string
* @param data input buffer of values
* @param vars names of environment variables
* @return 0 on success, non-0 on error
*/
static int type_string_write_vars(const char *type_str, uint8_t *data,
char * const vars[])
{
size_t offset;
uint32_t value;
for (offset = 0; *type_str; type_str++, vars++) {
switch (*type_str) {
case 'b':
value = data[offset];
offset += 1;
break;
case 'w':
value = get_unaligned_be16(data + offset);
offset += 2;
break;
case 'd':
value = get_unaligned_be32(data + offset);
offset += 4;
break;
default:
return -1;
}
if (setenv_ulong(*vars, value))
return -1;
}
return 0;
}
static int do_tpm_startup(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
enum tpm_startup_type mode;
if (argc != 2)
return CMD_RET_USAGE;
if (!strcasecmp("TPM_ST_CLEAR", argv[1])) {
mode = TPM_ST_CLEAR;
} else if (!strcasecmp("TPM_ST_STATE", argv[1])) {
mode = TPM_ST_STATE;
} else if (!strcasecmp("TPM_ST_DEACTIVATED", argv[1])) {
mode = TPM_ST_DEACTIVATED;
} else {
printf("Couldn't recognize mode string: %s\n", argv[1]);
return CMD_RET_FAILURE;
}
return report_return_code(tpm_startup(mode));
}
static int do_tpm_nv_define_space(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t index, perm, size;
if (argc != 4)
return CMD_RET_USAGE;
index = simple_strtoul(argv[1], NULL, 0);
perm = simple_strtoul(argv[2], NULL, 0);
size = simple_strtoul(argv[3], NULL, 0);
return report_return_code(tpm_nv_define_space(index, perm, size));
}
static int do_tpm_nv_read_value(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t index, count, rc;
void *data;
if (argc != 4)
return CMD_RET_USAGE;
index = simple_strtoul(argv[1], NULL, 0);
data = (void *)simple_strtoul(argv[2], NULL, 0);
count = simple_strtoul(argv[3], NULL, 0);
rc = tpm_nv_read_value(index, data, count);
if (!rc) {
puts("area content:\n");
print_byte_string(data, count);
}
return report_return_code(rc);
}
static int do_tpm_nv_write_value(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t index, rc;
size_t count;
void *data;
if (argc != 3)
return CMD_RET_USAGE;
index = simple_strtoul(argv[1], NULL, 0);
data = parse_byte_string(argv[2], NULL, &count);
if (!data) {
printf("Couldn't parse byte string %s\n", argv[2]);
return CMD_RET_FAILURE;
}
rc = tpm_nv_write_value(index, data, count);
free(data);
return report_return_code(rc);
}
static int do_tpm_extend(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t index, rc;
uint8_t in_digest[20], out_digest[20];
if (argc != 3)
return CMD_RET_USAGE;
index = simple_strtoul(argv[1], NULL, 0);
if (!parse_byte_string(argv[2], in_digest, NULL)) {
printf("Couldn't parse byte string %s\n", argv[2]);
return CMD_RET_FAILURE;
}
rc = tpm_extend(index, in_digest, out_digest);
if (!rc) {
puts("PCR value after execution of the command:\n");
print_byte_string(out_digest, sizeof(out_digest));
}
return report_return_code(rc);
}
static int do_tpm_pcr_read(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t index, count, rc;
void *data;
if (argc != 4)
return CMD_RET_USAGE;
index = simple_strtoul(argv[1], NULL, 0);
data = (void *)simple_strtoul(argv[2], NULL, 0);
count = simple_strtoul(argv[3], NULL, 0);
rc = tpm_pcr_read(index, data, count);
if (!rc) {
puts("Named PCR content:\n");
print_byte_string(data, count);
}
return report_return_code(rc);
}
static int do_tpm_tsc_physical_presence(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint16_t presence;
if (argc != 2)
return CMD_RET_USAGE;
presence = (uint16_t)simple_strtoul(argv[1], NULL, 0);
return report_return_code(tpm_tsc_physical_presence(presence));
}
static int do_tpm_read_pubek(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t count, rc;
void *data;
if (argc != 3)
return CMD_RET_USAGE;
data = (void *)simple_strtoul(argv[1], NULL, 0);
count = simple_strtoul(argv[2], NULL, 0);
rc = tpm_read_pubek(data, count);
if (!rc) {
puts("pubek value:\n");
print_byte_string(data, count);
}
return report_return_code(rc);
}
static int do_tpm_physical_set_deactivated(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint8_t state;
if (argc != 2)
return CMD_RET_USAGE;
state = (uint8_t)simple_strtoul(argv[1], NULL, 0);
return report_return_code(tpm_physical_set_deactivated(state));
}
static int do_tpm_get_capability(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t cap_area, sub_cap, rc;
void *cap;
size_t count;
if (argc != 5)
return CMD_RET_USAGE;
cap_area = simple_strtoul(argv[1], NULL, 0);
sub_cap = simple_strtoul(argv[2], NULL, 0);
cap = (void *)simple_strtoul(argv[3], NULL, 0);
count = simple_strtoul(argv[4], NULL, 0);
rc = tpm_get_capability(cap_area, sub_cap, cap, count);
if (!rc) {
puts("capability information:\n");
print_byte_string(cap, count);
}
return report_return_code(rc);
}
#define TPM_COMMAND_NO_ARG(cmd) \
static int do_##cmd(cmd_tbl_t *cmdtp, int flag, \
int argc, char * const argv[]) \
{ \
if (argc != 1) \
return CMD_RET_USAGE; \
return report_return_code(cmd()); \
}
TPM_COMMAND_NO_ARG(tpm_init)
TPM_COMMAND_NO_ARG(tpm_self_test_full)
TPM_COMMAND_NO_ARG(tpm_continue_self_test)
TPM_COMMAND_NO_ARG(tpm_force_clear)
TPM_COMMAND_NO_ARG(tpm_physical_enable)
TPM_COMMAND_NO_ARG(tpm_physical_disable)
static int get_tpm(struct udevice **devp)
{
int rc;
rc = uclass_first_device_err(UCLASS_TPM, devp);
if (rc) {
printf("Could not find TPM (ret=%d)\n", rc);
return CMD_RET_FAILURE;
}
return 0;
}
static int do_tpm_info(cmd_tbl_t *cmdtp, int flag, int argc,
char *const argv[])
{
struct udevice *dev;
char buf[80];
int rc;
rc = get_tpm(&dev);
if (rc)
return rc;
rc = tpm_get_desc(dev, buf, sizeof(buf));
if (rc < 0) {
printf("Couldn't get TPM info (%d)\n", rc);
return CMD_RET_FAILURE;
}
printf("%s\n", buf);
return 0;
}
static int do_tpm_raw_transfer(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
struct udevice *dev;
void *command;
uint8_t response[1024];
size_t count, response_length = sizeof(response);
uint32_t rc;
command = parse_byte_string(argv[1], NULL, &count);
if (!command) {
printf("Couldn't parse byte string %s\n", argv[1]);
return CMD_RET_FAILURE;
}
rc = get_tpm(&dev);
if (rc)
return rc;
rc = tpm_xfer(dev, command, count, response, &response_length);
free(command);
if (!rc) {
puts("tpm response:\n");
print_byte_string(response, response_length);
}
return report_return_code(rc);
}
static int do_tpm_nv_define(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t index, perm, size;
if (argc != 4)
return CMD_RET_USAGE;
size = type_string_get_space_size(argv[1]);
if (!size) {
printf("Couldn't parse arguments\n");
return CMD_RET_USAGE;
}
index = simple_strtoul(argv[2], NULL, 0);
perm = simple_strtoul(argv[3], NULL, 0);
return report_return_code(tpm_nv_define_space(index, perm, size));
}
static int do_tpm_nv_read(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t index, count, err;
void *data;
if (argc < 3)
return CMD_RET_USAGE;
if (argc != 3 + type_string_get_num_values(argv[1]))
return CMD_RET_USAGE;
index = simple_strtoul(argv[2], NULL, 0);
data = type_string_alloc(argv[1], &count);
if (!data) {
printf("Couldn't parse arguments\n");
return CMD_RET_USAGE;
}
err = tpm_nv_read_value(index, data, count);
if (!err) {
if (type_string_write_vars(argv[1], data, argv + 3)) {
printf("Couldn't write to variables\n");
err = ~0;
}
}
free(data);
return report_return_code(err);
}
static int do_tpm_nv_write(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t index, count, err;
void *data;
if (argc < 3)
return CMD_RET_USAGE;
if (argc != 3 + type_string_get_num_values(argv[1]))
return CMD_RET_USAGE;
index = simple_strtoul(argv[2], NULL, 0);
data = type_string_alloc(argv[1], &count);
if (!data) {
printf("Couldn't parse arguments\n");
return CMD_RET_USAGE;
}
if (type_string_pack(argv[1], argv + 3, data)) {
printf("Couldn't parse arguments\n");
free(data);
return CMD_RET_USAGE;
}
err = tpm_nv_write_value(index, data, count);
free(data);
return report_return_code(err);
}
#ifdef CONFIG_TPM_AUTH_SESSIONS
static int do_tpm_oiap(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t auth_handle, err;
err = tpm_oiap(&auth_handle);
return report_return_code(err);
}
static int do_tpm_load_key2_oiap(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t parent_handle, key_len, key_handle, err;
uint8_t usage_auth[DIGEST_LENGTH];
void *key;
if (argc < 5)
return CMD_RET_USAGE;
parent_handle = simple_strtoul(argv[1], NULL, 0);
key = (void *)simple_strtoul(argv[2], NULL, 0);
key_len = simple_strtoul(argv[3], NULL, 0);
if (strlen(argv[4]) != 2 * DIGEST_LENGTH)
return CMD_RET_FAILURE;
parse_byte_string(argv[4], usage_auth, NULL);
err = tpm_load_key2_oiap(parent_handle, key, key_len, usage_auth,
&key_handle);
if (!err)
printf("Key handle is 0x%x\n", key_handle);
return report_return_code(err);
}
static int do_tpm_get_pub_key_oiap(cmd_tbl_t *cmdtp, int flag,
int argc, char * const argv[])
{
uint32_t key_handle, err;
uint8_t usage_auth[DIGEST_LENGTH];
uint8_t pub_key_buffer[TPM_PUBKEY_MAX_LENGTH];
size_t pub_key_len = sizeof(pub_key_buffer);
if (argc < 3)
return CMD_RET_USAGE;
key_handle = simple_strtoul(argv[1], NULL, 0);
if (strlen(argv[2]) != 2 * DIGEST_LENGTH)
return CMD_RET_FAILURE;
parse_byte_string(argv[2], usage_auth, NULL);
err = tpm_get_pub_key_oiap(key_handle, usage_auth,
pub_key_buffer, &pub_key_len);
if (!err) {
printf("dump of received pub key structure:\n");
print_byte_string(pub_key_buffer, pub_key_len);
}
return report_return_code(err);
}
TPM_COMMAND_NO_ARG(tpm_end_oiap)
#endif /* CONFIG_TPM_AUTH_SESSIONS */
#define MAKE_TPM_CMD_ENTRY(cmd) \
U_BOOT_CMD_MKENT(cmd, 0, 1, do_tpm_ ## cmd, "", "")
static cmd_tbl_t tpm_commands[] = {
U_BOOT_CMD_MKENT(info, 0, 1, do_tpm_info, "", ""),
U_BOOT_CMD_MKENT(init, 0, 1,
do_tpm_init, "", ""),
U_BOOT_CMD_MKENT(startup, 0, 1,
do_tpm_startup, "", ""),
U_BOOT_CMD_MKENT(self_test_full, 0, 1,
do_tpm_self_test_full, "", ""),
U_BOOT_CMD_MKENT(continue_self_test, 0, 1,
do_tpm_continue_self_test, "", ""),
U_BOOT_CMD_MKENT(force_clear, 0, 1,
do_tpm_force_clear, "", ""),
U_BOOT_CMD_MKENT(physical_enable, 0, 1,
do_tpm_physical_enable, "", ""),
U_BOOT_CMD_MKENT(physical_disable, 0, 1,
do_tpm_physical_disable, "", ""),
U_BOOT_CMD_MKENT(nv_define_space, 0, 1,
do_tpm_nv_define_space, "", ""),
U_BOOT_CMD_MKENT(nv_read_value, 0, 1,
do_tpm_nv_read_value, "", ""),
U_BOOT_CMD_MKENT(nv_write_value, 0, 1,
do_tpm_nv_write_value, "", ""),
U_BOOT_CMD_MKENT(extend, 0, 1,
do_tpm_extend, "", ""),
U_BOOT_CMD_MKENT(pcr_read, 0, 1,
do_tpm_pcr_read, "", ""),
U_BOOT_CMD_MKENT(tsc_physical_presence, 0, 1,
do_tpm_tsc_physical_presence, "", ""),
U_BOOT_CMD_MKENT(read_pubek, 0, 1,
do_tpm_read_pubek, "", ""),
U_BOOT_CMD_MKENT(physical_set_deactivated, 0, 1,
do_tpm_physical_set_deactivated, "", ""),
U_BOOT_CMD_MKENT(get_capability, 0, 1,
do_tpm_get_capability, "", ""),
U_BOOT_CMD_MKENT(raw_transfer, 0, 1,
do_tpm_raw_transfer, "", ""),
U_BOOT_CMD_MKENT(nv_define, 0, 1,
do_tpm_nv_define, "", ""),
U_BOOT_CMD_MKENT(nv_read, 0, 1,
do_tpm_nv_read, "", ""),
U_BOOT_CMD_MKENT(nv_write, 0, 1,
do_tpm_nv_write, "", ""),
#ifdef CONFIG_TPM_AUTH_SESSIONS
U_BOOT_CMD_MKENT(oiap, 0, 1,
do_tpm_oiap, "", ""),
U_BOOT_CMD_MKENT(end_oiap, 0, 1,
do_tpm_end_oiap, "", ""),
U_BOOT_CMD_MKENT(load_key2_oiap, 0, 1,
do_tpm_load_key2_oiap, "", ""),
U_BOOT_CMD_MKENT(get_pub_key_oiap, 0, 1,
do_tpm_get_pub_key_oiap, "", ""),
#endif /* CONFIG_TPM_AUTH_SESSIONS */
};
static int do_tpm(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
cmd_tbl_t *tpm_cmd;
if (argc < 2)
return CMD_RET_USAGE;
tpm_cmd = find_cmd_tbl(argv[1], tpm_commands, ARRAY_SIZE(tpm_commands));
if (!tpm_cmd)
return CMD_RET_USAGE;
return tpm_cmd->cmd(cmdtp, flag, argc - 1, argv + 1);
}
U_BOOT_CMD(tpm, CONFIG_SYS_MAXARGS, 1, do_tpm,
"Issue a TPM command",
"cmd args...\n"
" - Issue TPM command <cmd> with arguments <args...>.\n"
"Admin Startup and State Commands:\n"
" info - Show information about the TPM\n"
" init\n"
" - Put TPM into a state where it waits for 'startup' command.\n"
" startup mode\n"
" - Issue TPM_Starup command. <mode> is one of TPM_ST_CLEAR,\n"
" TPM_ST_STATE, and TPM_ST_DEACTIVATED.\n"
"Admin Testing Commands:\n"
" self_test_full\n"
" - Test all of the TPM capabilities.\n"
" continue_self_test\n"
" - Inform TPM that it should complete the self-test.\n"
"Admin Opt-in Commands:\n"
" physical_enable\n"
" - Set the PERMANENT disable flag to FALSE using physical presence as\n"
" authorization.\n"
" physical_disable\n"
" - Set the PERMANENT disable flag to TRUE using physical presence as\n"
" authorization.\n"
" physical_set_deactivated 0|1\n"
" - Set deactivated flag.\n"
"Admin Ownership Commands:\n"
" force_clear\n"
" - Issue TPM_ForceClear command.\n"
" tsc_physical_presence flags\n"
" - Set TPM device's Physical Presence flags to <flags>.\n"
"The Capability Commands:\n"
" get_capability cap_area sub_cap addr count\n"
" - Read <count> bytes of TPM capability indexed by <cap_area> and\n"
" <sub_cap> to memory address <addr>.\n"
#ifdef CONFIG_TPM_AUTH_SESSIONS
"Storage functions\n"
" loadkey2_oiap parent_handle key_addr key_len usage_auth\n"
" - loads a key data from memory address <key_addr>, <key_len> bytes\n"
" into TPM using the parent key <parent_handle> with authorization\n"
" <usage_auth> (20 bytes hex string).\n"
" get_pub_key_oiap key_handle usage_auth\n"
" - get the public key portion of a loaded key <key_handle> using\n"
" authorization <usage auth> (20 bytes hex string)\n"
#endif /* CONFIG_TPM_AUTH_SESSIONS */
"Endorsement Key Handling Commands:\n"
" read_pubek addr count\n"
" - Read <count> bytes of the public endorsement key to memory\n"
" address <addr>\n"
"Integrity Collection and Reporting Commands:\n"
" extend index digest_hex_string\n"
" - Add a new measurement to a PCR. Update PCR <index> with the 20-bytes\n"
" <digest_hex_string>\n"
" pcr_read index addr count\n"
" - Read <count> bytes from PCR <index> to memory address <addr>.\n"
#ifdef CONFIG_TPM_AUTH_SESSIONS
"Authorization Sessions\n"
" oiap\n"
" - setup an OIAP session\n"
" end_oiap\n"
" - terminates an active OIAP session\n"
#endif /* CONFIG_TPM_AUTH_SESSIONS */
"Non-volatile Storage Commands:\n"
" nv_define_space index permission size\n"
" - Establish a space at index <index> with <permission> of <size> bytes.\n"
" nv_read_value index addr count\n"
" - Read <count> bytes from space <index> to memory address <addr>.\n"
" nv_write_value index addr count\n"
" - Write <count> bytes from memory address <addr> to space <index>.\n"
"Miscellaneous helper functions:\n"
" raw_transfer byte_string\n"
" - Send a byte string <byte_string> to TPM and print the response.\n"
" Non-volatile storage helper functions:\n"
" These helper functions treat a non-volatile space as a non-padded\n"
" sequence of integer values. These integer values are defined by a type\n"
" string, which is a text string of 'bwd' characters: 'b' means a 8-bit\n"
" value, 'w' 16-bit value, 'd' 32-bit value. All helper functions take\n"
" a type string as their first argument.\n"
" nv_define type_string index perm\n"
" - Define a space <index> with permission <perm>.\n"
" nv_read types_string index vars...\n"
" - Read from space <index> to environment variables <vars...>.\n"
" nv_write types_string index values...\n"
" - Write to space <index> from values <values...>.\n"
);
| 25.531756 | 79 | 0.690518 |
ebe197e0dca469e6669ae9fa04fcee3d13740df8 | 2,603 | h | C | Sources/CConfig.h | jpez1432/Legacy-Monster-Freestyle-Racing | bc370736643531d1bf310bd45453cd98036b58a4 | [
"Info-ZIP"
] | null | null | null | Sources/CConfig.h | jpez1432/Legacy-Monster-Freestyle-Racing | bc370736643531d1bf310bd45453cd98036b58a4 | [
"Info-ZIP"
] | null | null | null | Sources/CConfig.h | jpez1432/Legacy-Monster-Freestyle-Racing | bc370736643531d1bf310bd45453cd98036b58a4 | [
"Info-ZIP"
] | null | null | null |
// Define
#ifndef CCONFIG_H
#define CCONFIG_H
// Include
#include "Shared.h" // Shared Header File
#include "CXml.h" // Xml Class Header File
// CConfig Class
class CConfig
{
private:
CXmlParser *cXml; // Xml Class Object
public:
CConfig( ); // Constructor
~CConfig( ); // Destructor
// Load Configuration File
bool LoadConfig( string Filename );
// Save Configuration File
bool SaveConfig( string Filename );
// Convert Integer Number To String
string NtoS( int i );
// Return Boolean Value
bool GetBool( int Value ) { if ( Value == 0 ) return false; else return true; }
// Return Int Value
int GetInt( bool Value ) { if ( Value == true ) return 1; else return 0; }
// Debug
bool RenderInfo; // Render Debug Information
bool EnableConsole; // Enable Debug Console
bool SkipIntro; // Skip Intro Flag
// Disable
bool Fullscreen; // Fullscreen Flag
bool UseRefresh; // Use Refresh Rate
int RefreshRate; // Refresh Rate
int DisplayWidth; // Resolution Width
int DisplayHeight; // Resolution Height
int DisplayDepth; // Display Bits Per Pixel
// OpenGL
float FieldOfVision; // Field Of Vision
float ZDrawDistance; // Z Draw Distance
int TextureFilter; // Texture Filtering
// Camera
string RotateLeft; // Rotate Right Key
string RotateRight; // Rotate Left Key
string RotateUp; // Rotate Up Key
string RotateDown; // Rotate Down Key
string ZoomIn; // Zoom In Key
string ZoomOut; // Zoom Out Key
// Sound
bool UseSound; // Use Sound Flag
string EngineSound; // Engine Sound String
int Volume; // Sound Volume
// Input
bool UseJoystick; // Use Joy/Wheel Flag
string Gas; // Gas Key
string Brake; // Brake Key
string FrontSteerLeft; // Steer Front Left Key
string FrontSteerRight; // Steer Front Right Key
string RearSteerLeft; // Steer Rear Left Key
string RearSteerRight; // Steer Rear Right Key
// Game Options
bool UsePodFiles; // Use Pod Files Flag
bool UseReflections; // Use Reflections Flag
bool UseLenseFlare; // Use Lense Flare Flag
bool WrapTrack; // Wrap Track Flag
int Weather; // Weather Flag
int SceneryComplexity; // Complexity Flag
string TrackName; // Track Name
string TruckName; // Truck Name
};
#endif // Endif
| 28.604396 | 82 | 0.604687 |
640fc21f0d9077d370ae0d02c2e1074b9af21a25 | 2,294 | h | C | kern/include/thumips_tlb.h | a1exwang/ucore_mips_vwtf | 3071db3596544b75b96c101888352d68fae17673 | [
"MIT"
] | null | null | null | kern/include/thumips_tlb.h | a1exwang/ucore_mips_vwtf | 3071db3596544b75b96c101888352d68fae17673 | [
"MIT"
] | null | null | null | kern/include/thumips_tlb.h | a1exwang/ucore_mips_vwtf | 3071db3596544b75b96c101888352d68fae17673 | [
"MIT"
] | null | null | null | /*
* =====================================================================================
*
* Filename: thumips_tlb.h
*
* Description:
*
* Version: 1.0
* Created: 07/06/2012 10:20:30 AM
* Revision: none
* Compiler: gcc
*
* Author: Chen Yuheng (Chen Yuheng), chyh1990@163.com
* Organization: Tsinghua Unv.
*
* =====================================================================================
*/
#ifndef _THUMIPS_TLB_H
#define _THUMIPS_TLB_H
#include <asm/mipsregs.h>
#include <memlayout.h>
#include <glue_pgmap.h>
#include <stdio.h>
#define THUMIPS_TLB_ENTRYL_V (1<<1)
#define THUMIPS_TLB_ENTRYL_D (1<<2)
#define THUMIPS_TLB_ENTRYL_G (1<<0)
#define THUMIPS_TLB_ENTRYH_VPN2_MASK (~0x1FFF)
static inline void write_one_tlb(int index, unsigned int pagemask, unsigned int hi, unsigned int low0, unsigned int low1)
{
write_c0_entrylo0(low0);
write_c0_pagemask(pagemask);
write_c0_entrylo1(low1);
write_c0_entryhi(hi);
write_c0_index(index);
/*
if (hi < 0x80000000u || hi >= 0xc0000000u)
kprintf("write_one_tlb: %d %x %x %x %x\n",
index, pagemask, hi, low0, low1);
*/
tlb_write_indexed();
}
/*
static inline void tlb_replace_random(unsigned int pagemask, unsigned int hi, unsigned int low0, unsigned int low1)
{
write_c0_entrylo0(low0);
write_c0_pagemask(pagemask);
write_c0_entrylo1(low1);
write_c0_entryhi(hi);
tlb_write_random();
}
*/
#define PTE2TLBLOW(x) (((((uint32_t)(*(x))-KERNBASE)>> 12)<<6)|THUMIPS_TLB_ENTRYL_V|THUMIPS_TLB_ENTRYL_D|(2<<3))
static inline uint32_t pte2tlblow(pte_t pte)
{
uint32_t t = (((uint32_t)pte - KERNBASE ) >> 12)<<6;
if(!ptep_present(&pte))
return 0;
t |= THUMIPS_TLB_ENTRYL_V;
/* always ignore ASID */
t |= THUMIPS_TLB_ENTRYL_G;
t |= (2<<3);
if(ptep_s_write(&pte))
t |= THUMIPS_TLB_ENTRYL_D;
return t;
}
static inline void tlb_refill(uint32_t badaddr, pte_t *pte)
{
if(!pte)
return ;
if(badaddr & (1<<12))
pte--;
//tlb_replace_random(0, badaddr & THUMIPS_TLB_ENTRYH_VPN2_MASK,
// pte2tlblow(*pte), pte2tlblow(*(pte+1)));
static int index = 0;
write_one_tlb(index++/*(badaddr >> 13)*/, 0, badaddr & THUMIPS_TLB_ENTRYH_VPN2_MASK,
pte2tlblow(*pte), pte2tlblow(*(pte+1)));
}
void tlb_invalidate_all();
#endif
| 26.367816 | 121 | 0.627724 |
8abe01e038b028c45426b3026ce5a3dda7b466ce | 2,400 | c | C | Exercises/Exercises/hashconjuntos.c | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | Exercises/Exercises/hashconjuntos.c | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | Exercises/Exercises/hashconjuntos.c | whoiswelliton/Algorithms_and_Data_Structures | 8aded4a427c68f6c89135fd8c0094dc361bd1538 | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define TAM 1021
//TABELA HASH COM TRATAMENTO DE COLISÕES POR ENCADEAMENTO SEPARADO
typedef struct celula{
int conteudo;
struct celula*prox;
struct celula*ant;
}celula;
typedef struct listaDENC{
celula*inicio;
int cont;
}listaDENC;
listaDENC *inicializa()
{
listaDENC* l = (listaDENC*) malloc(sizeof(listaDENC));
l->inicio = NULL;
l->cont = 0;
return l;
}
celula *cria(int conteudo)
{
celula *p = malloc(sizeof(celula));
p->conteudo = conteudo;
p->prox = NULL;
p->ant = NULL;
return p;
}
int HASH(int conteudo)
{
return(conteudo % TAM);
}
int insere_inicio(listaDENC *l, int conteudo)
{
if(l == NULL)
{
return 0;
}
celula *novo = cria(conteudo);
if(novo == NULL)
{
return 0;
}
novo->prox = l->inicio;
novo->ant = NULL;
l->inicio = novo;
if(novo->prox != NULL)
{
novo->prox->ant = novo;
}
l->cont++;
return 1;
}
int insere_fim(listaDENC *l, int conteudo)
{
if(l->inicio==NULL)
{
return(insere_inicio(l,conteudo));
}
celula *novo = cria(conteudo);
if(novo==NULL)
{
return (0);
}
celula *ultimo = l->inicio;
while(ultimo->prox !=NULL)
{
ultimo = ultimo->prox;
}
ultimo->prox=novo;
l->cont++;
return 1;
}
void imprimelista (listaDENC *l)
{
celula *p;
for(p = l->inicio;p != NULL;p = p->prox)
{
printf("%d ", p->conteudo);
}
}
void imprime_lista (listaDENC *l)
{
celula *p =l->inicio;
while(p->prox != NULL)
{
printf("%d ", p->conteudo);
p = p->prox;
}
printf("%d ", p->conteudo);
}
int main(void)
{
int i,j, N;
int conteudo;
int flagrepetida=0;
i=j=0;
scanf("%d",&N);
listaDENC** tab = (listaDENC**)malloc(TAM*sizeof(listaDENC*));
for (i = 0; i < TAM; i++)
{
tab[i] = inicializa();
}
for(i = 0;i < N; i++)
{
scanf("%d",&conteudo);
for(j = 0;j < TAM; j++)
{
if(tab[j]->inicio != NULL)
{
if(tab[j]->inicio->conteudo == conteudo)
{
flagrepetida = 1;
}
}
}
if(flagrepetida == 0)
{
insere_fim(tab[HASH(conteudo)],conteudo);
}
else
{
flagrepetida = 0;
}
}
for(i = 0;i < TAM; i++)
{
if(tab[i]->inicio != NULL)
{
imprime_lista(tab[i]);
}
}
return(0);
}
| 13.793103 | 66 | 0.540417 |
9ccf31e1465378d729f0717709b743c2bbb2123d | 400 | h | C | world/Chars.h | l4l/rl | 7b72f5a7a4e0a0160d4ef1b3a1839d760b9cb2ce | [
"WTFPL"
] | 1 | 2015-10-08T18:58:23.000Z | 2015-10-08T18:58:23.000Z | world/Chars.h | l4l/rl | 7b72f5a7a4e0a0160d4ef1b3a1839d760b9cb2ce | [
"WTFPL"
] | null | null | null | world/Chars.h | l4l/rl | 7b72f5a7a4e0a0160d4ef1b3a1839d760b9cb2ce | [
"WTFPL"
] | null | null | null | #ifndef CLIENT_CHARS_H
#define CLIENT_CHARS_H
namespace game {
#define CHARS_NUM 5
enum CharType {
WAR,
ARCH,
ROG,
MAGE,
CUSTOM
};
// Base stats
// TODO
#define WAR_BASE_STATS {}
#define ARCH_BASE_STATS {}
#define ROG_BASE_STATS {}
#define MAGE_BASE_STATS {}
#define CUSTOM_BASE_STATS {}
}
#endif //CLIENT_CHARS_H
| 14.814815 | 32 | 0.595 |
140206f9cc43bd75a345852cd2798a1a7b074f5f | 495 | h | C | iOS/Examples/Maps/Maps/MapsAppDelegate.h | AppBlade/AppBladeSDK | ff46fcec1d11a4464a1b81068cb8122f5fde5200 | [
"MIT"
] | 3 | 2015-03-19T17:11:06.000Z | 2016-12-01T20:47:56.000Z | iOS/Examples/Maps/Maps/MapsAppDelegate.h | AppBlade/AppBladeSDK | ff46fcec1d11a4464a1b81068cb8122f5fde5200 | [
"MIT"
] | 6 | 2015-03-27T08:53:53.000Z | 2016-12-03T08:44:56.000Z | iOS/Examples/Maps/Maps/MapsAppDelegate.h | AppBlade/AppBladeSDK | ff46fcec1d11a4464a1b81068cb8122f5fde5200 | [
"MIT"
] | 8 | 2015-01-13T10:53:04.000Z | 2020-11-04T06:33:51.000Z | //
// MapsAppDelegate.h
// Maps
//
// Created by Craig Spitzkoff on 5/31/11.
// Copyright 2011 Raizlabs Corporation. All rights reserved.
//
#define APPBLADE_DEBUG_LOGGING 1
#define APPBLADE_ERROR_LOGGING 1
#import <UIKit/UIKit.h>
@class MainViewController;
@interface MapsAppDelegate : NSObject <UIApplicationDelegate, UIAlertViewDelegate> {
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MainViewController *mainViewController;
@end
| 22.5 | 84 | 0.775758 |
6cbb5b8f7ca298b26cccaeb3036a7ca1a7a9c4ea | 2,398 | c | C | testfiles/testfileSlice15.c | DantheJack/SliCer | 9cb93dcf0cb9fa5174bf7482fb5f0d02bbce20a9 | [
"MIT"
] | null | null | null | testfiles/testfileSlice15.c | DantheJack/SliCer | 9cb93dcf0cb9fa5174bf7482fb5f0d02bbce20a9 | [
"MIT"
] | null | null | null | testfiles/testfileSlice15.c | DantheJack/SliCer | 9cb93dcf0cb9fa5174bf7482fb5f0d02bbce20a9 | [
"MIT"
] | null | null | null | main()
{
int H;
H = 0;
float x[12];
float var2, var3, var4 ;
float var5, var1;
float ssq;
float avg;
float dev;
int i, n;
int settings_Variable1, settings_Variable2 = 0, settings_Variable3;
var4 = 0 ;
var2 = 0 ;
settings_Variable1 = 1;
if(settings_Variable1 != 0){
ssq = 0 ;
dev = 0;
settings_Variable3 = 1;
scanf ("%d", &n);
for ( i = 0 ; i < n ; i = i + 1)
{
scanf ("%f", &x[i]);
if(settings_Variable1 <= 0 && settings_Variable1 != -3) var2 = var2 + x[i];
else if (settings_Variable1 == var2) ssq = ssq + x[i] * x[i];
else if (settings_Variable3 == var2) ++settings_Variable2;
}
avg = var2 / n; H = 8;
if(settings_Variable2 == 0)
{
settings_Variable2 = 1;
}
else for(i = 0 ; i < n ; i = i + 1) {
if(settings_Variable2 <= 0 && settings_Variable2 != -3) var2 = var2 + x[i];
else if (settings_Variable2 == var2) ssq = ssq + x[i] * x[i];
else if (settings_Variable3 == var2) dev = -1; var2 *= 10;
}}
else{
scanf ("%d",&dev);
scanf ("%d",&settings_Variable3);
dev = 2*dev;
var3 = dev*var2;
scanf ("%d",&avg);
var1 = settings_Variable3 + avg;
var3 = (ssq - n * avg * avg) / (n - 1);
var4 = (ssq - var2 * avg) / (n - 1);
if(var2 == 0) var2 = var2 * var2 / n;
if(var2 > 18) var3 = 0; else if (var2 > 0) var3 = 14;
else var3 = 14; if (var3 == 0 || var3 == 14){
for (i = 0; i < dev; i++) { var3 += var2; }
scanf ("%d",&var2);
var2 = (ssq - var2 ) / (n - 1);
var2 = 0 ;
}
else if (settings_Variable3 % 2 == 0){
for ( i = 0 ; i < n ; i = i + 1)
{
dev = x[i] - avg ;
var4 = dev ;
var2 = dev * dev ; H = dev * 2;
}} else {
while (var2 > 0){
var2 = 6; H = 3;
var5 = (var2 - var4 * var4 / n ) / (n -1);
var1 = var2 / (n - 1);
printf("variance (two pass): %f \n",var1);
}
}
var5 = (var2 - var4 * var4 / n ) / (n -1);
printf("variance (two pass): %f \n",var1);
var3 = var3 + var1;
var1 = var2 / (n - 1);
var2 = -1 + var5;
ssq = avg + var2 + H;
printf ("%d %d\n",var3,var1);
}
} | 31.142857 | 83 | 0.437448 |
8c2ed6ff0a556d730cb55dbb607cfb59b04bfa19 | 270 | h | C | interrupt.h | daniRiesgo/OS-Thread-Scheduler-simulation | 95a6c73565da3b2b42eed9fe28561a01035a303c | [
"MIT"
] | null | null | null | interrupt.h | daniRiesgo/OS-Thread-Scheduler-simulation | 95a6c73565da3b2b42eed9fe28561a01035a303c | [
"MIT"
] | null | null | null | interrupt.h | daniRiesgo/OS-Thread-Scheduler-simulation | 95a6c73565da3b2b42eed9fe28561a01035a303c | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <sys/time.h>
#include <signal.h>
#include <stdlib.h>
#include <ucontext.h>
#include <unistd.h>
#define TICK_TIME 5000
#define STARVATION 300
void timer_interrupt ();
void init_interrupt();
void disable_interrupt();
void enable_interrupt();
| 18 | 25 | 0.748148 |
f02113252b2077235e0c222b74435007fee036cd | 331 | h | C | linkage/source/backgrounds.h | otrho/ragbag | be6212e82c4b6e393bddd08979b29d84592a3500 | [
"MIT"
] | null | null | null | linkage/source/backgrounds.h | otrho/ragbag | be6212e82c4b6e393bddd08979b29d84592a3500 | [
"MIT"
] | null | null | null | linkage/source/backgrounds.h | otrho/ragbag | be6212e82c4b6e393bddd08979b29d84592a3500 | [
"MIT"
] | null | null | null | #pragma once
// Use BG1 for the puzzle tiles. Load the tile data to the first character block, use the last
// screen block for the tilemap.
#define PUZZLE_BG_IDX 1
#define CHAR_BASE_IDX 0
#define MAP_BASE_IDX 28
#define LIT_PALETTE 0
#define DULL_PALETTE 1
void init_puzzle_bg();
void palette_flash_screen(s32 total_frames);
| 22.066667 | 95 | 0.785498 |
1595c3ddcdb994637f385520904eb5e9b8e37b0a | 5,131 | h | C | api/nntrainer-api-common.h | kparichay/nntrainer | 79e37918a3ced623346e285993d6714cb5d1e14b | [
"Apache-2.0"
] | null | null | null | api/nntrainer-api-common.h | kparichay/nntrainer | 79e37918a3ced623346e285993d6714cb5d1e14b | [
"Apache-2.0"
] | null | null | null | api/nntrainer-api-common.h | kparichay/nntrainer | 79e37918a3ced623346e285993d6714cb5d1e14b | [
"Apache-2.0"
] | null | null | null | // SPDX-License-Identifier: Apache-2.0-only
/**
* Copyright (C) 2020 Parichay Kapoor <pk.kapoor@samsung.com>
*
* @file nntrainer-api-common.h
* @date 02 April 2020
* @brief NNTrainer Common-API Header.
* @see https://github.com/nnstreamer/nntrainer
* @author Parichay Kapoor <pk.kapoor@samsung.com>
* @bug No known bugs except for NYI items
*/
#ifndef __TIZEN_MACHINELEARNING_NNTRAINER_API_COMMON_H__
#define __TIZEN_MACHINELEARNING_NNTRAINER_API_COMMON_H__
/**
* @addtogroup CAPI_ML_NNTRAINER_TRAIN_MODULE
* @{
*/
/**
* @brief Dataset generator callback function for train/valid/test data.
*
* @details The user of the API must provide this callback function to supply
* data to the model and register the callback with
* ml_train_dataset_create_with_generator(). The model will call this callback
* whenever it needs more data. This function should provide a single element of
* input and label data in the passed containers. The containers passed by the
* caller will already be allocated with sufficient space to contain the data.
* This function callback should fill the data row-wise in the containers
* provided. The containers represent array of memory to hold inputs for the
* model. If the model contains two inputs, then input[0] will hold the first
* input, and input[1] will hold the second input. The same applies for labels
* as well. The number of inputs and labels, and the size of each input and
* label should match with the shape of each input and label set in the model.
* The order of the inputs/labels, in case of multiple of inputs/labels, will be
* determined based on the sequence of addition of the input layers to the
* model.
* @since_tizen 6.0
* @note This function can be called multiple times in parallel when total
* number of samples are set as a property for this dataset. In this case, last
* is only used for verification purposes. If total number of samples for the
* dataset is unknown, this function will be called in sequence.
* @param[out] input Container to hold all the input data. Should not be freed
* by the user.
* @param[out] label Container to hold corresponding label data. Should not be
* freed by the user.
* @param[out] last Container to notify if data is finished. Set true if no more
* data to provide, else set false. Should not be freed by the user.
* @param[in] user_data User application's private data.
* @return @c 0 on success. Otherwise a negative error value.
* @retval #ML_ERROR_NONE Successful.
* @retval #ML_ERROR_INVALID_PARAMETER Invalid parameter.
*
* A sample implementation of this function is below:
* Note : input data information available from outside this function.
* num_samples : total number of data samples in the dataset.
* count : number of samples already given.
* num_inputs : number of inputs.
* num_labels : number of labels.
* input_length[num_inputs] : length of the input. With (batch, c, h, w) as
* input shape, the length will be c * h * w.
* label_length[num_labels] : length of the label. With (batch, l) as label
* shape, then length will be l.
* @code
* // function signature :
* // int rand_dataset_generator (float **input, float **label, bool *last,
* // void *user_data).
*
* // This sample fills inputs and labels with random data.
* srand(0);
* if (count > num_samples) {
* *last = true;
* // handle preparation for start of next epoch
* return ML_ERROR_NONE;
* }
*
* // Fill input data
* for (int idx = 0; idx < num_inputs; ++ idx) {
* for (int len = 0; len < input_length[idx]; ++ len) {
* input[idx][len] = rand();
* }
* }
*
* // Fill label data
* for (int idx = 0; idx < num_inputs; ++ idx) {
* for (int len = 0; len < label_length[idx]; ++ len) {
* label[idx][len] = rand();
* }
* }
*
* // Update the helper variables
* count += 1;
*
* return ML_ERROR_NONE;
* @endcode
*
*
* Below is an example of the usage of this sample:
* @code
* int status;
* ml_train_dataset_h handle;
*
* status = ml_train_dataset_create_with_generator(&handle,
* rand_dataset_generator, NULL, NULL);
* if (status != ML_ERROR_NONE) {
* // handle error case.
* return status;
* }
*
* // Destroy the handle if not added to a model.
* status = ml_train_layer_destroy(handle);
* if (status != ML_ERROR_NONE) {
* // handle error case
* return status;
* }
* @endcode
*/
typedef int (*ml_train_datagen_cb)(float **input, float **label, bool *last,
void *user_data);
/**
* @brief Enumeration for the neural network summary verbosity of NNTrainer.
* @since_tizen 6.0
*/
typedef enum {
ML_TRAIN_SUMMARY_MODEL = 0, /**< Overview of model
summary with one-line layer information */
ML_TRAIN_SUMMARY_LAYER, /**< Detailed model summary with layer properties */
ML_TRAIN_SUMMARY_TENSOR /**< Model summary layer's including weight
information */
} ml_train_summary_type_e;
/**
* @}
*/
#endif /* __TIZEN_MACHINELEARNING_NNTRAINER_API_COMMON_H__ */
| 36.913669 | 80 | 0.689144 |
9b73ec41ecb2278d252ce08ed207087298be9338 | 353 | h | C | QtumJsIosServer/qtum-ios-develop/qtum wallet/Auth and Login/Auth/RepeatePinOutput/RepeateOutputDelegate.h | shekoocoder/telepathy | 8da35e3dc41baf6f479b129dc723d8f321ccd39d | [
"MIT"
] | 1 | 2019-07-08T09:33:56.000Z | 2019-07-08T09:33:56.000Z | QtumJsIosServer/qtum-ios-develop/qtum wallet/Auth and Login/Auth/RepeatePinOutput/RepeateOutputDelegate.h | shekoocoder/telepathy | 8da35e3dc41baf6f479b129dc723d8f321ccd39d | [
"MIT"
] | null | null | null | QtumJsIosServer/qtum-ios-develop/qtum wallet/Auth and Login/Auth/RepeatePinOutput/RepeateOutputDelegate.h | shekoocoder/telepathy | 8da35e3dc41baf6f479b129dc723d8f321ccd39d | [
"MIT"
] | null | null | null | //
// RepeateOutputDelegate.h
// qtum wallet
//
// Created by Vladimir Lebedevich on 10.07.17.
// Copyright © 2017 QTUM. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol RepeateOutputDelegate <NSObject>
- (void)didCreateWalletPressed;
- (void)didCancelPressedOnRepeatePin;
- (void)didEnteredSecondPin:(NSString *) pin;
@end
| 17.65 | 47 | 0.736544 |
18bd5d8154bd901f100a1f2e1a3a18e2d476f927 | 177 | h | C | src/ntp_client.h | mashafrancis/almond-hw | a2ccde1c745eeae8f2c5bb4fdec9faede0ed1474 | [
"MIT"
] | null | null | null | src/ntp_client.h | mashafrancis/almond-hw | a2ccde1c745eeae8f2c5bb4fdec9faede0ed1474 | [
"MIT"
] | 1 | 2020-05-27T10:26:57.000Z | 2020-05-27T10:26:57.000Z | src/ntp_client.h | almond-hydroponics/almond-hw | a2ccde1c745eeae8f2c5bb4fdec9faede0ed1474 | [
"MIT"
] | null | null | null | #ifndef NTP_CLIENT_H
#define NTP_CLIENT_H
#include <cstdint>
/// @returns current time since epoc in seconds, on error returns 0
uint32_t ntp_update();
#endif //NTP_CLIENT_H
| 17.7 | 67 | 0.768362 |
0afbe870f944721dbf2cbc66d007852a699cdb0b | 386 | h | C | core/fm_mpx.h | unxcepted/FmRadioStreamer | 017076bebd71695622766d955ffa9f2d2180f204 | [
"WTFPL"
] | null | null | null | core/fm_mpx.h | unxcepted/FmRadioStreamer | 017076bebd71695622766d955ffa9f2d2180f204 | [
"WTFPL"
] | null | null | null | core/fm_mpx.h | unxcepted/FmRadioStreamer | 017076bebd71695622766d955ffa9f2d2180f204 | [
"WTFPL"
] | null | null | null | /*
PiFmAdv - Advanced FM transmitter for the Raspberry Pi
Copyright (C) 2017 Miegl
See https://github.com/Miegl/PiFmAdv
*/
extern int fm_mpx_open(char *filename, size_t len, int cutoff_freq, int preemphasis_corner_freq, int srate, int nochan);
extern int fm_mpx_get_samples(double *mpx_buffer, double *rds_buffer, float mpx, int rds, int wait);
extern int fm_mpx_close();
| 35.090909 | 120 | 0.756477 |
178ac3bfdcd78f8c4843dcbefc170493a5404549 | 4,009 | h | C | include/QtPositioning/qgeopath.h | nesbox/qt5-static-linux2 | 16c9bce4e6ceab3675c517f1892144e81e172bcd | [
"Libpng",
"Zlib"
] | 2 | 2019-03-07T11:19:06.000Z | 2021-07-05T18:15:03.000Z | include/QtPositioning/qgeopath.h | nesbox/qt5-static-linux2 | 16c9bce4e6ceab3675c517f1892144e81e172bcd | [
"Libpng",
"Zlib"
] | null | null | null | include/QtPositioning/qgeopath.h | nesbox/qt5-static-linux2 | 16c9bce4e6ceab3675c517f1892144e81e172bcd | [
"Libpng",
"Zlib"
] | 2 | 2019-07-26T09:24:47.000Z | 2021-04-07T15:30:36.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtPositioning module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QGEOPATH_H
#define QGEOPATH_H
#include <QtPositioning/QGeoShape>
#include <QtCore/QVariantList>
QT_BEGIN_NAMESPACE
class QGeoCoordinate;
class QGeoPathPrivate;
class Q_POSITIONING_EXPORT QGeoPath : public QGeoShape
{
Q_GADGET
Q_PROPERTY(QVariantList path READ variantPath WRITE setVariantPath)
Q_PROPERTY(qreal width READ width WRITE setWidth)
public:
QGeoPath();
QGeoPath(const QList<QGeoCoordinate> &path, const qreal &width = 0.0);
QGeoPath(const QGeoPath &other);
QGeoPath(const QGeoShape &other);
~QGeoPath();
QGeoPath &operator=(const QGeoPath &other);
using QGeoShape::operator==;
bool operator==(const QGeoPath &other) const;
using QGeoShape::operator!=;
bool operator!=(const QGeoPath &other) const;
void setPath(const QList<QGeoCoordinate> &path);
const QList<QGeoCoordinate> &path() const;
void setVariantPath(const QVariantList &path);
QVariantList variantPath() const;
void setWidth(const qreal &width);
qreal width() const;
Q_INVOKABLE void translate(double degreesLatitude, double degreesLongitude);
Q_INVOKABLE QGeoPath translated(double degreesLatitude, double degreesLongitude) const;
Q_INVOKABLE double length(int indexFrom = 0, int indexTo = -1) const;
Q_INVOKABLE int size() const;
Q_INVOKABLE void addCoordinate(const QGeoCoordinate &coordinate);
Q_INVOKABLE void insertCoordinate(int index, const QGeoCoordinate &coordinate);
Q_INVOKABLE void replaceCoordinate(int index, const QGeoCoordinate &coordinate);
Q_INVOKABLE QGeoCoordinate coordinateAt(int index) const;
Q_INVOKABLE bool containsCoordinate(const QGeoCoordinate &coordinate) const;
Q_INVOKABLE void removeCoordinate(const QGeoCoordinate &coordinate);
Q_INVOKABLE void removeCoordinate(int index);
Q_INVOKABLE QString toString() const;
private:
inline QGeoPathPrivate *d_func();
inline const QGeoPathPrivate *d_func() const;
};
Q_DECLARE_TYPEINFO(QGeoPath, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
Q_DECLARE_METATYPE(QGeoPath)
#endif // QGEOPATH_H
| 37.46729 | 91 | 0.732103 |
0257c33ad439026ac3d8767085e2f8e40f8ca575 | 2,495 | h | C | src/elements/basis/TACSLineBasis.h | tchin-divergent/tacs | 34743b370da4ab6ea16d24de7c574c3fec9d333a | [
"Apache-2.0"
] | null | null | null | src/elements/basis/TACSLineBasis.h | tchin-divergent/tacs | 34743b370da4ab6ea16d24de7c574c3fec9d333a | [
"Apache-2.0"
] | null | null | null | src/elements/basis/TACSLineBasis.h | tchin-divergent/tacs | 34743b370da4ab6ea16d24de7c574c3fec9d333a | [
"Apache-2.0"
] | null | null | null | /*
This file is part of TACS: The Toolkit for the Analysis of Composite
Structures, a parallel finite-element code for structural and
multidisciplinary design optimization.
Copyright (C) 2014 Georgia Tech Research Corporation
TACS is 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
*/
#ifndef TACS_LINE_BASIS_H
#define TACS_LINE_BASIS_H
#include "TACSElementBasis.h"
/**
Basis class for a linear element
*/
class TACSLinearLineBasis : public TACSElementBasis {
public:
ElementLayout getLayoutType();
void getVisPoint( int n, double pt[] );
int getNumNodes();
int getNumParameters();
int getNumQuadraturePoints();
double getQuadratureWeight( int n );
double getQuadraturePoint( int n, double pt[] );
int getNumElementFaces();
int getNumFaceQuadraturePoints( int face );
double getFaceQuadraturePoint( int face, int n, double pt[], double t[] );
void computeBasis( const double pt[], double N[] );
void computeBasisGradient( const double pt[], double N[], double Nxi[] );
};
/**
Basis class for a quadratic element
*/
class TACSQuadraticLineBasis : public TACSElementBasis {
public:
ElementLayout getLayoutType();
void getVisPoint( int n, double pt[] );
int getNumNodes();
int getNumParameters();
int getNumQuadraturePoints();
double getQuadratureWeight( int n );
double getQuadraturePoint( int n, double pt[] );
int getNumElementFaces();
int getNumFaceQuadraturePoints( int face );
double getFaceQuadraturePoint( int face, int n, double pt[], double t[] );
void computeBasis( const double pt[], double N[] );
void computeBasisGradient( const double pt[], double N[], double Nxi[] );
};
/**
Basis class for a cubic element
*/
class TACSCubicLineBasis : public TACSElementBasis {
public:
ElementLayout getLayoutType();
void getVisPoint( int n, double pt[] );
int getNumNodes();
int getNumParameters();
int getNumQuadraturePoints();
double getQuadratureWeight( int n );
double getQuadraturePoint( int n, double pt[] );
int getNumElementFaces();
int getNumFaceQuadraturePoints( int face );
double getFaceQuadraturePoint( int face, int n, double pt[], double t[] );
void computeBasis( const double pt[], double N[] );
void computeBasisGradient( const double pt[], double N[], double Nxi[] );
};
#endif // TACS_LINE_BASIS_H
| 31.987179 | 76 | 0.72986 |
4fc107639da3117546cdbc5d5a79529eea6fc32f | 2,894 | c | C | pthreads/misc/forking_MT_prcs/mt_fork_exec.c | kaiwan/trg_linux_sysprg_L1 | 1ddd7c11604b137401943d29c9b462a043879f0b | [
"MIT"
] | null | null | null | pthreads/misc/forking_MT_prcs/mt_fork_exec.c | kaiwan/trg_linux_sysprg_L1 | 1ddd7c11604b137401943d29c9b462a043879f0b | [
"MIT"
] | null | null | null | pthreads/misc/forking_MT_prcs/mt_fork_exec.c | kaiwan/trg_linux_sysprg_L1 | 1ddd7c11604b137401943d29c9b462a043879f0b | [
"MIT"
] | 11 | 2020-11-27T11:27:47.000Z | 2022-02-23T14:11:36.000Z | /*
* mt_fork_exec.c
*
* Call fork() within a process that has multiple threads alive.
* Duplicates only the thread that invokes fork in the new child.
* Here, we demo this by having the "child" process (a copy of the
* thread that called fork()), exec the PDF reader app (evince)!
*
* (c) kaiwanTECH
* License: MIT
*/
#define _POSIX_C_SOURCE 200112L /* or earlier: 199506L */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define LAST_COL 79
// Thread p2
// write() 's "2" to stderr
void *thrd_p2(void *msg)
{
printf("%s(): will terminate in 2s...\n", __func__);
sleep(2);
pthread_exit(NULL);
}
/* Thread p3
* Parameter: the PDF file to view
*/
void *thrd_p3(void *msg)
{
pid_t n;
char *fname = (char *)msg;
if (!fname) {
fprintf(stderr, "%s(): PDF-file-to-view absent?\n", __func__);
exit(1);
}
printf("%s(): PID %d...fname=%s\n", __func__, getpid(), fname);
printf("+++ Worker thread 2: fork() in 3 seconds...\n");
sleep(3);
switch (n = fork()) {
case -1:
perror("fork failed");
exit(1);
case 0: // Child
printf("In child: PID %d. Exec-ing evince now ...\n", getpid());
if (execl
("/usr/bin/evince", "evince PDF reader", fname,
(char *)0) < 0) {
perror("execl failed!");
exit(1);
}
exit(0);
default:
printf("worker 2: waiting for child...\n");
printf("worker 2: child %d died...\n", wait(0));
}
pthread_exit(NULL);
}
int main(int argc, char **argv)
{
pthread_t p2, p3;
int fd, r;
void *ret;
if (argc == 1) {
fprintf(stderr, "Usage: %s PDF-file-to-view\n", argv[0]);
exit(1);
}
// Ensure this file is present!
fd = open(argv[1], O_RDONLY);
if (fd == -1) {
fprintf(stderr,
"%s: PDF-file-to-view \"%s\" not existing or unreadable?\n",
argv[0], argv[1]);
perror("File open failed");
exit(1);
}
close(fd);
// Create 2 threads (main p1 is parent..)
printf("p1 (the main() thread): now creating pthread p2..\n");
r = pthread_create(&p2, // thread id
NULL, // thread attributes (use default)
thrd_p2, // function to execute
(void *)argv[1]); // argument to function
if (r)
perror("pthread creation"), exit(1);
printf("p1 (the main() thread): now creating pthread p3..\n");
r = pthread_create(&p3, // thread id
NULL, // thread attributes (use default)
thrd_p3, // function to execute
(void *)argv[1]); // argument to function
if (r)
perror("pthread creation"), exit(1);
printf("p1: threads p2 and p3 created...\n");
fflush(stdout);
// Have main join on child threads
printf("main: join-ing ...\n");
if (pthread_join(p2, &ret) != 0)
perror("pthread join"), exit(1);
printf("p1: p2 has joined up\n");
if (pthread_join(p3, &ret) != 0)
perror("pthread join"), exit(1);
printf("p1: p3 has joined up\n");
exit(0);
}
| 23.528455 | 66 | 0.615411 |
ae3dbf19eb1b93ef7b7086371b84606f1b8dc4d8 | 3,457 | h | C | WRK-V1.2/clr/src/fusion/inc/mdlmgr.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/clr/src/fusion/inc/mdlmgr.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/clr/src/fusion/inc/mdlmgr.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | // ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, 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 __MDLMGR_H_INCLUDED__
#define __MDLMGR_H_INCLUDED__
#include "dbglog.h"
class CModDownloadMgr : public IDownloadMgr, public ICodebaseList
{
public:
CModDownloadMgr(IAssemblyName *pName, IAssemblyManifestImport *pManImport,
IApplicationContext *pAppCtx, CDebugLog *pdbglog);
virtual ~CModDownloadMgr();
HRESULT Init(LPCWSTR pwzCodebase, LPCWSTR pwzModuleName);
static HRESULT Create(CModDownloadMgr **ppDLMgr, IAssemblyName *pName,
IAssemblyManifestImport *pManImport,
IApplicationContext *pAppCtx, LPCWSTR pwzCodebase,
LPCWSTR pwzModuleName, CDebugLog *pdbglog);
// IUnknown methods
STDMETHODIMP QueryInterface(REFIID riid, void **ppv);
STDMETHODIMP_(ULONG) AddRef();
STDMETHODIMP_(ULONG) Release();
// IDownloadMgr methods
STDMETHODIMP DoSetup(LPCWSTR wzSourceUrl,
LPCWSTR wzFilePath,
const FILETIME *pftLastMod,
IUnknown **ppUnk,
IUnknown **ppAsmNI);
STDMETHODIMP ProbeFailed(IUnknown **ppUnk);
STDMETHODIMP PreDownloadCheck(void **ppv, void **ppvNI);
STDMETHODIMP IsDuplicate(IDownloadMgr *ppDLMgr);
STDMETHODIMP LogResult();
STDMETHODIMP DownloadEnabled(BOOL *pbEnabled);
STDMETHODIMP GetBindInfo(FusionBindInfo *pBindInfo);
STDMETHODIMP CacheBindingResult(HRESULT hrResult);
// ICodebaseList methods
STDMETHODIMP AddCodebase(LPCWSTR wzCodebase, DWORD dwFlags);
STDMETHODIMP RemoveCodebase(DWORD dwIndex);
STDMETHODIMP GetCodebase(DWORD dwIndex, DWORD *pdwFlags, __out_ecount_opt(*pcbCodebase) LPWSTR wzCodebase, DWORD *pcbCodebase);
STDMETHODIMP GetCount(DWORD *pdwCount);
STDMETHODIMP RemoveAll();
private:
DWORD _dwSig;
ULONG _cRef;
LONGLONG _llFlags;
DWORD _dwNumCodebases;
LPWSTR _pwzCodebase;
LPWSTR _pwzModuleName;
IAssemblyName *_pName;
IAssemblyManifestImport *_pManImport;
IApplicationContext *_pAppCtx;
CDebugLog *_pdbglog;
};
HRESULT AddModuleToAssembly(IApplicationContext *pAppCtx, IAssemblyName *pName,
LPCOLESTR pszURL, FILETIME *pftLastModTime,
LPCOLESTR szPath, LPCWSTR pwzModuleName,
IAssemblyManifestImport *pManImport,
CDebugLog *pdbglog,
IAssemblyModuleImport **ppModImport);
#endif
| 40.670588 | 135 | 0.573908 |
3ee467a4946b9239f5f6b96dcfb838b344d3d24e | 554 | c | C | examples/hello.c | jblang/TMS9918A | f2630b05a4b80e43477af0e26c37fdae76711682 | [
"Unlicense"
] | 86 | 2018-12-11T14:03:59.000Z | 2022-03-17T09:53:42.000Z | examples/hello.c | jblang/TMS9918A | f2630b05a4b80e43477af0e26c37fdae76711682 | [
"Unlicense"
] | 7 | 2019-03-12T19:41:52.000Z | 2021-02-18T15:18:06.000Z | examples/hello.c | jblang/TMS9918A | f2630b05a4b80e43477af0e26c37fdae76711682 | [
"Unlicense"
] | 15 | 2018-12-11T14:04:01.000Z | 2022-03-07T11:16:17.000Z | /*
* TMS9918A Hello World C example
*
* Compile with z88dk:
* zcc +cpm -create-app -ohello hello.c tmsc.asm z180c.asm
*/
#include <stdio.h>
#include <stdint.h>
#include "font.h"
#include "tms.h"
#include "z180.h"
main()
{
if (!TmsProbe()) {
printf("TMS9918A not found, aborting!\n");
return;
}
if (Z180Detect() != 0xFF) {
TmsSetWait(Z180GetClock());
} else {
TmsSetWait(0);
}
TmsTextMode(font);
TmsBackground(TMS_DARKBLUE);
TmsTextColor(TMS_WHITE);
TmsTextPos(0, 0);
TmsStrOut("hello, world");
} | 18.466667 | 59 | 0.617329 |
9933da80516e7498ffc46be30d7dc883b04d3b61 | 890 | h | C | src/uefi/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.h | kkennett/oscore.dev | 59e786f12f9af969211c95a9d2863b1767528341 | [
"BSD-3-Clause"
] | 1 | 2020-05-10T09:43:50.000Z | 2020-05-10T09:43:50.000Z | src/uefi/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.h | kkennett/oscore.dev | 59e786f12f9af969211c95a9d2863b1767528341 | [
"BSD-3-Clause"
] | null | null | null | src/uefi/EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.h | kkennett/oscore.dev | 59e786f12f9af969211c95a9d2863b1767528341 | [
"BSD-3-Clause"
] | null | null | null | /** @file
*
* Copyright (c) 2017, Linaro Limited. All rights reserved.
*
* This program and the accompanying materials are licensed and made available
* under the terms and conditions of the BSD License which accompanies this
* distribution. The full text of the license may be found at
* http://opensource.org/licenses/bsd-license.php
*
* THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
* WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*
**/
#ifndef __CONSOLE_PREF_DXE_H__
#define __CONSOLE_PREF_DXE_H__
#include <Guid/HiiPlatformSetupFormset.h>
#include <Guid/ConsolePrefFormSet.h>
#define CONSOLE_PREF_GRAPHICAL 0x0
#define CONSOLE_PREF_SERIAL 0x1
#define CONSOLE_PREF_VARIABLE_NAME L"ConsolePref"
typedef struct {
UINT8 Console;
UINT8 Reserved[3];
} CONSOLE_PREF_VARSTORE_DATA;
#endif
| 27.8125 | 80 | 0.755056 |
994f437fff6fa4f13c79ec650a5a511a66bfb918 | 1,177 | h | C | windows_gui/include/resource.h | dsanno/reverse_reversi | 2b6d74c5687cdfb968d72f2692b1d5b1ff97a5e1 | [
"MIT"
] | null | null | null | windows_gui/include/resource.h | dsanno/reverse_reversi | 2b6d74c5687cdfb968d72f2692b1d5b1ff97a5e1 | [
"MIT"
] | null | null | null | windows_gui/include/resource.h | dsanno/reverse_reversi | 2b6d74c5687cdfb968d72f2692b1d5b1ff97a5e1 | [
"MIT"
] | null | null | null | //{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by reversi_gui.rc
//
#define IDD_ABOUTBOX 100
#define IDR_MAINFRAME 128
#define IDR_REVERSTYPE 129
#define ID_PLAY_START 32771
#define ID_PLAY_BREAK 32772
#define ID_PLAY_UNDO 32773
#define ID_PLAY_BLACK 32774
#define ID_PLAY_WHITE 32775
#define ID_PLAY_LEVEL1 32776
#define ID_PLAY_LEVEL2 32777
#define ID_PLAY_LEVEL3 32778
#define ID_PLAY_LEVEL4 32779
#define ID_PLAY_LEVEL5 32780
#define ID_PLAY_LEVEL6 32781
#define ID_PLAY_LEVEL7 32782
#define ID_PLAY_LEVEL8 32783
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_3D_CONTROLS 1
#define _APS_NEXT_RESOURCE_VALUE 130
#define _APS_NEXT_COMMAND_VALUE 32784
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 35.666667 | 53 | 0.601529 |
996363fe578e31d2541aa5008b7fb92ca1bd5912 | 955 | h | C | Darkly/DataModels/LDFlagConfig/LDFlagCounter.h | ecobee/ios-client | 5f12ffab0e3ea494c5d4af3f674eed3b4fc04ffd | [
"Apache-2.0"
] | null | null | null | Darkly/DataModels/LDFlagConfig/LDFlagCounter.h | ecobee/ios-client | 5f12ffab0e3ea494c5d4af3f674eed3b4fc04ffd | [
"Apache-2.0"
] | null | null | null | Darkly/DataModels/LDFlagConfig/LDFlagCounter.h | ecobee/ios-client | 5f12ffab0e3ea494c5d4af3f674eed3b4fc04ffd | [
"Apache-2.0"
] | null | null | null | //
// LDFlagCounter.h
// Darkly
//
// Created by Mark Pokorny on 4/18/18. +JMJ
// Copyright © 2018 LaunchDarkly. All rights reserved.
//
#import <Foundation/Foundation.h>
@class LDFlagValueCounter;
@class LDFlagConfigValue;
@interface LDFlagCounter : NSObject <NSCopying>
@property (nonatomic, strong, nonnull, readonly) NSString *flagKey;
@property (nonatomic, strong, nonnull) id defaultValue;
@property (nonatomic, assign, readonly) BOOL hasLoggedRequests;
+(nonnull instancetype)counterWithFlagKey:(nonnull NSString*)flagKey defaultValue:(nonnull id)defaultValue;
-(nonnull instancetype)initWithFlagKey:(nonnull NSString*)flagKey defaultValue:(nonnull id)defaultValue;
-(void)logRequestWithFlagConfigValue:(nullable LDFlagConfigValue*)flagConfigValue reportedFlagValue:(nonnull id)reportedFlagValue;
-(nonnull NSDictionary*)dictionaryValue;
-(nonnull NSString*)description;
-(nonnull instancetype)copyWithZone:(nullable NSZone*)zone;
@end
| 31.833333 | 130 | 0.796859 |
3e3f04bd6b7ce90a874b65581beb6d8974667d7a | 1,137 | c | C | tests/system_tests/test_cases/test_redblack-periodic.manual.ref.c | naoyam/physis | 39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19 | [
"BSD-3-Clause"
] | 30 | 2015-01-27T02:45:34.000Z | 2022-02-17T03:50:49.000Z | tests/system_tests/test_cases/test_redblack-periodic.manual.ref.c | naoyam/physis | 39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19 | [
"BSD-3-Clause"
] | 8 | 2015-01-02T02:10:04.000Z | 2015-04-21T08:42:12.000Z | tests/system_tests/test_cases/test_redblack-periodic.manual.ref.c | naoyam/physis | 39ee5250a2d5baa545ca03e7c5c9aa9c81f1ab19 | [
"BSD-3-Clause"
] | 4 | 2015-12-16T10:18:31.000Z | 2021-12-28T22:43:56.000Z | #include <stdio.h>
#include <stdlib.h>
#define N 32
#define REAL float
#define OFFSET(x, y, z) ((x) + (y) * N + (z) * N * N)
void kernel(float *g, int rb) {
int x, y, z;
for (z = 0; z < N; ++z) {
int zp = ((z - 1) + N) % N;
int zn = (z + 1) % N;
for (y = 0; y < N; ++y) {
int yp = ((y - 1) + N) % N;
int yn = (y + 1) % N;
for (x = (y+z+rb)%2 ; x < N; x+=2) {
int xp = ((x - 1) + N) % N;
int xn = (x + 1) % N;
float v =
g[OFFSET(x, y, z)] +
g[OFFSET(xn, y, z)] +
g[OFFSET(xp, y, z)] +
g[OFFSET(x, yn, z)] +
g[OFFSET(x, yp, z)] +
g[OFFSET(x, y, zn)] +
g[OFFSET(x, y, zp)];
g[OFFSET(x, y, z)] = v;
}
}
}
return;
}
void dump(float *input) {
int i;
for (i = 0; i < N*N*N; ++i) {
printf("%f\n", input[i]);
}
}
int main(int argc, char *argv[]) {
REAL *g;
size_t nelms = N*N*N;
g = (REAL *)malloc(sizeof(REAL) * nelms);
int i;
for (i = 0; i < (int)nelms; i++) {
g[i] = i;
}
kernel(g, 0);
kernel(g, 1);
dump(g);
free(g);
return 0;
}
| 18.95 | 53 | 0.39226 |
e27b8fe92adb48bb4b6fb73d4f4b9b090ee8b464 | 136 | h | C | Using Structures/Using Structures/myStruct.h | shonwr/c-assignments-projects | fab40807ba2720cec577aa9689361746e33ef678 | [
"Apache-2.0"
] | null | null | null | Using Structures/Using Structures/myStruct.h | shonwr/c-assignments-projects | fab40807ba2720cec577aa9689361746e33ef678 | [
"Apache-2.0"
] | null | null | null | Using Structures/Using Structures/myStruct.h | shonwr/c-assignments-projects | fab40807ba2720cec577aa9689361746e33ef678 | [
"Apache-2.0"
] | null | null | null | //Included seperate header file for practice
struct Student{
char fName[25];
char lName[25];
float stuGrade[3];
float avgGrade;
};
| 17 | 45 | 0.727941 |
eb5b91a593ad2c5100dc94a2b3c3f43c8d02fec2 | 3,766 | h | C | BellaVista-ios/BellaVista/BellaVista/transpiled/com/sparseware/bellavista/CareTeam.h | sparseware/ccp-bellavista | c2689b44938ca93bacc64f9a1dcd8513aacc5983 | [
"Apache-2.0"
] | 6 | 2015-03-17T17:46:47.000Z | 2017-11-13T14:31:27.000Z | BellaVista-ios/BellaVista/BellaVista/transpiled/com/sparseware/bellavista/CareTeam.h | sparseware/ccp-bellavista | c2689b44938ca93bacc64f9a1dcd8513aacc5983 | [
"Apache-2.0"
] | 6 | 2016-03-02T23:36:57.000Z | 2016-03-07T23:08:23.000Z | BellaVista-ios/BellaVista/BellaVista/transpiled/com/sparseware/bellavista/CareTeam.h | sparseware/ccp-bellavista | c2689b44938ca93bacc64f9a1dcd8513aacc5983 | [
"Apache-2.0"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: com/sparseware/bellavista/CareTeam.java
//
// Created by decoteaud on 3/14/16.
//
#ifndef _CCPBVCareTeam_H_
#define _CCPBVCareTeam_H_
@class CCPBVaCommunicationHandler;
@class CCPBVaCommunicationHandler_UserStatus;
@class JavaUtilEventObject;
@class RAREListBoxViewer;
@class RARERenderableDataItem;
@class RAREUTJSONArray;
@class RAREWindowViewer;
@protocol JavaUtilMap;
@protocol RAREiFormViewer;
@protocol RAREiWidget;
#import "JreEmulation.h"
#include "com/appnativa/rare/iFunctionCallback.h"
#include "com/appnativa/rare/ui/iEventHandler.h"
#include "com/sparseware/bellavista/external/aCommunicationHandler.h"
@interface CCPBVCareTeam : NSObject < RAREiEventHandler, CCPBVaCommunicationHandler_iStatusListener > {
@public
CCPBVaCommunicationHandler *commHandler_;
id<JavaUtilMap> userStatuses_;
RAREListBoxViewer *listViewer_;
id<JavaUtilMap> statusIcons_;
int idPosition_;
long long int lastUpdateTime_;
int dataTimeout_;
}
+ (CCPBVaCommunicationHandler_UserStatus *)OFFLINE;
+ (void)setOFFLINE:(CCPBVaCommunicationHandler_UserStatus *)OFFLINE;
- (id)init;
- (void)onCreatedWithNSString:(NSString *)eventName
withRAREiWidget:(id<RAREiWidget>)widget
withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onDisposeWithNSString:(NSString *)eventName
withRAREiWidget:(id<RAREiWidget>)widget
withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onEventWithNSString:(NSString *)eventName
withRAREiWidget:(id<RAREiWidget>)widget
withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onListChangeWithNSString:(NSString *)eventName
withRAREiWidget:(id<RAREiWidget>)widget
withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onListShownWithNSString:(NSString *)eventName
withRAREiWidget:(id<RAREiWidget>)widget
withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)onShownWithNSString:(NSString *)eventName
withRAREiWidget:(id<RAREiWidget>)widget
withJavaUtilEventObject:(JavaUtilEventObject *)event;
- (void)serviceAvailbilityChangedWithCCPBVaCommunicationHandler:(CCPBVaCommunicationHandler *)handler;
- (void)statusChangedWithCCPBVaCommunicationHandler:(CCPBVaCommunicationHandler *)handler
withNSString:(NSString *)user
withCCPBVaCommunicationHandler_UserStatus:(CCPBVaCommunicationHandler_UserStatus *)status;
- (NSString *)getUserIDWithRARERenderableDataItem:(RARERenderableDataItem *)row;
- (void)updateFormWithRAREiFormViewer:(id<RAREiFormViewer>)fv
withRAREUTJSONArray:(RAREUTJSONArray *)items;
- (void)copyAllFieldsTo:(CCPBVCareTeam *)other;
@end
J2OBJC_FIELD_SETTER(CCPBVCareTeam, commHandler_, CCPBVaCommunicationHandler *)
J2OBJC_FIELD_SETTER(CCPBVCareTeam, userStatuses_, id<JavaUtilMap>)
J2OBJC_FIELD_SETTER(CCPBVCareTeam, listViewer_, RAREListBoxViewer *)
J2OBJC_FIELD_SETTER(CCPBVCareTeam, statusIcons_, id<JavaUtilMap>)
typedef CCPBVCareTeam ComSparsewareBellavistaCareTeam;
@interface CCPBVCareTeam_$1 : NSObject < RAREiFunctionCallback > {
@public
CCPBVCareTeam *this$0_;
RAREWindowViewer *val$w_;
id<RAREiWidget> val$widget_;
}
- (void)finishedWithBoolean:(BOOL)canceled
withId:(id)returnValue;
- (id)initWithCCPBVCareTeam:(CCPBVCareTeam *)outer$
withRAREWindowViewer:(RAREWindowViewer *)capture$0
withRAREiWidget:(id<RAREiWidget>)capture$1;
@end
J2OBJC_FIELD_SETTER(CCPBVCareTeam_$1, this$0_, CCPBVCareTeam *)
J2OBJC_FIELD_SETTER(CCPBVCareTeam_$1, val$w_, RAREWindowViewer *)
J2OBJC_FIELD_SETTER(CCPBVCareTeam_$1, val$widget_, id<RAREiWidget>)
#endif // _CCPBVCareTeam_H_
| 39.642105 | 103 | 0.779076 |
b9ebbdda7cdd17470ff42bdd0ae20df009b663cc | 515 | h | C | Templates/ZIKRouter.xctemplate/ZIKViewRoutermodule inputObjective-C/___VARIABLE_moduleProtocolName___.h | faimin/ZIKRouter | bfb9b328c00c3348194064dfee4c3e2396d9b6db | [
"MIT"
] | 611 | 2017-08-08T05:27:10.000Z | 2022-03-31T14:33:40.000Z | Templates/ZIKRouter.xctemplate/ZIKViewRoutermodule inputObjective-C/___VARIABLE_moduleProtocolName___.h | faimin/ZIKRouter | bfb9b328c00c3348194064dfee4c3e2396d9b6db | [
"MIT"
] | 32 | 2018-05-16T07:54:25.000Z | 2022-03-30T05:40:59.000Z | Templates/ZIKRouter.xctemplate/ZIKViewRoutermodule inputObjective-C/___VARIABLE_moduleProtocolName___.h | faimin/ZIKRouter | bfb9b328c00c3348194064dfee4c3e2396d9b6db | [
"MIT"
] | 116 | 2017-08-23T04:24:10.000Z | 2022-03-16T02:53:20.000Z | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
#import <ZIKRouter/ZIKViewModuleRoutable.h>
NS_ASSUME_NONNULL_BEGIN
@protocol ___VARIABLE_protocolName___;
#error TODO: replace /*arguments*/ with type of module config parameters
@protocol ___VARIABLE_moduleProtocolName___ <ZIKViewModuleRoutable>
@property (nonatomic, copy, readonly) id<___VARIABLE_protocolName___> _Nullable(^makeDestinationWith)(/*arguments*/);
@end
NS_ASSUME_NONNULL_END
| 24.52381 | 117 | 0.81165 |
ac9ccaee7477fa14df9940c012f72b15ff229312 | 370 | h | C | Estruturas de dados/studys/hash.h | RodriguesAlonso/UNIVESP | c80c408f52136672ee4eea31fbfeedd8bca9abfb | [
"MIT"
] | null | null | null | Estruturas de dados/studys/hash.h | RodriguesAlonso/UNIVESP | c80c408f52136672ee4eea31fbfeedd8bca9abfb | [
"MIT"
] | null | null | null | Estruturas de dados/studys/hash.h | RodriguesAlonso/UNIVESP | c80c408f52136672ee4eea31fbfeedd8bca9abfb | [
"MIT"
] | null | null | null | #include "aluno.h"
class Hash{
private:
Aluno* structure;
int max_item;
int length;
int getHash(Aluno aluno);
public:
Hash(int maxItem = 100);
~Hash();
void retriveItem(Aluno& aluno,bool& found);
void insertItem(Aluno aluno);
void deleteItem(Aluno aluno);
void print();
bool isFull();
int getLength();
}; | 16.086957 | 47 | 0.602703 |
557609ad8b542d417d743bea560f62014549c157 | 26,941 | c | C | demo/13_EG4S20withM0/M0/IPCore/AT510-MN-80001-r2p0-00rel0/software/common/validation/timer_tests.c | verimake-team/SparkRoad-V | 5c02eb65c551c1389878389c9b9682fff96e43ec | [
"MIT"
] | 23 | 2019-08-15T11:58:13.000Z | 2022-03-27T02:45:38.000Z | demo/13_EG4S20withM0/M0/IPCore/AT510-MN-80001-r2p0-00rel0/software/common/validation/timer_tests.c | crazyalpha/SparkRoad-V | 5c02eb65c551c1389878389c9b9682fff96e43ec | [
"MIT"
] | 2 | 2019-10-16T05:12:30.000Z | 2020-08-13T07:17:02.000Z | demo/13_EG4S20withM0/M0/IPCore/AT510-MN-80001-r2p0-00rel0/software/common/validation/timer_tests.c | crazyalpha/SparkRoad-V | 5c02eb65c551c1389878389c9b9682fff96e43ec | [
"MIT"
] | 28 | 2019-08-15T11:15:35.000Z | 2022-03-17T01:42:27.000Z | /*
*-----------------------------------------------------------------------------
* The confidential and proprietary information contained in this file may
* only be used by a person authorised under and to the extent permitted
* by a subsisting licensing agreement from ARM Limited or its affiliates.
*
* (C) COPYRIGHT 2010-2013 ARM Limited or its affiliates.
* ALL RIGHTS RESERVED
*
* This entire notice must be reproduced on all copies of this file
* and copies of this file may only be made by a person if such person is
* permitted to do so under the terms of a subsisting license agreement
* from ARM Limited or its affiliates.
*
* SVN Information
*
* Checked In : $Date: 2017-07-25 15:10:13 +0100 (Tue, 25 Jul 2017) $
*
* Revision : $Revision: 368444 $
*
* Release Information : Cortex-M0 DesignStart-r2p0-00rel0
*-----------------------------------------------------------------------------
*/
/*
A simple test to check the functionalities of APB timer
*/
#include "CMSDK_CM0.h"
#include <stdio.h>
#include "uart_stdout.h"
int timer_register_rw_test(CMSDK_TIMER_TypeDef *CMSDK_TIMER);
int timer_start_stop_test(CMSDK_TIMER_TypeDef *CMSDK_TIMER);
int timer_interrupt_test_1(CMSDK_TIMER_TypeDef *CMSDK_TIMER);
int timer_external_input(CMSDK_TIMER_TypeDef *CMSDK_TIMER);
int timer0_id_check(void); // Detect Timer 0 present
int timer1_id_check(void); // Detect Timer 1 present
int gpio1_id_check(void); // Detect GPIO 1 present
/* Global variables */
volatile int timer0_irq_occurred;
volatile int timer1_irq_occurred;
volatile int timer0_irq_expected;
volatile int timer1_irq_expected;
volatile int counter;
/* peripheral and component ID values */
#define APB_TIMER_PID4 0x04
#define APB_TIMER_PID5 0x00
#define APB_TIMER_PID6 0x00
#define APB_TIMER_PID7 0x00
#define APB_TIMER_PID0 0x22
#define APB_TIMER_PID1 0xB8
#define APB_TIMER_PID2 0x1B
#define APB_TIMER_PID3 0x00
#define APB_TIMER_CID0 0x0D
#define APB_TIMER_CID1 0xF0
#define APB_TIMER_CID2 0x05
#define APB_TIMER_CID3 0xB1
#define HW32_REG(ADDRESS) (*((volatile unsigned long *)(ADDRESS)))
#define HW8_REG(ADDRESS) (*((volatile unsigned char *)(ADDRESS)))
int main (void)
{
int result=0;
// UART init
UartStdOutInit();
// Test banner message and revision number
puts("\nCortex Microcontroller System Design Kit - Timer Test - revision $Revision: 368444 $\n");
timer0_irq_occurred = 0;
timer1_irq_occurred = 0;
timer0_irq_expected = 0;
timer1_irq_expected = 0;
puts("1) Timer 0");
if (timer0_id_check()==0) { /* Detect if timer is available */
/* Timer 0 present */
result += timer_register_rw_test(CMSDK_TIMER0);
result += timer_start_stop_test(CMSDK_TIMER0);
result += timer_interrupt_test_1(CMSDK_TIMER0);
if (gpio1_id_check()==0) {
/* External input test need GPIO 1 to generate input */
result += timer_external_input(CMSDK_TIMER0);
} else {
puts ("- GPIO #1 not present. Test skipped.");
}
} else {
puts ("- Timer #0 not present. Tests skipped.");
}
puts("\n2) Timer 1");
if (timer1_id_check()==0) { /* Detect if timer is available */
/* Timer 1 present */
result += timer_register_rw_test(CMSDK_TIMER1);
result += timer_start_stop_test(CMSDK_TIMER1);
result += timer_interrupt_test_1(CMSDK_TIMER1);
if (gpio1_id_check()==0) {
/* External input test need GPIO 1 to generate input */
result += timer_external_input(CMSDK_TIMER1);
} else {
puts ("- GPIO #1 not present. Test skipped.");
}
} else {
puts ("- Timer #1 not present. Tests skipped.");
}
if (result==0) {
printf ("\n** TEST PASSED **\n");
} else {
printf ("\n** TEST FAILED **\n, Error code = (0x%x)", result);
}
UartEndSimulation();
return 0;
}
/* --------------------------------------------------------------- */
/* Timer register read/write tests */
/* --------------------------------------------------------------- */
int timer_register_rw_test(CMSDK_TIMER_TypeDef *CMSDK_TIMER){
int return_val=0;
int err_code=0;
unsigned int timer_base;
puts("Timer R/W test");
puts("- initial values");
NVIC_DisableIRQ(TIMER0_IRQn);
NVIC_DisableIRQ(TIMER1_IRQn);
if (CMSDK_TIMER->CTRL != 0) { err_code += (1<<0); }
if (CMSDK_TIMER->VALUE != 0) { err_code += (1<<1); }
if (CMSDK_TIMER->RELOAD != 0) { err_code += (1<<2); }
if (CMSDK_TIMER->INTSTATUS != 0) { err_code += (1<<3); }
timer_base = CMSDK_TIMER0_BASE;
if (CMSDK_TIMER==CMSDK_TIMER1) {timer_base = CMSDK_TIMER1_BASE;}
// Perform a write access to all PIDs
HW32_REG(timer_base + 0xFD0) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFD4) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFD8) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFDC) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFE0) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFE4) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFE8) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFEC) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFF0) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFF4) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFF8) = 0xFFFFFFFF;
HW32_REG(timer_base + 0xFFC) = 0xFFFFFFFF;
if (HW32_REG(timer_base + 0xFD0) != APB_TIMER_PID4) {err_code += (1<<4); }
if (HW32_REG(timer_base + 0xFD4) != APB_TIMER_PID5) {err_code += (1<<5); }
if (HW32_REG(timer_base + 0xFD8) != APB_TIMER_PID6) {err_code += (1<<6); }
if (HW32_REG(timer_base + 0xFDC) != APB_TIMER_PID7) {err_code += (1<<7); }
if (HW32_REG(timer_base + 0xFE0) != APB_TIMER_PID0) {err_code += (1<<8); }
if (HW32_REG(timer_base + 0xFE4) != APB_TIMER_PID1) {err_code += (1<<9); }
if (HW32_REG(timer_base + 0xFE8) != APB_TIMER_PID2) {err_code += (1<<10); }
if (HW32_REG(timer_base + 0xFEC) != APB_TIMER_PID3) {err_code += (1<<11); }
if (HW32_REG(timer_base + 0xFF0) != APB_TIMER_CID0) {err_code += (1<<12); }
if (HW32_REG(timer_base + 0xFF4) != APB_TIMER_CID1) {err_code += (1<<13); }
if (HW32_REG(timer_base + 0xFF8) != APB_TIMER_CID2) {err_code += (1<<14); }
if (HW32_REG(timer_base + 0xFFC) != APB_TIMER_CID3) {err_code += (1<<15); }
if (err_code != 0) {
printf ("ERROR : initial value failed (0x%x)\n", err_code);
return_val=1;
err_code = 0;
}
puts("- read/write");
CMSDK_TIMER->VALUE = 0x3355AAFF;
if (CMSDK_TIMER->VALUE != 0x3355AAFF) { err_code += (1<<0); }
CMSDK_TIMER->VALUE = 0xCCAA5500;
if (CMSDK_TIMER->VALUE != 0xCCAA5500) { err_code += (1<<1); }
CMSDK_TIMER->VALUE = 0x00000000;
if (CMSDK_TIMER->VALUE != 0x00000000) { err_code += (1<<2); }
CMSDK_TIMER->RELOAD = 0x3355AAFF;
if (CMSDK_TIMER->RELOAD != 0x3355AAFF) { err_code += (1<<3); }
CMSDK_TIMER->RELOAD = 0xCCAA5500;
if (CMSDK_TIMER->RELOAD != 0xCCAA5500) { err_code += (1<<4); }
CMSDK_TIMER->RELOAD = 0x00000000;
if (CMSDK_TIMER->RELOAD != 0x00000000) { err_code += (1<<5); }
CMSDK_TIMER->CTRL = 0x01; /* Set enable */
if (CMSDK_TIMER->CTRL != 0x01) { err_code += (1<<6); }
CMSDK_TIMER->CTRL = 0x02; /* external select */
if (CMSDK_TIMER->CTRL != 0x02) { err_code += (1<<7); }
CMSDK_TIMER->CTRL = 0x04; /* external clock select */
if (CMSDK_TIMER->CTRL != 0x04) { err_code += (1<<8); }
CMSDK_TIMER->CTRL = 0x08; /* external clock select */
if (CMSDK_TIMER->CTRL != 0x08) { err_code += (1<<9); }
CMSDK_TIMER->CTRL = 0x00; /* all clear */
if (CMSDK_TIMER->CTRL != 0x00) { err_code += (1<<10); }
/* Trigger timer interrupt status */
CMSDK_TIMER->RELOAD = 0x3;
CMSDK_TIMER->VALUE = 0x3;
CMSDK_TIMER->CTRL = 0x9; /* enable with internal clock as source */
while ( CMSDK_TIMER->INTSTATUS == 0);
CMSDK_TIMER->CTRL = 0x0; /* disable timer */
if (CMSDK_TIMER->INTSTATUS != 0x01) { err_code += (1<<11); }
CMSDK_TIMER->INTCLEAR = 0x1; /* clear timer interrupt */
if (CMSDK_TIMER->INTSTATUS != 0x00) { err_code += (1<<12); }
/* Generate return value */
if (err_code != 0) {
printf ("ERROR : Read/write failed (0x%x)\n", err_code);
return_val=1;
err_code = 0;
}
NVIC_ClearPendingIRQ(TIMER0_IRQn);
NVIC_ClearPendingIRQ(TIMER1_IRQn);
return(return_val);
}
/* --------------------------------------------------------------- */
/* Timer start/stop tests */
/* --------------------------------------------------------------- */
/*
Timer value set to 0x1000, and enabled.
A polling loop is then use to check that timer had decremented to 0x900
within a certain period of time. A software variable called counter to
used to detect timeout, which make sure that the test report fail
if the timer does not decrement.
The timer is then stopped, and the value is sampled twice and checked
that the timer is really stopped.
The timer value is then set to 0x10, and then enabled, with interrupt feature
enabled (Note : NVIC is not enabled for this test so interrupt doesn't get
triggered).
A polling loop is then use to wait until timer reach zero and reloaded
(by checking interrupt status register). The current value of the timer
is then checked to make sure it is in the expected value range.
*/
int timer_start_stop_test(CMSDK_TIMER_TypeDef *CMSDK_TIMER){
int return_val=0;
int err_code=0;
unsigned long tvalue;
puts("Timer start/stop test");
puts("- timer enable");
NVIC_DisableIRQ(TIMER0_IRQn);
NVIC_DisableIRQ(TIMER1_IRQn);
CMSDK_TIMER->RELOAD = 0x1000;
CMSDK_TIMER->VALUE = 0x1000;
CMSDK_TIMER->CTRL = 0x01; /* Set enable */
counter = 0x100; /* Time out counter */
while ((CMSDK_TIMER->VALUE > 0x900) && (counter>= 0)){
counter --;
}
CMSDK_TIMER->CTRL = 0x00; /* stop timer for now */
if (CMSDK_TIMER->VALUE > 0x900) {
puts("ERROR : Timer not decrementing.");
err_code += (1<<0);
}
tvalue = CMSDK_TIMER->VALUE;
puts("- timer disable");
__NOP();
__NOP();
if (CMSDK_TIMER->VALUE != tvalue) {
puts("ERROR : Timer not stopping.");
err_code += (1<<1);
}
/* Check reload operation */
puts("- timer reload");
CMSDK_TIMER->VALUE = 0x10;
CMSDK_TIMER->CTRL = 0x09; /* Set enable, and interrupt generation */
while ( CMSDK_TIMER->INTSTATUS == 0);
CMSDK_TIMER->CTRL = 0x00; /* Stop timer */
if (CMSDK_TIMER->VALUE > CMSDK_TIMER->RELOAD) {
puts("ERROR : Timer reload fail 1.");
err_code += (1<<2);
}
if ( (CMSDK_TIMER->RELOAD - CMSDK_TIMER->VALUE) > 0x100 ) {
puts("ERROR : Timer reload fail 2.");
err_code += (1<<3);
}
// Need to lower the interrupt in the timer before clearing in the NVIC
CMSDK_TIMER->INTCLEAR = 1;
// Clear the NVIC interrupts related to both timers to save working out which
// timer is currently being tested
NVIC_ClearPendingIRQ(TIMER0_IRQn);
NVIC_ClearPendingIRQ(TIMER1_IRQn);
/* Generate return value */
if (err_code != 0) {
printf ("ERROR : start/stop failed (0x%x)\n", err_code);
return_val=1;
err_code = 0;
}
return(return_val);
}
/* --------------------------------------------------------------- */
/* Timer interrupt test 1 */
/* --------------------------------------------------------------- */
/*
Interrupt enable:
Timer is enabled, with reload value set to 0x7F (128 cycles),
and timer interrupt is enabled.
check that timer interrupt has take place as least twice
when counter (software variable) is increased from 0 to 0x300.
If counter is > 0x300 but less than two timer interrupt is received
(timerx_irq_occurred < 2), then flag it as time out error.
Interrupt disable:
Timer is enabled, with reload value set to 0x1F (32 cycles),
and timer interrupt is disabled.
The counter (software variable) is increased from 0 to 0x100.
Check that timer interrupt did not take place.
(timer0_irq_occurred and timer1_irq_occurred are 0).
*/
int timer_interrupt_test_1(CMSDK_TIMER_TypeDef *CMSDK_TIMER){
int return_val=0;
int err_code=0;
puts ("Timer interrupt test");
puts ("- Test interrupt generation enabled.");
CMSDK_TIMER->VALUE = 0; /* Disable timer */
NVIC_DisableIRQ(TIMER0_IRQn);
NVIC_DisableIRQ(TIMER1_IRQn);
NVIC_ClearPendingIRQ(TIMER0_IRQn);
NVIC_ClearPendingIRQ(TIMER1_IRQn);
/* Check which timer is being tested and setup software flags */
if (CMSDK_TIMER==CMSDK_TIMER0) {
timer0_irq_expected = 1;
timer1_irq_expected = 0;
timer0_irq_occurred = 0;
timer1_irq_occurred = 0;
NVIC_EnableIRQ(TIMER0_IRQn); /* Enable Timer Interrupt */
}
if (CMSDK_TIMER==CMSDK_TIMER1) {
timer0_irq_expected = 0;
timer1_irq_expected = 1;
timer0_irq_occurred = 0;
timer1_irq_occurred = 0;
NVIC_EnableIRQ(TIMER1_IRQn); /* Enable Timer Interrupt */
}
CMSDK_TIMER->RELOAD = 0x01FF;
CMSDK_TIMER->VALUE = 0x01FF;
CMSDK_TIMER->CTRL = 0x0009; /* Timer enabled */
counter = 0;
if (CMSDK_TIMER==CMSDK_TIMER0) {
while (( timer0_irq_occurred < 2) && (counter < 0x300)){
counter ++;
};
CMSDK_TIMER->CTRL = 0x0000; /* Stop Timer */
}
if (CMSDK_TIMER==CMSDK_TIMER1) {
while (( timer1_irq_occurred < 2) && (counter < 0x300)){
counter ++;
};
CMSDK_TIMER->CTRL = 0x0000; /* Stop Timer */
}
/* Check timeout has not occurred */
if (counter >= 0x300) {
puts("ERROR : Timer interrupt enable fail.");
err_code += (1<<0);
}
counter = 0;
puts ("- Test interrupt generation disabled.");
timer0_irq_expected = 0;
timer1_irq_expected = 0;
timer0_irq_occurred = 0;
timer1_irq_occurred = 0;
CMSDK_TIMER->RELOAD = 0x001F;
CMSDK_TIMER->VALUE = 0x001F;
CMSDK_TIMER->CTRL = 0x0001; /* Timer enabled, with interrupt generation disabled */
counter = 0;
while ((counter<0x100) && (timer0_irq_occurred==0) && (timer1_irq_occurred==0)) {
counter++;
}
CMSDK_TIMER->CTRL = 0x0000; /* Stop Timer */
if ((timer0_irq_occurred!=0) || (timer1_irq_occurred!=0)) {
puts("ERROR : Timer interrupt disable fail.");
err_code += (1<<1);
}
counter = 0;
NVIC_DisableIRQ(TIMER0_IRQn);
NVIC_DisableIRQ(TIMER1_IRQn);
/* Generate return value */
if (err_code != 0) {
printf ("ERROR : Interrupt test failed (0x%x)\n", err_code);
return_val=1;
err_code = 0;
}
return(return_val);
}
/* --------------------------------------------------------------- */
/* Timer extin test 1 */
/* --------------------------------------------------------------- */
/* External input :
TIMER 0 - GPIO #1 [bit 8]
TIMER 1 - GPIO #1 [bit 9]
Checking of external input as enable:
Timer is programmed so that it use external input as enable.
The external input is set to 0 (disabled), and the timer value is sample twice
to make sure it is not decrementing.
The program then set the timer current value to 99, and then use the
SysTick timer to generate a pulse of 100 cycles on the timer
external input. This is done by
- setting up the SysTick to be triggered at every 100 cycles,
- the first timer SysTick interrupt is triggered, set ext input to 1
- the second timer SysTick interrupt is triggered, set ext input to 0, and disable SysTick
After the SysTick exception is entered twice, it then check if the timer has underflowed.
(check current value range between 0xFF to 0xA0).
Since the timer could be running at a divided APB clock speed which is half of the AHB,
the value check might fail in such configuration. If the current counter value is between
30 and 60, generate another pulse of 100 clocks cycle to the external input and do the
check again.
It then check the timer interrupt status, and the clearing of the interrupt status.
------------------------------------
Checking of external input as clock:
The test then program the timer to use external input as "clock" (rising edge detection).
Timer starting value is set to 0xC0.
It first keep the external input as 0, and check that the timer current value hasn't been
changed.
It then change the external input to 1, and check if the timer has decrement. (value = 0xBF)
It then wait for a short period (counter variable decrement from 10 to 0),
then check that the timer has not been decremented further.(value = 0xBF)
It then set external input to 0, again, wait for short period of time,
and check that the timer has not been decremented further.(value = 0xBF)
It then generate 15 pulses on the external input, and check the timer has decrement
15 times. (value = 0xB0) It also check that at this stage the timer interrupt status
should still be 0.
It then set the timer value to 2, with interrupt generation enabled, use external input
as clock. The external input is then switched from 0 to 1, (value changed from 2 to 1)
and the timer interrupt shouldn't be triggered. (it should only trigger at 1 to 0 value
change).
It then generate another pulse at the external input, and wait for a short period.
This time the timer interrupt should be triggered.
it then clear up the interrupt settings and report test status.
*/
int timer_external_input(CMSDK_TIMER_TypeDef *CMSDK_TIMER){
int return_val=0;
int err_code=0;
unsigned long tvalue;
uint32_t timer_value;
puts ("Timer external input test");
/* Set external inputs low */
CMSDK_GPIO1->OUTENABLESET = (1<<8) | (1<<9);
CMSDK_GPIO1->UB_MASKED[3] = 0x0000;
CMSDK_TIMER->RELOAD = 0x00FF;
CMSDK_TIMER->VALUE = 0x00FF;
CMSDK_TIMER->CTRL = 0x000B; /* Timer enabled, use external input, interrupt enabled */
tvalue = CMSDK_TIMER->VALUE;
puts("- timer use ext. input");
__NOP(); /* Some delay is needed due to double flip-flop synchronization logic */
__NOP();
if (CMSDK_TIMER->VALUE != tvalue) {
puts("ERROR : Timer not stopping when external input is low.");
err_code += (1<<0);
}
puts("- use SysTick to generate ext. input pulse");
CMSDK_TIMER->VALUE = 0xFE; /* Use 0xFE so that it count to 0 */
counter = 0;
NVIC_DisableIRQ(TIMER0_IRQn);
NVIC_DisableIRQ(TIMER1_IRQn);
NVIC_ClearPendingIRQ(TIMER0_IRQn);
NVIC_ClearPendingIRQ(TIMER1_IRQn);
/* Create a pulse of approximately four times the length of the expected
* duration that the system timer will be counting down.
* APB is possibly running at half speed, but this should be allowed for by
* the fact that the SysTick reload value is set to a larger value than the
* system timer start value. This therefore should allow the system timer to
* count round multiple times, and should have the expected outcome
* regardless of whether APB is running at full speed or half speed
*/
SysTick->LOAD = (0x100<<2)-1;
SysTick->VAL = 0;
SysTick->CTRL = 0x7; /* Enable, use internal clock, interrupt enable */
while (counter < 2); /* SysTick handler trigger twice */
/* Timer should be reloaded, expected value between 0xA0 to 0xFF (reload value) */
timer_value = CMSDK_TIMER->VALUE;
if ((timer_value > 0xFF) || (timer_value < 0xA0)) {
printf("ERROR : Timer not running when external input is high (0x%x).\n", timer_value);
err_code += (1<<1);
}
/* Timer interrupt should be pending */
if (((NVIC_GetPendingIRQ(TIMER0_IRQn)==0)&&(CMSDK_TIMER==CMSDK_TIMER0))||
((NVIC_GetPendingIRQ(TIMER1_IRQn)==0)&&(CMSDK_TIMER==CMSDK_TIMER1)))
{
puts("ERROR : Timer not trigger #1.");
err_code += (1<<2);
}
if (CMSDK_TIMER->INTSTATUS==0) {
puts("ERROR : Timer not trigger #2.");
err_code += (1<<3);
}
else {
CMSDK_TIMER->INTCLEAR=1; /* Clear interrupt status */
if (CMSDK_TIMER->INTSTATUS!=0) {
puts("ERROR : Timer not clear.");
err_code += (1<<4);
}
}
NVIC_ClearPendingIRQ(TIMER0_IRQn);
NVIC_ClearPendingIRQ(TIMER1_IRQn);
puts("- use EXTIN as clock");
CMSDK_TIMER->VALUE = 0xC0;
CMSDK_TIMER->CTRL = 0x0007; /* Timer enabled, use external input as clock, interrupt disabled */
CMSDK_GPIO1->UB_MASKED[3] = 0x0000;
counter = 10; /* delay */
while (counter > 0) {
counter --;
}
if (CMSDK_TIMER->VALUE != 0xC0) {
puts("ERROR : Timer change unexpectedly 1.");
err_code += (1<<5);
}
CMSDK_GPIO1->UB_MASKED[3] = 0x0300; /* Timer should decrement */
__ISB();
__ISB();
if (CMSDK_TIMER->VALUE != 0xBF) {
puts("ERROR : Timer decrement failed.");
err_code += (1<<6);
}
counter = 10; /* delay */
while (counter > 0) {
counter --;
}
if (CMSDK_TIMER->VALUE != 0xBF) {
puts("ERROR : Timer change unexpectedly 2.");
err_code += (1<<7);
}
CMSDK_GPIO1->UB_MASKED[3] = 0x0000; /* Timer should NOT decrement */
counter = 10; /* delay */
while (counter > 0) {
counter --;
}
if (CMSDK_TIMER->VALUE != 0xBF) {
puts("ERROR : Timer change unexpectedly 3.");
err_code += (1<<8);
}
counter = 15;
while (counter > 0) {
CMSDK_GPIO1->UB_MASKED[3] = 0x0300; /* Timer should decrement */
__ISB();
CMSDK_GPIO1->UB_MASKED[3] = 0x0000; /* Timer should not decrement */
counter --;
}
if (CMSDK_TIMER->VALUE != 0xB0) {
puts("ERROR : Timer counting failed");
err_code += (1<<9);
}
/* Check interrupt should not be trigger */
if ((NVIC_GetPendingIRQ(TIMER0_IRQn)!=0)||(NVIC_GetPendingIRQ(TIMER1_IRQn)!=0)||
(CMSDK_TIMER->INTSTATUS!=0))
{
puts("ERROR : Timer IRQ set unexpectedly.");
err_code += (1<<10);
}
puts("- IRQ at 1->0 transition");
CMSDK_TIMER->VALUE = 0x02;
CMSDK_TIMER->CTRL = 0x000F; /* Timer enabled, use external input as clock, interrupt enabled */
CMSDK_GPIO1->UB_MASKED[3] = 0x0000;
timer0_irq_expected = 0;
timer1_irq_expected = 0;
timer0_irq_occurred = 0;
timer1_irq_occurred = 0;
if (CMSDK_TIMER==CMSDK_TIMER0) {
NVIC_EnableIRQ(TIMER0_IRQn);
}
if (CMSDK_TIMER==CMSDK_TIMER1) {
NVIC_EnableIRQ(TIMER1_IRQn);
}
/* Test no IRQ generation for 2 to 1 transition */
CMSDK_GPIO1->UB_MASKED[3] = 0x0300; /* Timer should decrement */
__ISB();
CMSDK_GPIO1->UB_MASKED[3] = 0x0000; /* Timer should not decrement */
counter = 10; /* delay */
while (counter > 0) {
counter --;
}
if (CMSDK_TIMER==CMSDK_TIMER0) {
timer0_irq_expected=1;
}
if (CMSDK_TIMER==CMSDK_TIMER1) {
timer1_irq_expected=1;
}
/* Test IRQ generation for 1 to 0 transition */
CMSDK_GPIO1->UB_MASKED[3] = 0x0300; /* Timer should decrement */
__ISB();
CMSDK_GPIO1->UB_MASKED[3] = 0x0000; /* Timer should not decrement */
counter = 10; /* delay */
while (counter > 0) {
counter --;
}
if (((CMSDK_TIMER==CMSDK_TIMER0)&&(timer0_irq_occurred==0))||
((CMSDK_TIMER==CMSDK_TIMER1)&&(timer1_irq_occurred==0))) {
puts("ERROR : Timer not trigger.");
err_code += (1<<11);
}
timer0_irq_expected = 0;
timer1_irq_expected = 0;
timer0_irq_occurred = 0;
timer1_irq_occurred = 0;
/* Test IRQ generation for 0 to RELOAD transition */
CMSDK_GPIO1->UB_MASKED[3] = 0x0300; /* Timer should decrement */
__ISB();
CMSDK_GPIO1->UB_MASKED[3] = 0x0000; /* Timer should not decrement */
counter = 10; /* delay */
while (counter > 0) {
counter --;
}
if ((timer0_irq_occurred!=0)||(timer1_irq_occurred!=0)) {
puts("ERROR : Timer triggered unexpectedly.");
err_code += (1<<12);
}
NVIC_DisableIRQ(TIMER0_IRQn);
NVIC_DisableIRQ(TIMER1_IRQn);
NVIC_ClearPendingIRQ(TIMER0_IRQn);
NVIC_ClearPendingIRQ(TIMER1_IRQn);
/* Clearing up */
SysTick->CTRL = 0x0;
CMSDK_TIMER->CTRL = 0x00;/* Disable, use internal clock, interrupt enable */
CMSDK_TIMER->RELOAD = 0x0000;
CMSDK_TIMER->VALUE = 0x0000;
CMSDK_GPIO1->OUTENABLECLR = 0xFFFF;
CMSDK_GPIO1->UB_MASKED[3] = 0x0000;
timer0_irq_expected = 0;
timer1_irq_expected = 0;
timer0_irq_occurred = 0;
timer1_irq_occurred = 0;
/* Generate return value */
if (err_code != 0) {
printf ("ERROR : Interrupt test failed (0x%x)\n", err_code);
return_val=1;
err_code = 0;
}
return(return_val);
}
/* --------------------------------------------------------------- */
/* Peripheral detection */
/* --------------------------------------------------------------- */
/* Detect the part number to see if device is present */
int timer0_id_check(void)
{
unsigned char timer_id;
timer_id = HW8_REG(CMSDK_TIMER0_BASE + 0xFE8) & 0x07;
if ((HW32_REG(CMSDK_TIMER0_BASE + 0xFE0) != 0x22) ||
(HW32_REG(CMSDK_TIMER0_BASE + 0xFE4) != 0xB8) ||
(timer_id != 0x03))
return 1; /* part ID & ARM ID does not match */
else
return 0;
}
int timer1_id_check(void)
{
unsigned char timer_id;
timer_id = HW8_REG(CMSDK_TIMER1_BASE + 0xFE8) & 0x07;
if ((HW32_REG(CMSDK_TIMER1_BASE + 0xFE0) != 0x22) ||
(HW32_REG(CMSDK_TIMER1_BASE + 0xFE4) != 0xB8) ||
(timer_id != 0x03))
return 1; /* part ID & ARM ID does not match */
else
return 0;
}
int gpio1_id_check(void)
{
unsigned char gpio_id;
gpio_id = HW8_REG(CMSDK_GPIO1_BASE + 0xFE8) & 0x07;
if ((HW32_REG(CMSDK_GPIO1_BASE + 0xFE0) != 0x20) ||
(HW32_REG(CMSDK_GPIO1_BASE + 0xFE4) != 0xB8) ||
(gpio_id != 0x03))
return 1; /* part ID & ARM ID does not match */
else
return 0;
}
/* --------------------------------------------------------------- */
/* Timer exception handlers */
/* --------------------------------------------------------------- */
void TIMER0_Handler(void)
{
timer0_irq_occurred ++;
CMSDK_TIMER0->INTCLEAR = 1;
if (timer0_irq_expected ==0) {
puts ("ERROR : Unexpected Timer 0 interrupt occurred.\n");
UartEndSimulation();
while (1);
}
return;
}
void TIMER1_Handler(void)
{
timer1_irq_occurred ++;
CMSDK_TIMER1->INTCLEAR = 1;
if (timer1_irq_expected ==0) {
puts ("ERROR : Unexpected Timer 1 interrupt occurred.\n");
UartEndSimulation();
while (1);
}
return;
}
/* --------------------------------------------------------------- */
/* SysTick exception handlers */
/* --------------------------------------------------------------- */
void SysTick_Handler(void)
{
switch (counter) {
case 0 :
/* Assert the EXTIN to the system timer */
CMSDK_GPIO1->UB_MASKED[3] = 0x0300;
counter ++;
break;
case 1 :
CMSDK_GPIO1->UB_MASKED[3] = 0x0000;
SysTick->CTRL = 0;
SCB->ICSR = SCB->ICSR & 0xFDFFFFFF; /* Clear SysTick pending bit */
counter ++;
break;
default:
SysTick->CTRL = 0;
SCB->ICSR = SCB->ICSR & 0xFDFFFFFF; /* Clear SysTick pending bit */
break;
}
return;
}
| 33.260494 | 101 | 0.626814 |
55fc46b4ae18ecaead0ff5a5c90ee1b449241e6d | 2,288 | h | C | SigMeshOC/SigMeshOC/sig_mesh_lib/SIG_MESH_header_file/ble_lt_mesh/proj/simu/socket_api.h | flyskywhy/react-native-btsig-telink | 4bd87bbaef61371c82b8738d42c2d06755eca1db | [
"MIT"
] | 2 | 2020-10-06T09:48:53.000Z | 2021-09-17T05:37:57.000Z | android/src/main/cpp/header/ble_lt_mesh/proj/simu/socket_api.h | flyskywhy/react-native-btsig-telink | 4bd87bbaef61371c82b8738d42c2d06755eca1db | [
"MIT"
] | 2 | 2020-10-13T10:27:41.000Z | 2020-11-15T01:06:29.000Z | android/src/main/cpp/header/ble_lt_mesh/proj/simu/socket_api.h | flyskywhy/react-native-btsig-telink | 4bd87bbaef61371c82b8738d42c2d06755eca1db | [
"MIT"
] | null | null | null | /********************************************************************************************************
* @file socket_api.h
*
* @brief for TLSR chips
*
* @author telink
* @date Sep. 30, 2010
*
* @par Copyright (c) 2010, Telink Semiconductor (Shanghai) Co., Ltd.
* All rights reserved.
*
* The information contained herein is confidential and proprietary property of Telink
* Semiconductor (Shanghai) Co., Ltd. and is available under the terms
* of Commercial License Agreement between Telink Semiconductor (Shanghai)
* Co., Ltd. and the licensee in separate contract or the terms described here-in.
* This heading MUST NOT be removed from this file.
*
* Licensees are granted free, non-transferable use of the information in this
* file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
*
*******************************************************************************************************/
#pragma once
#ifdef WIN32
#include "../common/types.h"
typedef int (*handle_recv_data)(void *data, int len);
#define RECEIVE_MAX_LENGTH 128
#define SEND_MAX_LENGTH 128
#define SOCKET_HOST "127.0.0.1"
#define SOCKET_PORT_SERVER 7001
#define SOCKET_PORT_CLIENT 7002
enum {
SIMU_SOCKET = 0,
TEST_SOCKET,
WIRESHARK_SOCKET,
};
extern handle_recv_data handle_received_serial_data;
extern handle_recv_data handle_received_rf_data;
void socket_param_init(u8 type);
int node_send_to_rf(u8 *buf, u8 len);
int node_send_to_serial(u8 *buf, u8 len);
int node_send_to_wireshark(u8 *buf, u8 len);
int server_receive_from_rf(u8 *recvBuf, u8 bufLen);
#define SIMU_SOCK_UDP 0
#define SIMU_SOCK_TCP 1
void win32_param_init(void);
void simu_init(void);
int simu_recvFromRF(u8 *recvBuf, u8 bufLen);
int simu_recvFromTH(u8 *recvBuf, u8 bufLen);
int simu_sendToRF(u8 *buf, u8 len);
int simu_sendToWireshark(u8 *buf, u8 len);
int simu_sendToTH(u8* buf, u8 len);
void simu_setChannel(u8 ch);
void vs_sockEnvironmentInit(void);
void appSock_init(const char *ip, u32 port, u8 type);
int appSock_recv(u8 *recvBuf, u8 bufLen);
#endif
| 30.105263 | 106 | 0.619318 |
360c96d52193ed13f930620b73844e83a78734c7 | 1,735 | h | C | MSFoundation/class/category/NSData+SBMODULE.h | gank0326/MSFoundation | f6f76d9d5ad59cf3b9d53a22e4d52e297b3ee8cd | [
"MIT"
] | null | null | null | MSFoundation/class/category/NSData+SBMODULE.h | gank0326/MSFoundation | f6f76d9d5ad59cf3b9d53a22e4d52e297b3ee8cd | [
"MIT"
] | null | null | null | MSFoundation/class/category/NSData+SBMODULE.h | gank0326/MSFoundation | f6f76d9d5ad59cf3b9d53a22e4d52e297b3ee8cd | [
"MIT"
] | null | null | null | /*
#####################################################################
# File : NSDataCagegory.h
# Project :
# Created : 2013-03-30
# DevTeam : Thomas Develop
# Author :
# Notes :
#####################################################################
### Change Logs ###################################################
#####################################################################
---------------------------------------------------------------------
# Date :
# Author:
# Notes :
#
#####################################################################
*/
//为SDK自带的 NSData 类添加一些实用方法
@interface NSData (sbmodule)
/** 把一个 NSData 转成十六进制字符串 */
- (NSString *)sb_toHexString;
/** 从一个十六进制字符串创建一个 NSData 对象 */
+ (NSData *)sb_dataWithHexString:(NSString *)string;
/** 去掉转义符号 */
- (NSString *)sb_removeEscapes;
@end
@interface NSData (Base64)
/**base64字符串 创建一个nsdata对象*/
+ (NSData *)sb_dataWithBase64EncodedString:(NSString *)string;
/**NSDATA base 64 转 nsstring*/
- (NSString *)sb_base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth;
/**NSDATA base 64 转 nsstring*/
- (NSString *)base64EncodedString;
@end
@interface NSData (AES)
/**
AES256加密
@param key 密钥
@return 加密结果
*/
- (NSData*)sb_encryptAES:(NSString *) key;
/**
AES256解密
@param key 密钥
@return 解密结果
*/
- (NSData *)sb_decryptAES:(NSString *) key;
@end
@interface NSData (EMSB_JSON)
/**
从一个json的nsdata转换成dict或array,
**使用UTF8编码**
@return dict or array
*/
- (id)sb_objectFromJSONData;
/**
从一个json的nsdata转换成dict或array, 指定编码
@param encoding 编码
@return dict or array
*/
- (id)sb_objectFromJSONDataUsingEncoding:(NSStringEncoding)encoding;
@end
| 19.065934 | 73 | 0.498559 |
0d9e6c6238c3dc795728cee0fcd8a1a2223c81c3 | 694 | c | C | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr55342.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr55342.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr55342.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | /* PR rtl-optimization/55342 */
/* { dg-do compile } */
/* { dg-options "-O2" } */
/* { dg-final { scan-assembler-not "notb" } } */
void convert_image(unsigned char *in, unsigned char *out, int size) {
int i;
unsigned char * read = in,
* write = out;
for(i = 0; i < size; i++) {
unsigned char r = *read++;
unsigned char g = *read++;
unsigned char b = *read++;
unsigned char c, m, y, k, tmp;
c = 255 - r;
m = 255 - g;
y = 255 - b;
if (c < m)
k = ((c) > (y)?(y):(c));
else
k = ((m) > (y)?(y):(m));
*write++ = c - k;
*write++ = m - k;
*write++ = y - k;
*write++ = k;
}
}
| 23.931034 | 69 | 0.425072 |
1ddcd1963606d6a04eedc6782f0751071d0184ac | 270 | h | C | Concepts/Constructor Initialization List/Constructor Parameters and overloading/Person.h | nwy140/C-Projects | e1d960f0f08231eb496267ddae37da5fbc9c9de9 | [
"MIT"
] | 1 | 2021-02-17T05:44:52.000Z | 2021-02-17T05:44:52.000Z | Concepts/Constructor Initialization List/Constructor Parameters and overloading/Person.h | nwy140/C-Projects | e1d960f0f08231eb496267ddae37da5fbc9c9de9 | [
"MIT"
] | null | null | null | Concepts/Constructor Initialization List/Constructor Parameters and overloading/Person.h | nwy140/C-Projects | e1d960f0f08231eb496267ddae37da5fbc9c9de9 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <string.h>
using namespace std;
class Person
{
private:
string name;
int age;
public:
Person() :name("unamed"), age(0) {};
Person(string name, int age) :name(name), age(age) {};
~Person();
string toString();
};
| 11.25 | 55 | 0.637037 |
3d3df2b20d5860f21907601f0600078734d1cbfe | 11,553 | c | C | Src/main.c | afiskon/stm32-rotary-encoder-example | d45f43b513dc5350c8ba8340ac95f20ca8904e51 | [
"MIT"
] | 5 | 2020-11-24T14:15:41.000Z | 2021-12-16T11:45:34.000Z | Src/main.c | afiskon/stm32-rotary-encoder-example | d45f43b513dc5350c8ba8340ac95f20ca8904e51 | [
"MIT"
] | null | null | null | Src/main.c | afiskon/stm32-rotary-encoder-example | d45f43b513dc5350c8ba8340ac95f20ca8904e51 | [
"MIT"
] | 2 | 2020-12-05T16:09:00.000Z | 2021-04-25T18:42:33.000Z | /* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
** This notice applies to any and all portions of this file
* that are not between comment pairs USER CODE BEGIN and
* USER CODE END. Other portions of this file, whether
* inserted by the user or by software development tools
* are owned by their respective copyright owners.
*
* COPYRIGHT(c) 2020 STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "st7735.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi1;
TIM_HandleTypeDef htim1;
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM1_Init(void);
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
extern volatile uint8_t buttonPressed[5];
int32_t prevCounter = 0;
void init() {
ST7735_Init();
ST7735_FillScreen(ST7735_BLACK);
ST7735_WriteString(0, 26*0, "--------", Font_16x26, ST7735_RED, ST7735_BLACK);
ST7735_WriteString(0, 26*1, "??????", Font_16x26, ST7735_GREEN, ST7735_BLACK);
HAL_TIM_Encoder_Start(&htim1, TIM_CHANNEL_ALL);
}
void loop() {
// Thats annoying
// HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
int currCounter = __HAL_TIM_GET_COUNTER(&htim1);
currCounter = 32767 - ((currCounter-1) & 0xFFFF) / 2;
if(currCounter != prevCounter) {
char buff[16];
snprintf(buff, sizeof(buff), "%06d", currCounter);
ST7735_WriteString(0, 26*1, buff, Font_16x26, ST7735_GREEN, ST7735_BLACK);
prevCounter = currCounter;
}
uint8_t buttonNumber = 0;
while(buttonNumber < sizeof(buttonPressed)/sizeof(buttonPressed[0])) {
if(buttonPressed[buttonNumber]) {
buttonPressed[buttonNumber] = 0;
char buff[16];
snprintf(buff, sizeof(buff), "BUTTON %d", buttonNumber);
ST7735_WriteString(0, 26*0, buff, Font_16x26, ST7735_RED, ST7735_BLACK);
}
buttonNumber++;
}
HAL_Delay(100);
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI1_Init();
MX_TIM1_Init();
/* USER CODE BEGIN 2 */
init();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
loop();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief SPI1 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_1LINE;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
/**
* @brief TIM1 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM1_Init(void)
{
/* USER CODE BEGIN TIM1_Init 0 */
/* USER CODE END TIM1_Init 0 */
TIM_Encoder_InitTypeDef sConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM1_Init 1 */
/* USER CODE END TIM1_Init 1 */
htim1.Instance = TIM1;
htim1.Init.Prescaler = 0;
htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
htim1.Init.Period = 65535;
htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim1.Init.RepetitionCounter = 0;
htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
sConfig.EncoderMode = TIM_ENCODERMODE_TI1;
sConfig.IC1Polarity = TIM_ICPOLARITY_RISING;
sConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI;
sConfig.IC1Prescaler = TIM_ICPSC_DIV1;
sConfig.IC1Filter = 0;
sConfig.IC2Polarity = TIM_ICPOLARITY_RISING;
sConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI;
sConfig.IC2Prescaler = TIM_ICPSC_DIV1;
sConfig.IC2Filter = 0;
if (HAL_TIM_Encoder_Init(&htim1, &sConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM1_Init 2 */
/* USER CODE END TIM1_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2, GPIO_PIN_RESET);
/*Configure GPIO pin : PC13 */
GPIO_InitStruct.Pin = GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pins : PA0 PA2 */
GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_2;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : PA1 */
GPIO_InitStruct.Pin = GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PB10 PB11 PB12 PB13
PB14 */
GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13
|GPIO_PIN_14;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* EXTI interrupt init*/
HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
while(1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 30.007792 | 84 | 0.657232 |
cedda236d5f29bbf690ef5fb66d11a4db9fc00ae | 1,801 | h | C | ecmascript/lexical_env.h | openharmony-gitee-mirror/ark_js_runtime | b5ac878349b00b337c45f4702332c23aa82e1e28 | [
"Apache-2.0"
] | 3 | 2021-09-08T09:16:18.000Z | 2021-12-28T21:14:06.000Z | ecmascript/lexical_env.h | openharmony-gitee-mirror/ark_js_runtime | b5ac878349b00b337c45f4702332c23aa82e1e28 | [
"Apache-2.0"
] | null | null | null | ecmascript/lexical_env.h | openharmony-gitee-mirror/ark_js_runtime | b5ac878349b00b337c45f4702332c23aa82e1e28 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:12:04.000Z | 2021-09-13T12:12:04.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ECMASCRIPT_LEXICALENV_H
#define ECMASCRIPT_LEXICALENV_H
#include "ecmascript/js_object.h"
namespace panda::ecmascript {
class LexicalEnv : public TaggedArray {
public:
static constexpr array_size_t PARENT_ENV_INDEX = 0;
static constexpr array_size_t RESERVED_ENV_LENGTH = 1;
static LexicalEnv *Cast(ObjectHeader *object)
{
ASSERT(JSTaggedValue(object).IsTaggedArray());
return static_cast<LexicalEnv *>(object);
}
static size_t ComputeSize(uint32_t numSlots)
{
return TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), numSlots + RESERVED_ENV_LENGTH);
}
void SetParentEnv(JSThread *thread, JSTaggedValue value)
{
Set(thread, PARENT_ENV_INDEX, value);
}
JSTaggedValue GetParentEnv() const
{
return Get(PARENT_ENV_INDEX);
}
JSTaggedValue GetProperties(uint32_t index) const
{
return Get(index + RESERVED_ENV_LENGTH);
}
void SetProperties(JSThread *thread, uint32_t index, JSTaggedValue value)
{
Set(thread, index + RESERVED_ENV_LENGTH, value);
}
DECL_DUMP()
};
} // namespace panda::ecmascript
#endif // ECMASCRIPT_LEXICALENV_H
| 29.048387 | 105 | 0.714048 |
383596c42ca8f4a7b1c6959b217ad897a2208ea5 | 2,440 | c | C | snapgear_linux/user/modutils-2.4.26/kerneld/kdsend.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/user/modutils-2.4.26/kerneld/kdsend.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/user/modutils-2.4.26/kerneld/kdsend.c | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | 3 | 2016-06-13T13:20:56.000Z | 2019-12-05T02:31:23.000Z | #define CONFIG_KERNELD
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "kerneld.h"
#define MSIZE 1024
#ifndef KDHDR
# ifdef NEW_KERNELD_PROTOCOL
# define KDHDR (sizeof(long) + sizeof(short) + sizeof(short))
# else
# define KDHDR sizeof(long)
# endif
#endif
/*
* Copyright (C) 1995, Bjorn Ekwall <bj0rn@blox.se>
*
* See the file "COPYING" for your rights.
*
* Fake a call to kerneld.
* This is just used to debug kerneld...
*
* All calls are with id=0, i.e. no response from kerneld, unless
* the option "-r" is used, which will use reply type = current pid + 1024.
* Note: this message type will _not_ be intercepted by the kernel
* or kerneld, since the kernel listens for messages >= 0x7fff0000
* and kerneld listens for messages <= 255 !
*
* Usage: kdsend type message
* where type should be the numeric value of the request
* Example: "kdsend 2 ppp" will load the ppp stack
* "kdsend 4 ppp" will remove the ppp stack (if possible) after 60 sec
* "kdsend -r 1 ls" will execute ls and return the result.
*
* See <linux/kerneld.h> for possible types...
*/
#define REPLY_ID 1024
int
main(argc, argv)
int argc;
char **argv;
{
struct kerneld_msg *msgp;
int msgtyp;
int qid;
int status;
int reply = 0;
if ((argc > 1) && (strcmp(argv[1], "-r") == 0)) {
reply = 1;
++argv;
--argc;
}
if (argc < 2) {
fprintf(stderr, "use: kdsend [-r] type message\n");
exit(1);
}
qid = msgget(IPC_PRIVATE, 0600 | IPC_KERNELD);
if (qid < 0) {
perror("kdsend");
exit(1);
}
msgp = (struct kerneld_msg *)malloc(sizeof(struct kerneld_msg) + MSIZE);
#ifdef NEW_KERNELD_PROTOCOL
msgp->version = 2;
msgp->pid = getpid();
#endif
if ((msgtyp = atol(argv[1])) == 0)
msgtyp = 1; /* ksystem */
msgp->mtype = msgtyp;
if (reply)
reply = msgp->id = REPLY_ID + getpid();
else
msgp->id = 0;
if (argc == 3)
strcpy(msgp->text, argv[2]);
else
msgp->text[0] = '\0';
status = msgsnd(qid, (struct msgbuf *)msgp,
KDHDR + strlen(msgp->text), 0);
if (status < 0)
perror("kdsend");
if (reply) {
status = msgrcv(qid, (struct msgbuf *)msgp,
KDHDR + MSIZE, reply, MSG_NOERROR);
if (status > 0) {
msgp->text[status - KDHDR] = '\0';
printf("recieved %d bytes: '%s'\n", status, msgp->text);
}
else if (status < 0)
perror("kdsend");
else
printf("nothing recieved\n");
}
return status;
}
| 22.385321 | 79 | 0.640984 |
e1e5ecf7f01622e795d6084ddd373839f074c5be | 2,602 | h | C | src/ENGINE/Engine.h | dr4gon37/AtmosphereScattering | f5c14fc49889cf4d0572c5fe0e390b3f3dc9c958 | [
"MIT"
] | null | null | null | src/ENGINE/Engine.h | dr4gon37/AtmosphereScattering | f5c14fc49889cf4d0572c5fe0e390b3f3dc9c958 | [
"MIT"
] | null | null | null | src/ENGINE/Engine.h | dr4gon37/AtmosphereScattering | f5c14fc49889cf4d0572c5fe0e390b3f3dc9c958 | [
"MIT"
] | null | null | null | #pragma once
#include "ENGINE/WindowClass.h"
#include "ENGINE/InputEngine.h"
#include "ENGINE/EngineInputFunctions.h"
#include "IMGUI/ImguiClass.h"
#include <string>
#include "MODEL/model1.h"
#include "TEXT/text_renderer.h"
#include "MATHS/SunDirection.h"
#ifdef _WIN64
#include <intrin.h>
#include <glad/glad.h>
#include <memory>
#include "./MODEL/model1.h"
#include "./TEXT/text_renderer.h"
#endif
const int TICKS_PER_SECOND = 60;
const float SEC_PER_TICK = 1.0f / TICKS_PER_SECOND;
const float MS_PER_TICK = 1000.0f / TICKS_PER_SECOND;
struct Pointers
{
InputEngine<EngineInputFunctions> *inputEngine = nullptr;
SunDirection *sunDirection = nullptr;
Pointers::~Pointers()
{
std::cout << "Pointers deleted" << std::endl;
}
};
class Engine
{
private:
GLFWwindow* window;
InputEngine<EngineInputFunctions> *inputEngine;
ImguiClass * imguiClass;
SunDirection *sunDirection;
Pointers pointers;
std::string CPU;
std::string GPU;
std::string memory;
std::string usingMemory;
private:
void getSystemInfo() noexcept;
void refreshMemoryInfo() noexcept;
enum Luminance {
// Render the spectral radiance at kLambdaR, kLambdaG, kLambdaB.
NONE,
// Render the sRGB luminance, using an approximate (on the fly) conversion
APPROXIMATE,
// Render the sRGB luminance, precomputed from 15 spectral radiance values
PRECOMPUTED
};
void handleRedisplayEvent() ;
void handleReshapeEvent(int viewport_width, int viewport_height);
void setView(double viewDistanceMeters, double viewZenithAngleRadians,
double viewAzimuthAngleRadians, double sunZenithAngleRadians,
double sunAzimuthAngleRadians, double exposure);
void modelInit(double density, double kTop, double kRay, double kMie);
bool useConstantSolarSpectrum;
bool useOzone;
bool useCombinedTextures;
bool useHalfPrecision;
Luminance useLuminance;
bool doWhiteBalance;
std::unique_ptr<Model1> modelPointer;
GLuint vertexShader;
GLuint fragmentShader;
GLuint programId;
GLuint fullScreenQuadVAO;
GLuint fullScreenQuadVBO;
std::unique_ptr<TextRenderer> textRenderer;
int windowId;
double viewDistanceMeters;
double viewZenithAngleRadians;
double viewAzimuthAngleRadians;
double exposure;
public:
double density;
double topHeight;
double rayleigh;
double mie;
const Model1& model1() const { return *modelPointer; }
const GLuint vertex_shader() const { return vertexShader; }
const GLuint fragment_shader() const { return fragmentShader; }
const GLuint program() const { return programId; }
Engine();
~Engine();
void run();
void initializeObjects();
void updateModel();
}; | 22.824561 | 76 | 0.767487 |
c005863c078520263cb57a7fc9781c44c03c3e2e | 1,535 | h | C | examples/pxScene2d/external/libdash/libdash/libdash/source/xml/DOMParser.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 46 | 2017-09-07T14:59:22.000Z | 2020-10-31T20:34:12.000Z | examples/pxScene2d/external/libdash/libdash/libdash/source/xml/DOMParser.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/libdash/libdash/libdash/source/xml/DOMParser.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 317 | 2017-06-20T19:57:17.000Z | 2020-09-16T10:28:30.000Z | /*
* DOMParser.h
*****************************************************************************
* Copyright (C) 2012, bitmovin Softwareentwicklung OG, All Rights Reserved
*
* Email: libdash-dev@vicky.bitmovin.net
*
* This source code and its use and distribution, is subject to the terms
* and conditions of the applicable license agreement.
*****************************************************************************/
#ifndef DOMPARSER_H_
#define DOMPARSER_H_
#include "config.h"
#include "Node.h"
#include <libxml/xmlreader.h>
#include "../helpers/Path.h"
namespace dash
{
namespace xml
{
enum NodeType
{
Start = 1,
End = 15,
Comment = 8,
WhiteSpace = 14,
Text = 3,
};
class DOMParser
{
public:
DOMParser (std::string url);
virtual ~DOMParser ();
bool Parse ();
Node* GetRootNode () const;
void Print ();
private:
xmlTextReaderPtr reader;
Node *root;
std::string url;
void Init ();
Node* ProcessNode ();
void AddAttributesToNode (Node *node);
void Print (Node *node, int offset);
};
}
}
#endif /* DOMPARSER_H_ */ | 27.410714 | 79 | 0.403909 |
07a926b043fdfcfb39656e37d4086839e79b3af9 | 158 | h | C | src/imagine/math/geom/spatial/frustum.h | ads00/imagine | f8063f636306a18f7c98512548a3c2ef2fd8cc48 | [
"MIT"
] | null | null | null | src/imagine/math/geom/spatial/frustum.h | ads00/imagine | f8063f636306a18f7c98512548a3c2ef2fd8cc48 | [
"MIT"
] | null | null | null | src/imagine/math/geom/spatial/frustum.h | ads00/imagine | f8063f636306a18f7c98512548a3c2ef2fd8cc48 | [
"MIT"
] | null | null | null | /*
Imagine v0.1
[math]
Copyright (c) 2015-present, Hugo (hrkz) Frezat
*/
#ifndef IG_MATH_FRUSTUM_H
#define IG_MATH_FRUSTUM_H
#endif // IG_MATH_FRUSTUM_H
| 14.363636 | 47 | 0.740506 |
6dab7ba70c940bc4bdbdbc9f574071641bbbb322 | 3,176 | h | C | source/Matrix/ws2812b.h | Vadim-Seledets/ws2812b | 5d654ccd6eeb810bbae65255e8d672827045aaba | [
"MIT"
] | 1 | 2021-06-02T20:14:31.000Z | 2021-06-02T20:14:31.000Z | source/Matrix/ws2812b.h | Vadim-Seledets/ws2812b | 5d654ccd6eeb810bbae65255e8d672827045aaba | [
"MIT"
] | null | null | null | source/Matrix/ws2812b.h | Vadim-Seledets/ws2812b | 5d654ccd6eeb810bbae65255e8d672827045aaba | [
"MIT"
] | null | null | null | #ifndef WS2812B_H_
#define WS2812B_H_
#include <avr/io.h>
#include <avr/interrupt.h>
#include "stdlib.h"
#include "string.h"
const uint8_t MATRIX_WIDTH = 16;
const uint8_t MATRIX_HEIGHT = 16;
const uint16_t NUMBER_OF_PIXELS = MATRIX_WIDTH * MATRIX_HEIGHT;
const uint16_t NUMBER_OF_BYTES = NUMBER_OF_PIXELS * 3;
extern uint8_t *vram;
enum class ColorModel {
RGB,
HSL // Not yet implemented
};
struct RGB {
uint8_t red;
uint8_t green;
uint8_t blue;
RGB(uint8_t r, uint8_t g, uint8_t b)
: red(r), green(g), blue(b) {}
};
struct HSL {
uint8_t hue;
uint8_t saturation;
uint8_t lightness;
};
struct Color
{
ColorModel color_model;
union
{
RGB rgb;
HSL hsl;
};
Color(ColorModel cm, RGB value)
: color_model(cm), rgb(value) {}
};
const Color Black = { ColorModel::RGB, { 0, 0, 0 } };
const Color White = { ColorModel::RGB, { 255, 255, 255 } };
const Color Red = { ColorModel::RGB, { 255, 0, 0 } };
const Color Lime = { ColorModel::RGB, { 0, 255, 0 } };
const Color Blue = { ColorModel::RGB, { 0, 0, 255 } };
const Color Yellow = { ColorModel::RGB, { 255, 255, 0 } };
const Color Cyan = { ColorModel::RGB, { 0, 255, 255 } };
const Color Magenta = { ColorModel::RGB, { 255, 0, 255 } };
const Color Silver = { ColorModel::RGB, { 192, 192, 192 } };
const Color Gray = { ColorModel::RGB, { 128, 128, 128 } };
const Color Maroon = { ColorModel::RGB, { 128, 0, 0 } };
const Color Olive = { ColorModel::RGB, { 128, 128, 0 } };
const Color Green = { ColorModel::RGB, { 0, 128, 0 } };
const Color Purple = { ColorModel::RGB, { 128, 0, 128 } };
const Color Teal = { ColorModel::RGB, { 0, 128, 128 } };
const Color Navy = { ColorModel::RGB, { 0, 0, 128 } };
// const Color Black = { ColorModel::RGB, { 0, 0, 0 } };
// const Color White = { ColorModel::RGB, { 25, 25, 25 } };
// const Color Red = { ColorModel::RGB, { 25, 0, 0 } };
// const Color Lime = { ColorModel::RGB, { 0, 25, 0 } };
// const Color Blue = { ColorModel::RGB, { 0, 0, 25 } };
// const Color Yellow = { ColorModel::RGB, { 25, 25, 0 } };
// const Color Cyan = { ColorModel::RGB, { 0, 25, 25 } };
// const Color Magenta = { ColorModel::RGB, { 25, 0, 25 } };
// const Color Silver = { ColorModel::RGB, { 19, 19, 19 } };
// const Color Gray = { ColorModel::RGB, { 13, 13, 13 } };
// const Color Maroon = { ColorModel::RGB, { 13, 0, 0 } };
// const Color Olive = { ColorModel::RGB, { 13, 13, 0 } };
// const Color Green = { ColorModel::RGB, { 0, 13, 0 } };
// const Color Purple = { ColorModel::RGB, { 13, 0, 13 } };
// const Color Teal = { ColorModel::RGB, { 0, 13, 13 } };
// const Color Navy = { ColorModel::RGB, { 0, 0, 13 } };
inline uint8_t xy_to_pixel_index(const uint8_t x, const uint8_t y)
{
return ((x + 1) / 2) * (2 * MATRIX_HEIGHT - 1) + (x / 2) + (x % 2 == 0 ? y : -y);
}
inline void clear()
{
cli();
memset(vram, 0, NUMBER_OF_BYTES);
sei();
}
void show(uint8_t *bytes, uint16_t count);
void set_pixel(const uint8_t x, const uint8_t y, const Color color);
/** @param lightness the range is [0, 100]% */
Color set_lightness(const Color color, const uint8_t lightness);
#endif /* WS2812B_H_ */
| 31.137255 | 85 | 0.605164 |
0d4ee6fa099d32a32534dc227c794c8e2fbf5c68 | 1,731 | h | C | include/il2cpp/System/Array/InternalEnumerator_Section_FieldEffect_Add/getDefaultSuccessMessage_GroundTableElem_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/System/Array/InternalEnumerator_Section_FieldEffect_Add/getDefaultSuccessMessage_GroundTableElem_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/System/Array/InternalEnumerator_Section_FieldEffect_Add/getDefaultSuccessMessage_GroundTableElem_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem____ctor (System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem__o __this, System_Array_o* array, const MethodInfo* method_info);
void System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem___Dispose (System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem__o __this, const MethodInfo* method_info);
bool System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem___MoveNext (System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem__o __this, const MethodInfo* method_info);
Dpr_Battle_Logic_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem_o System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem___get_Current (System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem__o __this, const MethodInfo* method_info);
void System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem___System_Collections_IEnumerator_Reset (System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem__o __this, const MethodInfo* method_info);
Il2CppObject* System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem___System_Collections_IEnumerator_get_Current (System_Array_InternalEnumerator_Section_FieldEffect_Add_getDefaultSuccessMessage_GroundTableElem__o __this, const MethodInfo* method_info);
| 157.363636 | 335 | 0.949162 |
ed127818f2ef14e6c7e3dddbbb7d7cb816bd43ae | 1,980 | h | C | globalbp.h | bigsql/pldebugger | 510f90fd51d6b925738c602f3eb4bc8c48fb276e | [
"Artistic-2.0"
] | 1 | 2020-09-08T07:54:51.000Z | 2020-09-08T07:54:51.000Z | globalbp.h | bigsql/pldebugger | 510f90fd51d6b925738c602f3eb4bc8c48fb276e | [
"Artistic-2.0"
] | null | null | null | globalbp.h | bigsql/pldebugger | 510f90fd51d6b925738c602f3eb4bc8c48fb276e | [
"Artistic-2.0"
] | 1 | 2020-09-08T07:54:53.000Z | 2020-09-08T07:54:53.000Z | /*
* globalbp.h -
*
* This file defines the (shared-memory) structures used by the PL debugger
* to keep track of global breakpoints.
*
* Copyright (c) 2004-2018 EnterpriseDB Corporation. All Rights Reserved.
*
* Licensed under the Artistic License v2.0, see
* https://opensource.org/licenses/artistic-license-2.0
* for full details
*/
#ifndef GLOBALBP_H
#define GLOBALBP_H
#include "utils/hsearch.h"
typedef enum
{
BP_LOCAL = 0,
BP_GLOBAL
} eBreakpointScope;
/*
* Stores information pertaining to a global breakpoint.
*/
typedef struct BreakpointData
{
bool isTmp; /* tmp breakpoints are removed when hit */
bool busy; /* is this session already in use by a target? */
int proxyPort; /* port number of the proxy listener */
int proxyPid; /* process id of the proxy process */
} BreakpointData;
/*
* The key of the global breakpoints hash table. For now holds only have an Oid field.
* but it may contain more fields in future.
*/
typedef struct BreakpointKey
{
Oid databaseId;
Oid functionId;
int lineNumber;
int targetPid; /* -1 means any process */
} BreakpointKey;
typedef struct Breakpoint
{
BreakpointKey key;
BreakpointData data;
} Breakpoint;
extern Breakpoint * BreakpointLookup(eBreakpointScope scope, BreakpointKey *key);
extern bool BreakpointInsert(eBreakpointScope scope, BreakpointKey *key, BreakpointData *brkpnt);
extern bool BreakpointDelete(eBreakpointScope scope, BreakpointKey *key);
extern void BreakpointShowAll(eBreakpointScope scope);
extern bool BreakpointInsertOrUpdate(eBreakpointScope scope, BreakpointKey *key, BreakpointData *data);
extern bool BreakpointOnId(eBreakpointScope scope, Oid funcOid);
extern void BreakpointCleanupProc(int pid);
extern void BreakpointGetList(eBreakpointScope scope, HASH_SEQ_STATUS *scan);
extern void BreakpointReleaseList(eBreakpointScope scope);
extern void BreakpointBusySession(int pid);
extern void BreakpointFreeSession(int pid);
#endif
| 30.461538 | 105 | 0.761111 |
9876736c6731e8259a853c7c3a840f720a236493 | 1,345 | h | C | JCDT/JCDT_Lib/internal/lookup/SymbolCast.h | kuafuwang/JCDT | 2b009ea887b4816303fed9e6e1dc104a90c67d16 | [
"MIT"
] | 1 | 2021-04-17T01:55:27.000Z | 2021-04-17T01:55:27.000Z | JCDT/JCDT_Lib/internal/lookup/SymbolCast.h | kuafuwang/JCDT | 2b009ea887b4816303fed9e6e1dc104a90c67d16 | [
"MIT"
] | null | null | null | JCDT/JCDT_Lib/internal/lookup/SymbolCast.h | kuafuwang/JCDT | 2b009ea887b4816303fed9e6e1dc104a90c67d16 | [
"MIT"
] | 1 | 2022-02-18T12:02:00.000Z | 2022-02-18T12:02:00.000Z |
#ifndef SymbolCast_jikes_INCLUDED
#define SymbolCast_jikes_INCLUDED
#include "lookup_Pre_declaration.h"
namespace Jikes { // Open namespace Jikes block
class SymbolCast
{
public:
static PackageSymbol* PackageCast(Symbol*);
static const PackageSymbol* PackageCast(const Symbol*) ;
static TypeSymbol* TypeCast( Symbol*);
static const TypeSymbol* TypeCast(const Symbol*);
static MethodSymbol* MethodCast( Symbol*);
static const MethodSymbol* MethodCast(const Symbol*);
static BlockSymbol* BlockCast( Symbol*);
static const BlockSymbol* BlockCast(const Symbol*);
static VariableSymbol* VariableCast( Symbol*);
static const VariableSymbol* VariableCast(const Symbol*);
static LabelSymbol* LabelCast( Symbol*);
static const LabelSymbol* LabelCast(const Symbol*);
static LiteralSymbol* LiteralCast( Symbol*);
static const LiteralSymbol* LiteralCast(const Symbol*);
/*static NameSymbol* NameCast( Symbol*);
static const NameSymbol* NameCast(const Symbol*);
*/
static PathSymbol* PathCast(Symbol*);
static const PathSymbol* PathCast(const Symbol*) ;
static DirectorySymbol* DirectoryCast(Symbol*);
static const DirectorySymbol* DirectoryCast(const Symbol*) ;
static FileSymbol* FileCast(Symbol*);
static const FileSymbol* FileCast(const Symbol*);
};
} // Close namespace Jikes block
#endif // _INCLUDED
| 22.416667 | 61 | 0.768773 |
7214aa994606cb79ad33d3585a6c88970022b807 | 5,205 | c | C | tests/test-configuration.c | matttbe/mptcpd | ec93b41521d43d6636807ba462f62db2ab5506fc | [
"BSD-3-Clause"
] | null | null | null | tests/test-configuration.c | matttbe/mptcpd | ec93b41521d43d6636807ba462f62db2ab5506fc | [
"BSD-3-Clause"
] | null | null | null | tests/test-configuration.c | matttbe/mptcpd | ec93b41521d43d6636807ba462f62db2ab5506fc | [
"BSD-3-Clause"
] | null | null | null | // SPDX-License-Identifier: BSD-3-Clause
/**
* @file test-configuration.c
*
* @brief mptcpd configuration test.
*
* Copyright (c) 2019, 2021, Intel Corporation
*/
#include <ell/main.h>
#include <ell/util.h> // Needed by <ell/log.h>
#include <ell/log.h>
#include <ell/test.h>
#include <mptcpd/private/configuration.h> // INTERNAL!
#undef NDEBUG
#include <assert.h>
#define TEST_PROGRAM_NAME "test-configuration"
#define RUN_CONFIG(argv) run_config(L_ARRAY_SIZE(argv), (argv))
static void run_config(int argc, char **argv)
{
struct mptcpd_config *const config =
mptcpd_config_create(argc, argv);
assert(config != NULL);
mptcpd_config_destroy(config);
l_log_set_stderr();
}
static void test_debug(void const *test_data)
{
(void) test_data;
static char *argv1[] = { TEST_PROGRAM_NAME, "--debug" };
static char *argv2[] = { TEST_PROGRAM_NAME, "-d" };
RUN_CONFIG(argv1);
RUN_CONFIG(argv2);
}
#define TEST_LOG(logger) \
do { \
static char *argv1[] = { TEST_PROGRAM_NAME, "--log=" logger }; \
static char *argv2[] = { TEST_PROGRAM_NAME, "-l", logger }; \
\
RUN_CONFIG(argv1); \
RUN_CONFIG(argv2); \
} while(0)
static void test_log_stderr(void const *test_data)
{
(void) test_data;
TEST_LOG("stderr");
}
static void test_log_syslog(void const *test_data)
{
(void) test_data;
TEST_LOG("syslog");
}
static void test_log_journal(void const *test_data)
{
(void) test_data;
TEST_LOG("journal");
}
static void test_log_null(void const *test_data)
{
(void) test_data;
TEST_LOG("null");
}
static void test_plugin_dir(void const *test_data)
{
(void) test_data;
static char *argv[] =
{ TEST_PROGRAM_NAME, "--plugin-dir", "/tmp/foo/bar" };
RUN_CONFIG(argv);
}
static void test_path_manager(void const *test_data)
{
(void) test_data;
static char *argv[] =
{ TEST_PROGRAM_NAME, "--path-manager", "foo" };
RUN_CONFIG(argv);
}
static void test_load_plugins(void const *test_data)
{
(void) test_data;
static char *argv[] =
{ TEST_PROGRAM_NAME, "--load-plugins", "foo,bar" };
RUN_CONFIG(argv);
}
static void test_multi_arg(void const *test_data)
{
(void) test_data;
static char plugin_dir[] = "/tmp/foo/bar";
static char override_dir[] = "/tmp/foo/baz";
assert(strcmp(plugin_dir, override_dir) != 0);
static char pm[] = "foo";
static char override_pm[] = "bar";
assert(strcmp(pm, override_pm) != 0);
static char *argv[] = {
TEST_PROGRAM_NAME,
"--plugin-dir", plugin_dir,
"--path-manager", pm,
"--plugin-dir", override_dir,
"--path-manager", override_pm
};
struct mptcpd_config *const config =
mptcpd_config_create(L_ARRAY_SIZE(argv), argv);
assert(config != NULL);
assert(config->plugin_dir != NULL);
assert(strcmp(config->plugin_dir, override_dir) == 0);
assert(config->default_plugin != NULL);
assert(strcmp(config->default_plugin, override_pm) == 0);
mptcpd_config_destroy(config);
}
static void test_config_file(void const *test_data)
{
(void) test_data;
/**
* @todo Test mptcpd configuration file parsing. The
* configuration file location is currently compiled
* into the program since mptcpd may be run with
* elevated privileges. A test can't be performed until
* mptcpd supports specifying the configuration file
* location at run-time, perhaps through a XDG-style
* approach (@c $XDG_CONFIG_DIRS and/or
* @c $XDG_CONFIG_HOME).
*/
l_info("Configuration file test is unimplemented.");
}
int main(int argc, char *argv[])
{
if (!l_main_init())
return -1;
l_log_set_stderr();
l_test_init(&argc, &argv);
l_test_add("log stderr", test_log_stderr, NULL);
l_test_add("log syslog", test_log_syslog, NULL);
l_test_add("log journal", test_log_journal, NULL);
l_test_add("log null", test_log_null, NULL);
l_test_add("plugin dir", test_plugin_dir, NULL);
l_test_add("path manager", test_path_manager, NULL);
l_test_add("load plugins", test_load_plugins, NULL);
l_test_add("multi arg", test_multi_arg, NULL);
l_test_add("config file", test_config_file, NULL);
l_test_add("debug", test_debug, NULL);
l_test_run();
return l_main_exit() ? 0 : -1;
}
/*
Local Variables:
c-file-style: "linux"
End:
*/
| 26.42132 | 80 | 0.557925 |
900f69a7b0bcfa8cdf4a78d186cb5ffc3f0bb918 | 448 | h | C | ch08-inheritance-and-polymorphism/ExtremeC_examples_chapter8_4_duck.h | Grahame-student/Extreme-C | b5fa8c6575147e095d8e72b829f08d04b9d4e2e2 | [
"MIT"
] | 162 | 2019-07-02T21:58:08.000Z | 2022-03-27T20:53:31.000Z | ch08-inheritance-and-polymorphism/ExtremeC_examples_chapter8_4_duck.h | Grahame-student/Extreme-C | b5fa8c6575147e095d8e72b829f08d04b9d4e2e2 | [
"MIT"
] | 2 | 2020-09-01T22:00:49.000Z | 2021-09-05T13:57:14.000Z | ch08-inheritance-and-polymorphism/ExtremeC_examples_chapter8_4_duck.h | Grahame-student/Extreme-C | b5fa8c6575147e095d8e72b829f08d04b9d4e2e2 | [
"MIT"
] | 80 | 2019-01-26T09:51:33.000Z | 2022-03-30T13:53:23.000Z | // File name: ExtremeC_examples_chapter8_4_duck.h
// Description: Public interface of the duck class
#ifndef EXTREME_C_EXAMPLES_CHAPTER_8_4_DUCK_H
#define EXTREME_C_EXAMPLES_CHAPTER_8_4_DUCK_H
// Forward declaration
struct duck_t;
// Memory allocator
struct duck_t* duck_new();
// Constructor
void duck_ctor(struct duck_t*);
// Destructor
void duck_dtor(struct duck_t*);
// All behavior functions are inherited from the animal class.
#endif
| 20.363636 | 62 | 0.801339 |
fd1ebb37bda201043adc023962ca62353e8a4328 | 3,797 | c | C | src/common/tchatche.c | MisterDA/tCHATche | c05e5bfa22e838ded59ea78ca39529889e723125 | [
"MIT"
] | null | null | null | src/common/tchatche.c | MisterDA/tCHATche | c05e5bfa22e838ded59ea78ca39529889e723125 | [
"MIT"
] | null | null | null | src/common/tchatche.c | MisterDA/tCHATche | c05e5bfa22e838ded59ea78ca39529889e723125 | [
"MIT"
] | null | null | null | #include "tchatche.h"
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <dirent.h>
#include <regex.h>
#define TMP "/tmp/tCHATche"
//#define FILENAME_REGEX "^[a-zA-Z0-9' '()\\[\\]_\\-][a-zA-Z0-9.' '()\\[\\]_\\-]*$"
#define FILENAME_REGEX "^[-_a-zA-Z0-9 ()][-_a-zA-Z0-9. ()]*$"
void mktmpdir(void) {
mode_t omode = umask(0);
if (mkdir(TMP, 0777))
if (errno != EEXIST)
error_exit("mkdir");
umask(omode);
}
char *mktmpfifo(char *path) {
mode_t omode = umask(0);
int ret = mkfifo(path, 0666);
if (ret)
error_exit(path);
umask(omode);
return strdup(path);
}
/* To create a temporary named pipe, we have to create a temporary file with
* mkstemp, close and remove it, and use mkfifo on the generated name.
* mkfifo will fail if the file has been recreated. In this case, we try up to
* 10 times to create a new fifo. */
static char *mkstmpfifo(char *path)
{
int file, ret, i = 0;
do {
mode_t omode = umask(0);
if ((file = mkstemp(path)) == -1)
error_exit("mkstemp");
if (close(file))
error_exit("close");
if (unlink(path))
error_exit("unlink");
if ((ret = mkfifo(path, 0666)))
if (errno != EEXIST)
error_exit(NULL);
umask(omode);
++i;
} while (ret == -1 && i < 10);
return ret != -1 ? path : NULL;
}
char *mktmpfifo_client(void)
{
size_t len = sizeof(TMP"/client-XXXXXX");
char *p = malloc(len);
memcpy(p, TMP"/client-XXXXXX", len);
mktmpdir();
return mkstmpfifo(p);
}
char *mktmpfifo_server(void)
{
size_t len = sizeof(TMP"/server-XXXXXX");
char *p = malloc(len);
memcpy(p, TMP"/server-XXXXXX", len);
mktmpdir();
return mkstmpfifo(p);
}
bool
dir_is_empty(const char *path)
{
DIR *dir;
bool ret = true;
struct dirent *ent;
if ((dir = opendir(path)) == NULL)
return false;
while ((ent = readdir(dir))) {
if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, "..")))
continue;
//printf(">>> %s\n", ent->d_name); //DEV
ret = false;
break;
}
closedir(dir);
return ret;
}
static regex_t filename_regex;
static void
filename_regex_init()
{
static bool lock = false;
if (lock) return;
else lock = true;
if (regcomp(&filename_regex, FILENAME_REGEX, REG_EXTENDED|REG_NOSUB)) {
fprintf(stderr, "regex compilation failed\n");
exit(EXIT_FAILURE);
}
}
bool
valid_filename(char *filename)
{
filename_regex_init();
if (regexec(&filename_regex, filename, 0, NULL, 0))
return false;
return true;
}
int
open_new(char *dir, char *basename)
{
char *ext = rawmemchr(basename, '\0');
do {
char *e = memrchr(basename, '.', ext-basename);
if (e && e-basename) ext = e;
else break;
} while (strcmp(ext, ".gz")==0);
char *base = strndup(basename, ext-basename);
char *path;
int fd = -1;
uint32_t i = 1;
while (true) {
if (i==0)
break;
if (i==1)
asprintf(&path, "%s/%s%s", dir, base, ext);
else
asprintf(&path, "%s/%s(%u)%s", dir, base, i, ext);
fd = open(path, O_WRONLY|O_CREAT|O_EXCL, 0666);
free(path);
if (fd != -1 || errno != EEXIST) break;
i++;
}
free(base);
return fd;
}
static FILE *log_file = NULL;
static const char *log_motd = "";
void logs_start(FILE *file, const char *motd) {
if (log_file) {
fputs("Logging had already started", stderr);
exit(EXIT_FAILURE);
} else if (file) {
log_file = file;
}
fflush(log_file);
log_motd = motd;
}
void logs(const char *fmt, ...) {
if (!log_file) {
fputs("Logging had not started", stderr);
exit(EXIT_FAILURE);
}
fputs(log_motd, log_file);
va_list varglist;
va_start(varglist, fmt);
vfprintf(log_file, fmt, varglist);
va_end(varglist);
fflush(log_file);
}
void logs_end(void) {
fputs("\n\n", log_file);
if (log_file)
fclose(log_file);
log_file = NULL;
}
| 20.413978 | 83 | 0.636819 |
ccfa40abf119cef290bb91834ce06fbcdd6f4626 | 2,069 | h | C | include/stp/Simplifier/constantBitP/ConstantBitP_MaxPrecision.h | eurecom-s3/stp | f8510975ecc2c9774d9dbd5759f95e90f0a32cd6 | [
"BSL-1.0",
"MIT"
] | null | null | null | include/stp/Simplifier/constantBitP/ConstantBitP_MaxPrecision.h | eurecom-s3/stp | f8510975ecc2c9774d9dbd5759f95e90f0a32cd6 | [
"BSL-1.0",
"MIT"
] | null | null | null | include/stp/Simplifier/constantBitP/ConstantBitP_MaxPrecision.h | eurecom-s3/stp | f8510975ecc2c9774d9dbd5759f95e90f0a32cd6 | [
"BSL-1.0",
"MIT"
] | null | null | null | // -*- c++ -*-
/********************************************************************
* AUTHORS: Trevor Hansen
*
* BEGIN DATE: Februrary, 2010
*
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 CONSTANTBITPROPAGATION_MAXPRECISION_H_
#define CONSTANTBITPROPAGATION_MAXPRECISION_H_
#include "stp/Simplifier/constantBitP/ConstantBitPropagation.h"
#include <vector>
#include "stp/Simplifier/constantBitP/FixedBits.h"
#include "stp/AST/ASTKind.h"
namespace simplifier
{
namespace constantBitP
{
enum Direction
{
UPWARDS_ONLY, BOTH_WAYS
};
// This is used for very specific purposes.
enum Type
{
BOOL_TYPE, VALUE_TYPE
};
struct Signature
{
BEEV::Kind kind;
Type resultType;
Type inputType;
int maxInputWidth;
int numberOfInputs;
Direction direction;
bool imprecise;
Signature()
{
imprecise=false;
}
};
bool maxPrecision(std::vector<FixedBits*> children, FixedBits& output, BEEV::Kind kind, BEEV::STPMgr* beev);
}
}
#endif /* CONSTANTBITPROPAGATION_MAXPRECISION_H_ */
| 28.736111 | 108 | 0.719188 |
e63aba6aa04147d834259ad225fe1c998e470016 | 3,055 | h | C | chrome/browser/lacros/chrome_browser_main_extra_parts_lacros.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | chrome/browser/lacros/chrome_browser_main_extra_parts_lacros.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | chrome/browser/lacros/chrome_browser_main_extra_parts_lacros.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_LACROS_CHROME_BROWSER_MAIN_EXTRA_PARTS_LACROS_H_
#define CHROME_BROWSER_LACROS_CHROME_BROWSER_MAIN_EXTRA_PARTS_LACROS_H_
#include "chrome/browser/chrome_browser_main_extra_parts.h"
#include <memory>
class AutomationManagerLacros;
class BrowserServiceLacros;
class DriveFsCache;
class DownloadControllerClientLacros;
class ForceInstalledTrackerLacros;
class LacrosButterBar;
class LacrosExtensionAppsController;
class LacrosExtensionAppsPublisher;
class KioskSessionServiceLacros;
class FieldTrialObserver;
namespace crosapi {
class TaskManagerLacros;
class WebPageInfoProviderLacros;
} // namespace crosapi
namespace content {
class ScreenOrientationDelegate;
} // namespace content
// Browser initialization for Lacros.
class ChromeBrowserMainExtraPartsLacros : public ChromeBrowserMainExtraParts {
public:
ChromeBrowserMainExtraPartsLacros();
ChromeBrowserMainExtraPartsLacros(const ChromeBrowserMainExtraPartsLacros&) =
delete;
ChromeBrowserMainExtraPartsLacros& operator=(
const ChromeBrowserMainExtraPartsLacros&) = delete;
~ChromeBrowserMainExtraPartsLacros() override;
private:
// ChromeBrowserMainExtraParts:
void PostBrowserStart() override;
std::unique_ptr<AutomationManagerLacros> automation_manager_;
// Handles browser action requests from ash-chrome.
std::unique_ptr<BrowserServiceLacros> browser_service_;
// Handles task manager crosapi from ash for sending lacros tasks to ash.
std::unique_ptr<crosapi::TaskManagerLacros> task_manager_provider_;
// Receiver and cache of drive mount point path updates.
std::unique_ptr<DriveFsCache> drivefs_cache_;
// Sends lacros download information to ash.
std::unique_ptr<DownloadControllerClientLacros> download_controller_client_;
// Sends lacros installation status of force-installed extensions to ash.
std::unique_ptr<ForceInstalledTrackerLacros> force_installed_tracker_;
// Manages the resources used in the web Kiosk session, and sends window
// status changes of lacros-chrome to ash when necessary.
std::unique_ptr<KioskSessionServiceLacros> kiosk_session_service_;
// Handles tab property requests from ash.
std::unique_ptr<crosapi::WebPageInfoProviderLacros> web_page_info_provider_;
// Receives extension app events from ash.
std::unique_ptr<LacrosExtensionAppsController> extension_apps_controller_;
// Sends extension app events to ash.
std::unique_ptr<LacrosExtensionAppsPublisher> extension_apps_publisher_;
// Receiver of field trial updates.
std::unique_ptr<FieldTrialObserver> field_trial_observer_;
// Shows a butter bar on the first window.
std::unique_ptr<LacrosButterBar> butter_bar_;
// Receives orientation lock data.
std::unique_ptr<content::ScreenOrientationDelegate>
screen_orientation_delegate_;
};
#endif // CHROME_BROWSER_LACROS_CHROME_BROWSER_MAIN_EXTRA_PARTS_LACROS_H_
| 34.715909 | 79 | 0.819967 |
f76345572eef8137987ef71ae225acbbcbe04abb | 558 | h | C | payload/sp/storage/LogFile.h | StarMKWii/mkw-sp | e87fec9cdfc920fbe10b9680fc34cfe9a9ad2426 | [
"MIT"
] | 24 | 2022-01-31T00:35:29.000Z | 2022-03-20T17:03:04.000Z | payload/sp/storage/LogFile.h | StarMKWii/mkw-sp | e87fec9cdfc920fbe10b9680fc34cfe9a9ad2426 | [
"MIT"
] | 135 | 2022-01-31T09:24:26.000Z | 2022-03-31T19:49:07.000Z | payload/sp/storage/LogFile.h | StarMKWii/mkw-sp | e87fec9cdfc920fbe10b9680fc34cfe9a9ad2426 | [
"MIT"
] | 13 | 2022-01-31T04:10:22.000Z | 2022-03-26T10:06:41.000Z | #pragma once
#include <revolution.h>
#include <stdarg.h>
void LogFile_init(void);
void LogFile_vprintf(const char *restrict format, va_list args);
typedef struct ThreadNode ThreadNode;
struct ThreadNode {
OSThread *thread;
ThreadNode *next;
};
typedef struct {
ThreadNode node;
} LogFileDisableGuard;
void LogFile_disable(LogFileDisableGuard *guard);
void LogFile_restore(LogFileDisableGuard *guard);
#define LOG_FILE_DISABLE() \
LogFileDisableGuard _guard __attribute__((cleanup(LogFile_restore))); \
LogFile_disable(&_guard);
| 19.241379 | 75 | 0.765233 |
a19ff84d848c690aff805abcc373c0ef8e009245 | 1,950 | c | C | student-distrib/i8259.c | JiyuuuHuuu/ECE_391_MP3 | 5eb166e99e4a15045e4ed9cb59e51569f5976a81 | [
"AFL-1.1"
] | 2 | 2020-12-15T09:49:45.000Z | 2020-12-31T13:36:35.000Z | student-distrib/i8259.c | JiyuuuHuuu/ECE_391_MP3 | 5eb166e99e4a15045e4ed9cb59e51569f5976a81 | [
"AFL-1.1"
] | null | null | null | student-distrib/i8259.c | JiyuuuHuuu/ECE_391_MP3 | 5eb166e99e4a15045e4ed9cb59e51569f5976a81 | [
"AFL-1.1"
] | null | null | null | /* i8259.c - Functions to interact with the 8259 interrupt controller
* vim:ts=4 noexpandtab
*/
#include "i8259.h"
#include "lib.h"
// #include <linux/spinlock.h>
//static spinlock_t PIC_lock = SPIN_LOCK_UNLOCKED;
/* Interrupt masks to determine which interrupts are enabled and disabled */
static uint8_t master_mask = 0xff; /* IRQs 0-7 */
static uint8_t slave_mask = 0xff; /* IRQs 8-15 */
/* Initialize the 8259 PIC */
void i8259_init(void) {
// unsigned long flags;
outb(master_mask, MASTER_8259_PORT+1);
outb(slave_mask, SLAVE_8259_PORT+1);
outb(ICW1, MASTER_8259_PORT);
outb(ICW2_MASTER, MASTER_8259_PORT+1);
outb(ICW3_MASTER, MASTER_8259_PORT+1);
outb(ICW4, MASTER_8259_PORT+1);
outb(ICW1, SLAVE_8259_PORT);
outb(ICW2_SLAVE, SLAVE_8259_PORT+1);
outb(ICW3_SLAVE, SLAVE_8259_PORT+1);
outb(ICW4, SLAVE_8259_PORT+1);
outb(master_mask, MASTER_8259_PORT+1);
outb(slave_mask, SLAVE_8259_PORT+1);
enable_irq(2);
}
/* Disnable (mask) the specified IRQ */
void disable_irq(uint32_t irq_num) {
if(irq_num > 7){
irq_num -= 8;
slave_mask |= 1 << irq_num;
outb(slave_mask, SLAVE_8259_PORT+1);
}else{
master_mask |= 1 << irq_num;
outb(master_mask, MASTER_8259_PORT+1);
}
}
/* Enable (unmask) the specified IRQ */
void enable_irq(uint32_t irq_num) {
if(irq_num > 7){
irq_num -= 8;
slave_mask &= ~(1 << irq_num);
outb(slave_mask, SLAVE_8259_PORT+1);
}else{
master_mask &= ~(1 << irq_num);
outb(master_mask, MASTER_8259_PORT+1);
}
// spin_unlock_irqrestore(&PIC_lock, flags);
}
/* Send end-of-interrupt signal for the specified IRQ */
void send_eoi(uint32_t irq_num) {
if(irq_num >= ICW2_MASTER) irq_num -= ICW2_MASTER;
//Determine if the irq goes to slave or master
if(irq_num > 7){
irq_num -= 8;
outb(EOI | irq_num, SLAVE_8259_PORT);
}else{
outb(EOI | irq_num, MASTER_8259_PORT);
}
}
| 28.676471 | 76 | 0.672821 |
59b9551fa472b343df922940f4c201cbb7ee713e | 2,343 | h | C | KSRouter/KSRouterNavigationController.h | krin-san/KSRouter | 81ecfd9b56baaee6be2c7cf6afb1ea95ae24a159 | [
"MIT"
] | 3 | 2015-12-16T06:06:11.000Z | 2016-05-12T07:01:20.000Z | KSRouter/KSRouterNavigationController.h | krin-san/KSRouter | 81ecfd9b56baaee6be2c7cf6afb1ea95ae24a159 | [
"MIT"
] | null | null | null | KSRouter/KSRouterNavigationController.h | krin-san/KSRouter | 81ecfd9b56baaee6be2c7cf6afb1ea95ae24a159 | [
"MIT"
] | null | null | null | //
// KSRouterNavigationController.h
// Copyright (c) 2015 Krin-San. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "KSRouterItem.h"
extern NSString * _Nonnull const kRouterNotification;
extern NSString * _Nonnull const kRouterNotificationTarget;
extern NSString * _Nonnull const kRouterNotificationAnimation;
extern NSString * _Nonnull const kRouterAnimationFade;
extern NSString * _Nonnull const kRouterAnimationPush;
extern NSString * _Nonnull const kRouterAnimationPop;
extern NSString * _Nonnull const kNextRouteKey;
@class KSRouterNavigationController;
@protocol KSRouterDelegate <NSObject>
- (void)router:(KSRouterNavigationController * _Nonnull)router willRouteToViewController:(UIViewController * _Nonnull)destination;
@end
@interface KSRouterNavigationController: UINavigationController
/// Router will handle only requests with the same routerId
@property (nonatomic, strong, readonly, nonnull) NSString *routerId;
/// All of possible routes from current router controller
@property (nonatomic, strong, readonly, nonnull) NSArray *routes;
@property (nonatomic, weak, nullable) id<KSRouterDelegate> routerDelegate;
// Subclassing API
- (void)configureRouter __attribute__((objc_requires_super));
- (NSString * _Nonnull)initialRouteKey;
- (NSString * _Nullable)nextRouteKey;
/// Default error handler
- (void)unrecognizedRoute:(NSString * _Nonnull)routeKey;
// API
- (void)performRouteWithKey:(NSString * _Nonnull)key;
- (void)performRouteWithKey:(NSString * _Nonnull)key animation:(CAAnimation * _Nullable)animation;
- (void)performRouteWithKey:(NSString * _Nonnull)key animation:(CAAnimation * _Nullable)animation segueDestination:(UIViewController * _Nullable)segueVC;
- (void)performRoute:(KSRouterItem * _Nonnull)route withAnimation:(CAAnimation * _Nullable)animation;
- (void)performRoute:(KSRouterItem * _Nonnull)route withAnimation:(CAAnimation * _Nullable)animation segueDestination:(UIViewController * _Nullable)segueVC;
- (NSString * _Nonnull)currentRouteKey;
- (KSRouterItem * _Nullable)routeByKey:(NSString * _Nonnull)key;
// Animations
+ (void)setAnimationDuration:(CFTimeInterval)duration;
+ (CAAnimation * _Nullable)animationByKey:(NSString * _Nonnull)key;
+ (CATransition * _Nonnull)fadeAnimation;
+ (CATransition * _Nonnull)pushAnimation;
+ (CATransition * _Nonnull)popAnimation;
@end
| 36.046154 | 156 | 0.802817 |
d3778ed0164bd21a9ac868488d0dfe78d333361d | 32,132 | c | C | Robot/Libraries/STM8_TouchSensing_Driver/src/stm8l15x_tsl_ct_acquisition.c | sharpe-developer/WiFi-Robot | f3744f41233155f36e1b2348fcf1a2f2ca4d5351 | [
"MIT"
] | null | null | null | Robot/Libraries/STM8_TouchSensing_Driver/src/stm8l15x_tsl_ct_acquisition.c | sharpe-developer/WiFi-Robot | f3744f41233155f36e1b2348fcf1a2f2ca4d5351 | [
"MIT"
] | null | null | null | Robot/Libraries/STM8_TouchSensing_Driver/src/stm8l15x_tsl_ct_acquisition.c | sharpe-developer/WiFi-Robot | f3744f41233155f36e1b2348fcf1a2f2ca4d5351 | [
"MIT"
] | null | null | null | /**
******************************************************************************
* @file stm8l15x_tsl_ct_acquisition.c
* @author MCD Application Team
* @version V2.3.1
* @date 14-February-2011
* @brief STM8 Touch Sensing Library - This file provides all the functions
* to manage the Charge-Transfer acquisition based on STM8L15x devices.
******************************************************************************
* @attention
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2011 STMicroelectronics</center></h2>
*/
/* Includes ------------------------------------------------------------------*/
#include "stm8l15x_tsl_ct_acquisition.h"
#include "stm8_tsl_services.h"
#include "stm8_tsl_conf.h"
#if defined(CHARGE_TRANSFER) && defined(STM8L15X)
/* Memory section ------------------------------------------------------------*/
#if defined(_COSMIC_) && defined(USE_PRAGMA_SECTION)
#pragma section [TSL_IO_RAM]
#pragma section @tiny [TSL_IO_RAM0]
#pragma section const {TSL_IO_CONST}
#pragma section (TSL_IO_CODE)
#endif
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
//define the init value for the channel
#define INIT_VALUE 0x0000
//define the 1st Channel mask
#if SCKEY_P1_CH == CH1
#define SCKEY_P1_MASK (SCKEY_P1_A | SCKEY_P1_B | SCKEY_P1_C | SCKEY_P1_D | SCKEY_P1_E | SCKEY_P1_F | SCKEY_P1_G | SCKEY_P1_H | MKEY_CH1_MASK | ACTIVE_SHIELD_GROUP)
#elif SCKEY_P1_CH == CH2
#define SCKEY_P1_MASK (SCKEY_P1_A | SCKEY_P1_B | SCKEY_P1_C | SCKEY_P1_D | SCKEY_P1_E | SCKEY_P1_F | SCKEY_P1_G | SCKEY_P1_H | MKEY_CH2_MASK | ACTIVE_SHIELD_GROUP)
#else //SCKEY_P1_CH == CH3
#define SCKEY_P1_MASK (SCKEY_P1_A | SCKEY_P1_B | SCKEY_P1_C | SCKEY_P1_D | SCKEY_P1_E | SCKEY_P1_F | SCKEY_P1_G | SCKEY_P1_H | MKEY_CH3_MASK | ACTIVE_SHIELD_GROUP)
#endif
//define the 2nd Channel mask
#if (NUMBER_OF_ACQUISITION_PORTS > 1)
#if SCKEY_P2_CH == CH1
#define SCKEY_P2_MASK (SCKEY_P2_A | SCKEY_P2_B | SCKEY_P2_C | SCKEY_P2_D | SCKEY_P2_E | SCKEY_P2_F | SCKEY_P2_G | SCKEY_P2_H | MKEY_CH1_MASK | ACTIVE_SHIELD_GROUP)
#elif SCKEY_P2_CH == CH2
#define SCKEY_P2_MASK (SCKEY_P2_A | SCKEY_P2_B | SCKEY_P2_C | SCKEY_P2_D | SCKEY_P2_E | SCKEY_P2_F | SCKEY_P2_G | SCKEY_P2_H | MKEY_CH2_MASK | ACTIVE_SHIELD_GROUP)
#else //SCKEY_P2_CH == CH3
#define SCKEY_P2_MASK (SCKEY_P2_A | SCKEY_P2_B | SCKEY_P2_C | SCKEY_P2_D | SCKEY_P2_E | SCKEY_P2_F | SCKEY_P2_G | SCKEY_P2_H | MKEY_CH3_MASK | ACTIVE_SHIELD_GROUP)
#endif
#else
#define SCKEY_P2_MASK (0)
#endif
//define the SAMPLING capacitor channel mask
#define SAMP_CAP_MASK (SCKEY_P1_MASK | SCKEY_P2_MASK)
#if (SCKEY_P1_CH == CH1)
#define CCMR_P1 (RI->IOCMR1)
#define IOSR_P1 (RI->IOSR1)
#define CGCR_P1_PP_LOW_MASK (0x00)
#define CGCR_P1_PP_HIGH_MASK (0x01)
#define CGCR_P1_SW_OPEN_MASK (0x02)
#define CGCR_P1_SW_CLOSE_MASK (0x03)
#define CGCR_P1_GLOBAL_MASK (0xFC)
#elif (SCKEY_P1_CH == CH2)
#define CCMR_P1 (RI->IOCMR2)
#define IOSR_P1 (RI->IOSR2)
#define CGCR_P1_PP_LOW_MASK (0x00)
#define CGCR_P1_PP_HIGH_MASK (0x04)
#define CGCR_P1_SW_OPEN_MASK (0x08)
#define CGCR_P1_SW_CLOSE_MASK (0x0C)
#define CGCR_P1_GLOBAL_MASK (0xF3)
#else //(SCKEY_P1_CH == CH3)
#define CCMR_P1 (RI->IOCMR3)
#define IOSR_P1 (RI->IOSR3)
#define CGCR_P1_PP_LOW_MASK (0x00)
#define CGCR_P1_PP_HIGH_MASK (0x10)
#define CGCR_P1_SW_OPEN_MASK (0x20)
#define CGCR_P1_SW_CLOSE_MASK (0x30)
#define CGCR_P1_GLOBAL_MASK (0xCF)
#endif
#if NUMBER_OF_ACQUISITION_PORTS > 1
#if (SCKEY_P2_CH == CH1)
#define CCMR_P2 (RI->IOCMR1)
#define IOSR_P2 (RI->IOSR1)
#define CGCR_P2_PP_LOW_MASK (0x00)
#define CGCR_P2_PP_HIGH_MASK (0x01)
#define CGCR_P2_SW_OPEN_MASK (0x02)
#define CGCR_P2_SW_CLOSE_MASK (0x03)
#define CGCR_P2_GLOBAL_MASK (0xFC)
#elif (SCKEY_P2_CH == CH2)
#define CCMR_P2 (RI->IOCMR2)
#define IOSR_P2 (RI->IOSR2)
#define CGCR_P2_PP_LOW_MASK (0x00)
#define CGCR_P2_PP_HIGH_MASK (0x04)
#define CGCR_P2_SW_OPEN_MASK (0x08)
#define CGCR_P2_SW_CLOSE_MASK (0x0C)
#define CGCR_P2_GLOBAL_MASK (0xF3)
#else //(SCKEY_P2_CH == CH3)
#define CCMR_P2 (RI->IOCMR3)
#define IOSR_P2 (RI->IOSR3)
#define CGCR_P2_PP_LOW_MASK (0x00)
#define CGCR_P2_PP_HIGH_MASK (0x10)
#define CGCR_P2_SW_OPEN_MASK (0x20)
#define CGCR_P2_SW_CLOSE_MASK (0x30)
#define CGCR_P2_GLOBAL_MASK (0xCF)
#endif
#endif
#if (SAMP_CAP_CH == CH1)
#define CCMR_SAMP (RI->IOCMR1)
#define IOSR_SAMP (RI->IOSR1)
#define CSR_SAMP (RI->IOIR1)
#define CGCR_SAMP_PP_LOW_MASK (0x00)
#define CGCR_SAMP_PP_HIGH_MASK (0x01)
#define CGCR_SAMP_SW_OPEN_MASK (0x02)
#define CGCR_SAMP_SW_CLOSE_MASK (0x03)
#define CGCR_SAMP_GLOBAL_MASK (0xFC)
#elif (SAMP_CAP_CH == CH2)
#define CCMR_SAMP (RI->IOCMR2)
#define IOSR_SAMP (RI->IOSR2)
#define CSR_SAMP (RI->IOIR2)
#define CGCR_SAMP_PP_LOW_MASK (0x00)
#define CGCR_SAMP_PP_HIGH_MASK (0x04)
#define CGCR_SAMP_SW_OPEN_MASK (0x08)
#define CGCR_SAMP_SW_CLOSE_MASK (0x0C)
#define CGCR_SAMP_GLOBAL_MASK (0xF3)
#else //(SCKEY_SAMP_CH == CH3)
#define CCMR_SAMP (RI->IOCMR3)
#define IOSR_SAMP (RI->IOSR3)
#define CSR_SAMP (RI->IOIR3)
#define CGCR_SAMP_PP_LOW_MASK (0x00)
#define CGCR_SAMP_PP_HIGH_MASK (0x10)
#define CGCR_SAMP_SW_OPEN_MASK (0x20)
#define CGCR_SAMP_SW_CLOSE_MASK (0x30)
#define CGCR_SAMP_GLOBAL_MASK (0xCF)
#endif
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
#if SPREAD_SPECTRUM
#if SW_SPREAD_SPECTRUM
static u8 SpreadCounter;
#endif //SW_SPREAD_SPECTRUM
u8 Previous_calibration_value;
#endif //SPREAD_SPECTRUM
TOUCH_PORT_Info_T TINY sTouchIO;
u16 TINY CounterStop;
u8 TINY SamplingShifter;
u8 TINY AcquisitionBitMask;
Info_Channel Channel_P1;
Info_Channel Channel_P2;
Info_Channel Channel_P3;
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* This table is always defined */
#if NUMBER_OF_SINGLE_CHANNEL_PORTS > 0
CONST u8 Table_SCKEY_P1[SCKEY_P1_KEY_COUNT] =
{
#if (SCKEY_P1_A == GROUP1)
0x00
#elif (SCKEY_P1_A == GROUP2)
0x01
#elif (SCKEY_P1_A == GROUP3)
0x02
#elif (SCKEY_P1_A == GROUP4)
0x03
#elif (SCKEY_P1_A == GROUP5)
0x04
#elif (SCKEY_P1_A == GROUP6)
0x05
#elif (SCKEY_P1_A == GROUP7)
0x06
#elif (SCKEY_P1_A == GROUP8)
0x07
#endif
#if SCKEY_P1_KEY_COUNT > 1
#if (SCKEY_P1_B == GROUP1)
, 0x00
#elif (SCKEY_P1_B == GROUP2)
, 0x01
#elif (SCKEY_P1_B == GROUP3)
, 0x02
#elif (SCKEY_P1_B == GROUP4)
, 0x03
#elif (SCKEY_P1_B == GROUP5)
, 0x04
#elif (SCKEY_P1_B == GROUP6)
, 0x05
#elif (SCKEY_P1_B == GROUP7)
, 0x06
#elif (SCKEY_P1_B == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P1_KEY_COUNT > 2
#if (SCKEY_P1_C == GROUP1)
, 0x00
#elif (SCKEY_P1_C == GROUP2)
, 0x01
#elif (SCKEY_P1_C == GROUP3)
, 0x02
#elif (SCKEY_P1_C == GROUP4)
, 0x03
#elif (SCKEY_P1_C == GROUP5)
, 0x04
#elif (SCKEY_P1_C == GROUP6)
, 0x05
#elif (SCKEY_P1_C == GROUP7)
, 0x06
#elif (SCKEY_P1_C == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P1_KEY_COUNT > 3
#if (SCKEY_P1_D == GROUP1)
, 0x00
#elif (SCKEY_P1_D == GROUP2)
, 0x01
#elif (SCKEY_P1_D == GROUP3)
, 0x02
#elif (SCKEY_P1_D == GROUP4)
, 0x03
#elif (SCKEY_P1_D == GROUP5)
, 0x04
#elif (SCKEY_P1_D == GROUP6)
, 0x05
#elif (SCKEY_P1_D == GROUP7)
, 0x06
#elif (SCKEY_P1_D == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P1_KEY_COUNT > 4
#if (SCKEY_P1_E == GROUP1)
, 0x00
#elif (SCKEY_P1_E == GROUP2)
, 0x01
#elif (SCKEY_P1_E == GROUP3)
, 0x02
#elif (SCKEY_P1_E == GROUP4)
, 0x03
#elif (SCKEY_P1_E == GROUP5)
, 0x04
#elif (SCKEY_P1_E == GROUP6)
, 0x05
#elif (SCKEY_P1_E == GROUP7)
, 0x06
#elif (SCKEY_P1_E == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P1_KEY_COUNT > 5
#if (SCKEY_P1_F == GROUP1)
, 0x00
#elif (SCKEY_P1_F == GROUP2)
, 0x01
#elif (SCKEY_P1_F == GROUP3)
, 0x02
#elif (SCKEY_P1_F == GROUP4)
, 0x03
#elif (SCKEY_P1_F == GROUP5)
, 0x04
#elif (SCKEY_P1_F == GROUP6)
, 0x05
#elif (SCKEY_P1_F == GROUP7)
, 0x06
#elif (SCKEY_P1_F == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P1_KEY_COUNT > 6
#if (SCKEY_P1_G == GROUP1)
, 0x00
#elif (SCKEY_P1_G == GROUP2)
, 0x01
#elif (SCKEY_P1_G == GROUP3)
, 0x02
#elif (SCKEY_P1_G == GROUP4)
, 0x03
#elif (SCKEY_P1_G == GROUP5)
, 0x04
#elif (SCKEY_P1_G == GROUP6)
, 0x05
#elif (SCKEY_P1_G == GROUP7)
, 0x06
#elif (SCKEY_P1_G == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P1_KEY_COUNT > 7
#if (SCKEY_P1_H == GROUP1)
, 0x00
#elif (SCKEY_P1_H == GROUP2)
, 0x01
#elif (SCKEY_P1_H == GROUP3)
, 0x02
#elif (SCKEY_P1_H == GROUP4)
, 0x03
#elif (SCKEY_P1_H == GROUP5)
, 0x04
#elif (SCKEY_P1_H == GROUP6)
, 0x05
#elif (SCKEY_P1_H == GROUP7)
, 0x06
#elif (SCKEY_P1_H == GROUP8)
, 0x07
#endif
#endif
};
#endif
#if NUMBER_OF_SINGLE_CHANNEL_PORTS > 1
CONST u8 Table_SCKEY_P2[SCKEY_P2_KEY_COUNT] =
{
#if (SCKEY_P2_A == GROUP1)
0x00
#elif (SCKEY_P2_A == GROUP2)
0x01
#elif (SCKEY_P2_A == GROUP3)
0x02
#elif (SCKEY_P2_A == GROUP4)
0x03
#elif (SCKEY_P2_A == GROUP5)
0x04
#elif (SCKEY_P2_A == GROUP6)
0x05
#elif (SCKEY_P2_A == GROUP7)
0x06
#elif (SCKEY_P2_A == GROUP8)
0x07
#endif
#if SCKEY_P2_KEY_COUNT > 1
#if (SCKEY_P2_B == GROUP1)
, 0x00
#elif (SCKEY_P2_B == GROUP2)
, 0x01
#elif (SCKEY_P2_B == GROUP3)
, 0x02
#elif (SCKEY_P2_B == GROUP4)
, 0x03
#elif (SCKEY_P2_B == GROUP5)
, 0x04
#elif (SCKEY_P2_B == GROUP6)
, 0x05
#elif (SCKEY_P2_B == GROUP7)
, 0x06
#elif (SCKEY_P2_B == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P2_KEY_COUNT > 2
#if (SCKEY_P2_C == GROUP1)
, 0x00
#elif (SCKEY_P2_C == GROUP2)
, 0x01
#elif (SCKEY_P2_C == GROUP3)
, 0x02
#elif (SCKEY_P2_C == GROUP4)
, 0x03
#elif (SCKEY_P2_C == GROUP5)
, 0x04
#elif (SCKEY_P2_C == GROUP6)
, 0x05
#elif (SCKEY_P2_C == GROUP7)
, 0x06
#elif (SCKEY_P2_C == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P2_KEY_COUNT > 3
#if (SCKEY_P2_D == GROUP1)
, 0x00
#elif (SCKEY_P2_D == GROUP2)
, 0x01
#elif (SCKEY_P2_D == GROUP3)
, 0x02
#elif (SCKEY_P2_D == GROUP4)
, 0x03
#elif (SCKEY_P2_D == GROUP5)
, 0x04
#elif (SCKEY_P2_D == GROUP6)
, 0x05
#elif (SCKEY_P2_D == GROUP7)
, 0x06
#elif (SCKEY_P2_D == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P2_KEY_COUNT > 4
#if (SCKEY_P2_E == GROUP1)
, 0x00
#elif (SCKEY_P2_E == GROUP2)
, 0x01
#elif (SCKEY_P2_E == GROUP3)
, 0x02
#elif (SCKEY_P2_E == GROUP4)
, 0x03
#elif (SCKEY_P2_E == GROUP5)
, 0x04
#elif (SCKEY_P2_E == GROUP6)
, 0x05
#elif (SCKEY_P2_E == GROUP7)
, 0x06
#elif (SCKEY_P2_E == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P2_KEY_COUNT > 5
#if (SCKEY_P2_F == GROUP1)
, 0x00
#elif (SCKEY_P2_F == GROUP2)
, 0x01
#elif (SCKEY_P2_F == GROUP3)
, 0x02
#elif (SCKEY_P2_F == GROUP4)
, 0x03
#elif (SCKEY_P2_F == GROUP5)
, 0x04
#elif (SCKEY_P2_F == GROUP6)
, 0x05
#elif (SCKEY_P2_F == GROUP7)
, 0x06
#elif (SCKEY_P2_F == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P2_KEY_COUNT > 6
#if (SCKEY_P2_G == GROUP1)
, 0x00
#elif (SCKEY_P2_G == GROUP2)
, 0x01
#elif (SCKEY_P2_G == GROUP3)
, 0x02
#elif (SCKEY_P2_G == GROUP4)
, 0x03
#elif (SCKEY_P2_G == GROUP5)
, 0x04
#elif (SCKEY_P2_G == GROUP6)
, 0x05
#elif (SCKEY_P2_G == GROUP7)
, 0x06
#elif (SCKEY_P2_G == GROUP8)
, 0x07
#endif
#endif
#if SCKEY_P2_KEY_COUNT > 7
#if (SCKEY_P2_H == GROUP1)
, 0x00
#elif (SCKEY_P2_H == GROUP2)
, 0x01
#elif (SCKEY_P2_H == GROUP3)
, 0x02
#elif (SCKEY_P2_H == GROUP4)
, 0x03
#elif (SCKEY_P2_H == GROUP5)
, 0x04
#elif (SCKEY_P2_H == GROUP6)
, 0x05
#elif (SCKEY_P2_H == GROUP7)
, 0x06
#elif (SCKEY_P2_H == GROUP8)
, 0x07
#endif
#endif
};
#endif
/* Table_SCKEY_BITS contents the individual masks for the port acquisitions */
#if NUMBER_OF_SINGLE_CHANNEL_KEYS > 0
CONST u8 Table_SCKEY_BITS[
SCKEY_P1_KEY_COUNT
#if NUMBER_OF_SINGLE_CHANNEL_PORTS > 1
+ SCKEY_P2_KEY_COUNT
#endif
#if NUMBER_OF_SINGLE_CHANNEL_PORTS > 2
+ SCKEY_P3_KEY_COUNT
#endif
] =
{
SCKEY_P1_A /* Always defined */
#if SCKEY_P1_KEY_COUNT > 1
, SCKEY_P1_B
#endif
#if SCKEY_P1_KEY_COUNT > 2
, SCKEY_P1_C
#endif
#if SCKEY_P1_KEY_COUNT > 3
, SCKEY_P1_D
#endif
#if SCKEY_P1_KEY_COUNT > 4
, SCKEY_P1_E
#endif
#if SCKEY_P1_KEY_COUNT > 5
, SCKEY_P1_F
#endif
#if SCKEY_P1_KEY_COUNT > 6
, SCKEY_P1_G
#endif
#if SCKEY_P1_KEY_COUNT > 7
, SCKEY_P1_H
#endif
#if NUMBER_OF_SINGLE_CHANNEL_PORTS > 1
, SCKEY_P2_A
#if SCKEY_P2_KEY_COUNT > 1
, SCKEY_P2_B
#endif
#if SCKEY_P2_KEY_COUNT > 2
, SCKEY_P2_C
#endif
#if SCKEY_P2_KEY_COUNT > 3
, SCKEY_P2_D
#endif
#if SCKEY_P2_KEY_COUNT > 4
, SCKEY_P2_E
#endif
#if SCKEY_P2_KEY_COUNT > 5
, SCKEY_P2_F
#endif
#if SCKEY_P2_KEY_COUNT > 6
, SCKEY_P2_G
#endif
#if SCKEY_P2_KEY_COUNT > 7
, SCKEY_P2_H
#endif
#endif
#if NUMBER_OF_SINGLE_CHANNEL_PORTS > 2
, SCKEY_P3_A
#if SCKEY_P3_KEY_COUNT > 1
, SCKEY_P3_B
#endif
#if SCKEY_P3_KEY_COUNT > 2
, SCKEY_P3_C
#endif
#if SCKEY_P3_KEY_COUNT > 3
, SCKEY_P3_D
#endif
#if SCKEY_P3_KEY_COUNT > 4
, SCKEY_P3_E
#endif
#if SCKEY_P3_KEY_COUNT > 5
, SCKEY_P3_F
#endif
#if SCKEY_P3_KEY_COUNT > 6
, SCKEY_P3_G
#endif
#if SCKEY_P3_KEY_COUNT > 7
, SCKEY_P3_H
#endif
#endif
};
#endif
#if NUMBER_OF_MULTI_CHANNEL_KEYS > 0
CONST u16 Table_MCKEY_PORTS[
#if NUMBER_OF_MULTI_CHANNEL_KEYS == 1
CHANNEL_PER_MCKEY
#endif
#if NUMBER_OF_MULTI_CHANNEL_KEYS == 2
CHANNEL_PER_MCKEY + CHANNEL_PER_MCKEY
#endif
] =
{
MCKEY1_A_CH
, MCKEY1_B_CH
, MCKEY1_C_CH
#if CHANNEL_PER_MCKEY > 3
, MCKEY1_D_CH
, MCKEY1_E_CH
#endif
#if CHANNEL_PER_MCKEY > 5
, MCKEY1_F_CH
, MCKEY1_G_CH
, MCKEY1_H_CH
#endif
#if NUMBER_OF_MULTI_CHANNEL_KEYS > 1
, MCKEY2_A_CH
, MCKEY2_B_CH
, MCKEY2_C_CH
#if CHANNEL_PER_MCKEY > 3
, MCKEY2_D_CH
, MCKEY2_E_CH
#endif
#if CHANNEL_PER_MCKEY > 5
, MCKEY2_F_CH
, MCKEY2_G_CH
, MCKEY2_H_CH
#endif
#endif
};
#endif
#if NUMBER_OF_MULTI_CHANNEL_KEYS > 0
CONST u8 Table_MCKEY_BITS[
#if NUMBER_OF_MULTI_CHANNEL_KEYS == 1
CHANNEL_PER_MCKEY
#elif NUMBER_OF_MULTI_CHANNEL_KEYS == 2
CHANNEL_PER_MCKEY + CHANNEL_PER_MCKEY
#endif
] =
{
MCKEY1_A
, MCKEY1_B
, MCKEY1_C
#if CHANNEL_PER_MCKEY > 3
, MCKEY1_D
, MCKEY1_E
#endif
#if CHANNEL_PER_MCKEY > 5
, MCKEY1_F
, MCKEY1_G
, MCKEY1_H
#endif
#if NUMBER_OF_MULTI_CHANNEL_KEYS > 1
, MCKEY2_A
, MCKEY2_B
, MCKEY2_C
#if CHANNEL_PER_MCKEY > 3
, MCKEY2_D
, MCKEY2_E
#endif
#if CHANNEL_PER_MCKEY > 5
, MCKEY2_F
, MCKEY2_G
, MCKEY2_H
#endif
#endif
};
#endif
#if SPREAD_SPECTRUM && SW_SPREAD_SPECTRUM
/**
******************************************************************************
* @brief Spread Spectrum waiting routine. A variable delay is
* inserted between each step.
* @par Parameters:
* None
* @retval void None
* @par Required preconditions:
* SPREAD_SPECTRUM must be defined and not null in the configuration file
* SW_SPREAD_SPECTRUM must be defined and not null in the configuration file
******************************************************************************
*/
INLINE void TSL_SW_Spread_Spectrum(void)
{
u8 i;
SpreadCounter++;
if (SpreadCounter == SPREAD_COUNTER_MAX)
{
SpreadCounter = SPREAD_COUNTER_MIN;
}
i = SpreadCounter;
while (--i);
}
#endif /* SPREAD_SPECTRUM && SW_SPREAD_SPECTRUM */
/**
******************************************************************************
* @brief Init for I/Os used in the application. Used for SW I/O toggling.
* If the hardware cell is used, the responsability of the I/O configuration is
* given to the user layer.
* @par Parameters:
* None
* @retval void None
* @par Required preconditions:
* None
******************************************************************************
*/
void TSL_IO_Init(void)
{
/*init the IO to use with the TS controller registers*/
/*Enable the TS IP clcock*/
CLK->PCKENR2 |= 0x20;
/*initialization of TS IP*/
//select which IOs will be managed by the TS IP
CCMR_P1 = SCKEY_P1_MASK;
#if NUMBER_OF_ACQUISITION_PORTS > 1
CCMR_P2 = SCKEY_P2_MASK;
#endif
CCMR_SAMP = SAMP_CAP_MASK;
//select which channel will be enabled
IOSR_P1 = SCKEY_P1_MASK;
#if NUMBER_OF_ACQUISITION_PORTS > 1
IOSR_P2 = SCKEY_P2_MASK;
#endif
IOSR_SAMP = SAMP_CAP_MASK;
#if ACTIVE_SHIELD_GROUP
ACTIVE_SHIELD_P1_PORT->DDR &= (uint8_t)(~ACTIVE_SHIELD_P1_BIT);
ACTIVE_SHIELD_P1_PORT->CR1 &= (uint8_t)(~ACTIVE_SHIELD_P1_BIT);
ACTIVE_SHIELD_P2_PORT->DDR &= (uint8_t)(~ACTIVE_SHIELD_P2_BIT);
ACTIVE_SHIELD_P2_PORT->CR1 &= (uint8_t)(~ACTIVE_SHIELD_P2_BIT);
#endif
TSL_IO_Clamp();
}
/**
******************************************************************************
* @brief Put All Sensing I/Os in ouput mode at 0.
* @par Parameters:
* None
* @retval void None
* @par Required preconditions:
* None
******************************************************************************
*/
void TSL_IO_Clamp(void)
{
//All IO in input with the analog switch OPEN
RI->IOGCR = CGCR_P1_SW_OPEN_MASK | CGCR_SAMP_SW_OPEN_MASK
#if NUMBER_OF_ACQUISITION_PORTS > 1
| CGCR_P2_SW_OPEN_MASK
#endif
;
//All IO to pushpull LOW for discharging all capacitors (Ctouch and Csense)
RI->IOGCR = CGCR_P1_PP_LOW_MASK | CGCR_SAMP_PP_LOW_MASK
#if NUMBER_OF_ACQUISITION_PORTS > 1
| CGCR_P2_PP_LOW_MASK
#endif
;
//wait for good discharging of all capacitors
{u16 i;
for (i = 0; i < 2000 ;i++) {}
}
//All IO in input with the analog switch OPEN
RI->IOGCR = CGCR_P1_SW_OPEN_MASK | CGCR_SAMP_SW_OPEN_MASK
#if NUMBER_OF_ACQUISITION_PORTS > 1
| CGCR_P2_SW_OPEN_MASK
#endif
;
//close the analog switch of the channel used for the sampling capacitor
//RI->IOGCR = CGCR_SAMP_SW_CLOSE_MASK;
}
/**
******************************************************************************
* @brief Acquisition function for the 1st Channel IO of each group
* @param[in] AcqNumber Number of times the acquisition is done.
* @param[in] AdjustmentLevel Used to adjust the measured level.
* @retval void None
* @par Required preconditions:
* None
******************************************************************************
*/
void TSL_IO_Acquisition_P1(u16 MaxAcqNumber)
{
u16 MeasurementCounter;
#if SPREAD_SPECTRUM && !SW_SPREAD_SPECTRUM
u8 HSI_fact_Calib;
#endif
Channel_P1.Measure[0] = INIT_VALUE;
Channel_P1.Measure[1] = INIT_VALUE;
Channel_P1.Measure[2] = INIT_VALUE;
Channel_P1.Measure[3] = INIT_VALUE;
Channel_P1.Measure[4] = INIT_VALUE;
Channel_P1.Measure[5] = INIT_VALUE;
Channel_P1.Measure[6] = INIT_VALUE;
Channel_P1.Measure[7] = INIT_VALUE;
#if (ACTIVE_SHIELD_GROUP)
CCMR_P1 |= ACTIVE_SHIELD_GROUP;
#if NUMBER_OF_ACQUISITION_PORTS > 1
CCMR_P2 &= (uint8_t)(~ACTIVE_SHIELD_GROUP);
#endif
#endif
//P1 and Sampling capacitor IOs in input with the analog switch OPEN
RI->IOGCR = (u8)((RI->IOGCR & (CGCR_P1_GLOBAL_MASK & CGCR_SAMP_GLOBAL_MASK)) | (CGCR_P1_SW_OPEN_MASK | CGCR_SAMP_SW_OPEN_MASK));
//close the analog switch of the channel used for the sampling capacitor
RI->IOGCR |= CGCR_SAMP_SW_CLOSE_MASK;
Channel_P1.State.whole = 0x00;
/*reset the counter*/
MeasurementCounter = 0x0000;
/*START spread spectrum*/
#if SPREAD_SPECTRUM && !SW_SPREAD_SPECTRUM
/*save the user application calibration value*/
if (CLK->HSITRIMR != 0x00) /*the application use the Triming register*/
{
Previous_calibration_value = CLK->HSITRIMR;
}
else /*the application doesn't use the trimming register*/
{
Previous_calibration_value = CLK->HSICALR;
}
HSI_fact_Calib = CLK->HSICALR;
CLK->HSIUNLCKR = 0xAC;
CLK->HSIUNLCKR = 0x35;
CLK->HSITRIMR = HSI_fact_Calib;
#endif
/*loop while all the 1st channel of each group have not reach the VIH level*/
do
{
/*charging the Ctouch cap with connecting the IO to Vdd (IO in push-pull HIGH)*/
RI->IOGCR = (u8)((RI->IOGCR & CGCR_P1_GLOBAL_MASK) | CGCR_P1_PP_HIGH_MASK);
if (CSR_SAMP & (uint8_t)~Channel_P1.State.whole)
{
/*To guaranty a good charging the high level on Ctouch has to be maintained about 2us.
Instead of performing a waiting loop, the first part of the test to detect if a pin
has reach the VDDIO/2 threshold is performed here.*/
if ((Channel_P1.State.b.Grp1 == 0) && ((CSR_SAMP&Group1) == Group1))
{
Channel_P1.Measure[0] = MeasurementCounter;
Channel_P1.State.whole |= Group1;
}
if ((Channel_P1.State.b.Grp2 == 0) && ((CSR_SAMP&Group2) == Group2))
{
Channel_P1.Measure[1] = MeasurementCounter;
Channel_P1.State.whole |= Group2;
}
if ((Channel_P1.State.b.Grp3 == 0) && ((CSR_SAMP&Group3) == Group3))
{
Channel_P1.Measure[2] = MeasurementCounter;
Channel_P1.State.whole |= Group3;
}
if ((Channel_P1.State.b.Grp4 == 0) && ((CSR_SAMP&Group4) == Group4))
{
Channel_P1.Measure[3] = MeasurementCounter;
Channel_P1.State.whole |= Group4;
}
if ((Channel_P1.State.b.Grp5 == 0) && ((CSR_SAMP&Group5) == Group5))
{
Channel_P1.Measure[4] = MeasurementCounter;
Channel_P1.State.whole |= Group5;
}
if ((Channel_P1.State.b.Grp6 == 0) && ((CSR_SAMP&Group6) == Group6))
{
Channel_P1.Measure[5] = MeasurementCounter;
Channel_P1.State.whole |= Group6;
}
if ((Channel_P1.State.b.Grp7 == 0) && ((CSR_SAMP&Group7) == Group7))
{
Channel_P1.Measure[6] = MeasurementCounter;
Channel_P1.State.whole |= Group7;
}
if ((Channel_P1.State.b.Grp8 == 0) && ((CSR_SAMP&Group8) == Group8))
{
Channel_P1.Measure[7] = MeasurementCounter;
Channel_P1.State.whole |= Group8;
}
}
MeasurementCounter++;
CLWHTA; /**< programmable delay */
/*charging the Csense cap with connecting it to Ctouch by closing the analog switch.
Here the charge is transfered from the Ctouch to the Csens capacitors*/
RI->IOGCR = (u8)((RI->IOGCR & CGCR_P1_GLOBAL_MASK) | CGCR_P1_SW_CLOSE_MASK);
#if SPREAD_SPECTRUM && !SW_SPREAD_SPECTRUM
if (CLK->HSITRIMR > HSI_fact_Calib - SPREAD_COUNTER_MAX)
{
u8 Prev_HSI_TRIM;
Prev_HSI_TRIM = (u8)(CLK->HSITRIMR - 1);
CLK->HSIUNLCKR = 0xAC;
CLK->HSIUNLCKR = 0x35;
CLK->HSITRIMR = Prev_HSI_TRIM;
}
else
{
CLK->HSIUNLCKR = 0xAC;
CLK->HSIUNLCKR = 0x35;
CLK->HSITRIMR = HSI_fact_Calib ;
}
#endif
/*it's better to implement this like that because it's much more faster than to put this test in the "while test" below
and only the MSByte is tested in order to speed the test up */
if ((u8)(MeasurementCounter >> 8) > (u8)(MaxAcqNumber >> 8))
{
break;
}
/*wait for good discharging of the the Ctouch cap in the Csense */
CLWLTA; /**< programmable delay */
#if SPREAD_SPECTRUM && SW_SPREAD_SPECTRUM
TSL_SW_Spread_Spectrum();
#endif
}
while (((Channel_P1.State.whole & Channel_P1.EnabledChannels) != Channel_P1.EnabledChannels));
/*problem with the line above when the MASK is not done.
In fact when the SCKEY_P1_MASK is not performed some unused channels are is detected state */
#if SPREAD_SPECTRUM && !SW_SPREAD_SPECTRUM
/*Restore the user application calibration value*/
CLK->HSIUNLCKR = 0xAC;
CLK->HSIUNLCKR = 0x35;
CLK->HSITRIMR = Previous_calibration_value;
#endif
//P1 and Sampling capacitor IOs in input with the analog switch OPEN
RI->IOGCR = (u8)((RI->IOGCR & (CGCR_P1_GLOBAL_MASK & CGCR_SAMP_GLOBAL_MASK)) | (CGCR_P1_SW_OPEN_MASK | CGCR_SAMP_SW_OPEN_MASK));
//P1 and Sampling capacitors IOs to LOW for discharging
RI->IOGCR = (u8)((RI->IOGCR & (CGCR_P1_GLOBAL_MASK & CGCR_SAMP_GLOBAL_MASK)) | (CGCR_P1_PP_LOW_MASK | CGCR_SAMP_PP_LOW_MASK));
}
/**
******************************************************************************
* @brief Acquisition function for the 1st Channel IO of each group
* @param[in] AcqNumber Number of times the acquisition is done.
* @param[in] AdjustmentLevel Used to adjust the measured level.
* @retval void None
* @par Required preconditions:
* None
******************************************************************************
*/
#if NUMBER_OF_ACQUISITION_PORTS > 1
void TSL_IO_Acquisition_P2(u16 MaxAcqNumber)
{
u16 MeasurementCounter;
#if SPREAD_SPECTRUM && !SW_SPREAD_SPECTRUM
u8 HSI_fact_Calib;
#endif
Channel_P2.Measure[0] = INIT_VALUE;
Channel_P2.Measure[1] = INIT_VALUE;
Channel_P2.Measure[2] = INIT_VALUE;
Channel_P2.Measure[3] = INIT_VALUE;
Channel_P2.Measure[4] = INIT_VALUE;
Channel_P2.Measure[5] = INIT_VALUE;
Channel_P2.Measure[6] = INIT_VALUE;
Channel_P2.Measure[7] = INIT_VALUE;
#if (ACTIVE_SHIELD_GROUP)
CCMR_P2 |= ACTIVE_SHIELD_GROUP;
CCMR_P1 &= (uint8_t)(~ACTIVE_SHIELD_GROUP);
#endif
//P2 and Sampling capacitor IOs in input with the analog switch OPEN
RI->IOGCR = (u8)((RI->IOGCR & (CGCR_P2_GLOBAL_MASK & CGCR_SAMP_GLOBAL_MASK)) | (CGCR_P2_SW_OPEN_MASK | CGCR_SAMP_SW_OPEN_MASK));
//close the analog switch of the channel used for the sampling capacitor
RI->IOGCR |= CGCR_SAMP_SW_CLOSE_MASK;
Channel_P2.State.whole = 0x00;
/*reset the counter*/
MeasurementCounter = 0x0000;
/*START spread spectrum*/
#if SPREAD_SPECTRUM && !SW_SPREAD_SPECTRUM
/*save the user application calibration value*/
if (CLK->HSITRIMR != 0x00) /*the application use the Triming register*/
{
Previous_calibration_value = CLK->HSITRIMR;
}
else /*the application doesn't use the trimming register*/
{
Previous_calibration_value = CLK->HSICALR;
}
HSI_fact_Calib = CLK->HSICALR;
CLK->HSIUNLCKR = 0xAC;
CLK->HSIUNLCKR = 0x35;
CLK->HSITRIMR = HSI_fact_Calib;
#endif
/*loop while all the 1st channel of each group have not reach the VIH level*/
do
{
/*charging the Ctouch cap with connecting the IO to Vdd (IO in push-pull HIGH)*/
RI->IOGCR = (u8)((RI->IOGCR & CGCR_P2_GLOBAL_MASK) | CGCR_P2_PP_HIGH_MASK);
if (CSR_SAMP & (uint8_t)~Channel_P2.State.whole)
{
/*To guaranty a good charging the high level on Ctouch has to be maintained about 2us.
Instead of performing a waiting loop, the first part of the test to detect if a pin
has reach the VDDIO/2 threshold is performed here.*/
if ((Channel_P2.State.b.Grp1 == 0) && ((CSR_SAMP&Group1) == Group1))
{
Channel_P2.Measure[0] = MeasurementCounter;
Channel_P2.State.whole |= Group1;
}
if ((Channel_P2.State.b.Grp2 == 0) && ((CSR_SAMP&Group2) == Group2))
{
Channel_P2.Measure[1] = MeasurementCounter;
Channel_P2.State.whole |= Group2;
}
if ((Channel_P2.State.b.Grp3 == 0) && ((CSR_SAMP&Group3) == Group3))
{
Channel_P2.Measure[2] = MeasurementCounter;
Channel_P2.State.whole |= Group3;
}
if ((Channel_P2.State.b.Grp4 == 0) && ((CSR_SAMP&Group4) == Group4))
{
Channel_P2.Measure[3] = MeasurementCounter;
Channel_P2.State.whole |= Group4;
}
if ((Channel_P2.State.b.Grp5 == 0) && ((CSR_SAMP&Group5) == Group5))
{
Channel_P2.Measure[4] = MeasurementCounter;
Channel_P2.State.whole |= Group5;
}
if ((Channel_P2.State.b.Grp6 == 0) && ((CSR_SAMP&Group6) == Group6))
{
Channel_P2.Measure[5] = MeasurementCounter;
Channel_P2.State.whole |= Group6;
}
if ((Channel_P2.State.b.Grp7 == 0) && ((CSR_SAMP&Group7) == Group7))
{
Channel_P2.Measure[6] = MeasurementCounter;
Channel_P2.State.whole |= Group7;
}
if ((Channel_P2.State.b.Grp8 == 0) && ((CSR_SAMP&Group8) == Group8))
{
Channel_P2.Measure[7] = MeasurementCounter;
Channel_P2.State.whole |= Group8;
}
}
MeasurementCounter++;
CLWHTA; /**< programmable delay */
/*charging the Csense cap with connecting it to Ctouch by closing the analog switch.
Here the charge is transfered from the Ctouch to the Csens capacitors*/
RI->IOGCR = (u8)((RI->IOGCR & CGCR_P2_GLOBAL_MASK) | CGCR_P2_SW_CLOSE_MASK);
#if SPREAD_SPECTRUM && !SW_SPREAD_SPECTRUM
if (CLK->HSITRIMR > HSI_fact_Calib - SPREAD_COUNTER_MAX)
{
u8 Prev_HSI_TRIM;
Prev_HSI_TRIM = (u8)(CLK->HSITRIMR - 1);
CLK->HSIUNLCKR = 0xAC;
CLK->HSIUNLCKR = 0x35;
CLK->HSITRIMR = Prev_HSI_TRIM;
}
else
{
CLK->HSIUNLCKR = 0xAC;
CLK->HSIUNLCKR = 0x35;
CLK->HSITRIMR = HSI_fact_Calib ;
}
#endif
/*it's better to implement this like that because it's much more faster than to put this test in the "while test" below
and only the MSByte is tested in order to speed the test up */
if ((u8)(MeasurementCounter >> 8) > (u8)(MaxAcqNumber >> 8))
{
break;
}
/*wait for good discharging of the the Ctouch cap in the Csense */
CLWLTA; /**< programmable delay */
#if SPREAD_SPECTRUM && SW_SPREAD_SPECTRUM
TSL_SW_Spread_Spectrum();
#endif
}
while (((Channel_P2.State.whole & Channel_P2.EnabledChannels) != Channel_P2.EnabledChannels));
#if SPREAD_SPECTRUM && !SW_SPREAD_SPECTRUM
/*Restore the user application calibration value*/
CLK->HSIUNLCKR = 0xAC;
CLK->HSIUNLCKR = 0x35;
CLK->HSITRIMR = Previous_calibration_value;
#endif
//P2 and Sampling capacitor IOs in input with the analog switch OPEN
RI->IOGCR = (u8)((RI->IOGCR & (CGCR_P2_GLOBAL_MASK & CGCR_SAMP_GLOBAL_MASK)) | (CGCR_P2_SW_OPEN_MASK | CGCR_SAMP_SW_OPEN_MASK));
//P2 and Sampling capacitors IOs to LOW for discharing
RI->IOGCR = (u8)((RI->IOGCR & (CGCR_P2_GLOBAL_MASK & CGCR_SAMP_GLOBAL_MASK)) | (CGCR_P2_PP_LOW_MASK | CGCR_SAMP_PP_LOW_MASK));
}
#endif
#endif
/* Public functions ----------------------------------------------------------*/
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
| 28.536412 | 164 | 0.623148 |
97b807356eb291b455bdfe7ea7032be5aa1e29cc | 324 | h | C | inetsrv/msmq/src/trigger/include/msmqtrigbld.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/msmq/src/trigger/include/msmqtrigbld.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/msmq/src/trigger/include/msmqtrigbld.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //
// file: MSMQTrigbld.h
//
// Copyright (c) 1997-2000 Microsoft Corporation, All Rights Reserved
//
//
// This file is empty on all machines and should be out to the build machine only
// for specific build macro decleration
//
//#define MSMQTRIG_OFFICIAL_BUILD // defined only on the official build machine
| 24.923077 | 82 | 0.712963 |
46c5463aecda7470e19055d7bf276bf8c8589443 | 3,346 | h | C | includes/neuralnetwork.h | roloza7/nn-test | 3400e6e065be68858c6ce692d349f3ddb8596033 | [
"MIT"
] | null | null | null | includes/neuralnetwork.h | roloza7/nn-test | 3400e6e065be68858c6ce692d349f3ddb8596033 | [
"MIT"
] | null | null | null | includes/neuralnetwork.h | roloza7/nn-test | 3400e6e065be68858c6ce692d349f3ddb8596033 | [
"MIT"
] | null | null | null | #ifndef NEURAL_NETWORK_H_
#define NEURAL_NETWORK_H_
#include "activators.h"
#include "sparsematrix.h"
#include "inputbatch.h"
#include "outputbatch.h"
#include <ostream>
#include <cstddef>
using std::size_t;
struct NetworkStructure {
NetworkStructure() = default;
NetworkStructure(size_t network_size);
~NetworkStructure();
void Clear(size_t n_inputs, size_t n_outputs);
size_t network_size_;
vector<vector<double>*> inputs_capacity_;
vector<SparseMatrix<double>*> inputs_weight_;
vector<vector<double>*> outputs_capacity_;
vector<SparseMatrix<double>*> outputs_weight_;
vector<double> inner_capacity_;
vector<double> inner_biases_;
SparseMatrix<double> inner_weights_;
double plasticity_;
double dampening_;
double pruning_;
double synaptogenesis_;
size_t n_inputs_;
size_t n_outputs_;
};
typedef struct NetworkStructure NetworkStructure;
class NeuralNetwork {
public:
NeuralNetwork(unsigned int);
NeuralNetwork(unsigned int, Activators::FunctionType ftype);
~NeuralNetwork();
void SetConstants(double base_weights, double dampening, double plasticity,
double pruning, double synaptogenesis, const std::vector<double>& capacity);
void SetConstants(double base_weights, double dampening, double plasticity,
double pruning, double synaptogenesis);
void Initialise();
void Step();
void FeedData();
void PrintInnerNodes(std::ostream& os);
void PrintInnerWeights(std::ostream& os);
void PrintInputNodes(std::ostream& os);
void PrintInputWeights(std::ostream& os);
void PrintInputCapacities(std::ostream& os);
void PrintOutputNodes(std::ostream& os);
void AddInput(std::vector<double>* input_nodes, std::vector<double>* capacity);
void AddOutput(std::vector<double>* output_nodes, std::vector<double>* capacity);
void StepWeights();
InputBatch& GetInputNodes();
OutputBatch& GetOutputNodes();
SparseMatrix<double>& GetWeights();
vector<double>& GetBiases();
vector<double>& GetCapacities();
void GetStructuralData(NetworkStructure* ns);
void SetStructuralData(NetworkStructure* ns);
double GetDampening();
double Plasticity();
double Pruning();
double Synaptogenesis();
private:
void Propagate();
void Dampen();
void CalculateWeightChange();
double BASE_WEIGHTS;
double BASE_BIASES;
double DAMPENING;
double PLASTICITY;
double PRUNING;
double SYNAPTOGENESIS;
std::vector<double> CAPACITY;
bool initialised_;
size_t size_;
std::vector<double>* inner_nodes_;
SparseMatrix<double>* inner_weights_;
std::vector<double>* working_buffer_;
std::vector<double>* inner_biases_;
InputBatch input_nodes_;
OutputBatch output_nodes_;
double (*activator_)(double);
double (*activator_derivative_)(double);
};
#endif // NEURALNETOWRK_H_ | 30.981481 | 101 | 0.628811 |
ea698d9f9492c86e38d1f274e60803335e3ff475 | 219 | h | C | RecipeBook/RBDefinitions.h | baberthal/RecipeBook | edbda9cade9d60fde6a7551a0ee74f8929bca07e | [
"Apache-2.0"
] | null | null | null | RecipeBook/RBDefinitions.h | baberthal/RecipeBook | edbda9cade9d60fde6a7551a0ee74f8929bca07e | [
"Apache-2.0"
] | null | null | null | RecipeBook/RBDefinitions.h | baberthal/RecipeBook | edbda9cade9d60fde6a7551a0ee74f8929bca07e | [
"Apache-2.0"
] | null | null | null | //
// RBDefinitions.h
// RecipeBook
//
// Created by Morgan Lieberthal on 1/11/16.
// Copyright © 2016 Morgan Lieberthal. All rights reserved.
//
#pragma once
#define kRBRecipeStepDataType @"kRBRecipeStepDataType" | 19.909091 | 60 | 0.730594 |
ee8ef089eda631bb8dab0088e30432a01e7a160b | 1,086 | h | C | src/models/user/user.h | ulqiorra/sign_up_form | 9afdc87d60fafff6ea3cd70cc64539e04ecdf4f6 | [
"MIT"
] | null | null | null | src/models/user/user.h | ulqiorra/sign_up_form | 9afdc87d60fafff6ea3cd70cc64539e04ecdf4f6 | [
"MIT"
] | null | null | null | src/models/user/user.h | ulqiorra/sign_up_form | 9afdc87d60fafff6ea3cd70cc64539e04ecdf4f6 | [
"MIT"
] | null | null | null | #pragma once
#include <QObject>
class User : public QObject
{
Q_OBJECT
Q_PROPERTY(QString first_name READ get_first_name NOTIFY changed)
Q_PROPERTY(QString last_name READ get_last_name NOTIFY changed)
Q_PROPERTY(QString country READ get_country NOTIFY changed)
Q_PROPERTY(QString email READ get_email NOTIFY changed)
Q_PROPERTY(QString password READ get_password NOTIFY changed)
public:
explicit User() = default;
explicit User(const QString& first_name, const QString& last_name,
const QString& country, const QString& email,
const QString& pass);
const QString& get_first_name() const noexcept;
const QString& get_last_name() const noexcept;
const QString& get_country() const noexcept;
const QString& get_email() const noexcept;
const QString& get_password() const noexcept;
signals:
void changed();
private:
QString _first_name;
QString _last_name;
QString _country;
QString _email;
QString _password;
};
| 29.351351 | 71 | 0.683241 |
2d6f9555e8b783a2df480a1031f6f6efecf583be | 1,185 | c | C | py/objmodule.c | komuw/micropython | 501399330ecae4b055120787f08707d4ea1a5532 | [
"MIT"
] | null | null | null | py/objmodule.c | komuw/micropython | 501399330ecae4b055120787f08707d4ea1a5532 | [
"MIT"
] | null | null | null | py/objmodule.c | komuw/micropython | 501399330ecae4b055120787f08707d4ea1a5532 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include "nlr.h"
#include "misc.h"
#include "mpconfig.h"
#include "obj.h"
#include "runtime.h"
#include "map.h"
typedef struct _mp_obj_module_t {
mp_obj_base_t base;
qstr name;
mp_map_t *globals;
} mp_obj_module_t;
void module_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) {
mp_obj_module_t *self = self_in;
print(env, "<module '%s' from '-unknown-file-'>", qstr_str(self->name));
}
const mp_obj_type_t module_type = {
{ &mp_const_type },
"module",
module_print, // print
NULL, // make_new
NULL, // call_n
NULL, // unary_op
NULL, // binary_op
NULL, // getiter
NULL, // iternext
.methods = {{NULL, NULL},},
};
mp_obj_t mp_obj_new_module(qstr module_name) {
mp_obj_module_t *o = m_new_obj(mp_obj_module_t);
o->base.type = &module_type;
o->name = module_name;
o->globals = mp_map_new(MP_MAP_QSTR, 0);
return o;
}
mp_map_t *mp_obj_module_get_globals(mp_obj_t self_in) {
assert(MP_OBJ_IS_TYPE(self_in, &module_type));
mp_obj_module_t *self = self_in;
return self->globals;
}
| 23.7 | 96 | 0.663291 |
8700a10f879f271eb70ffd4bf7233fce42f64c89 | 957 | c | C | projects/power_distribution/src/rear_strobe_blinker.c | Citrusboa/firmware_xiv | 4379cefae900fd67bd14d930da6b8acfce625176 | [
"MIT"
] | 14 | 2019-11-12T00:11:29.000Z | 2021-12-13T05:32:41.000Z | projects/power_distribution/src/rear_strobe_blinker.c | 123Logan321/firmware_xiv | 14468d55753ad62f8a63a9289511e72131443042 | [
"MIT"
] | 191 | 2019-11-12T05:36:58.000Z | 2022-03-21T19:54:46.000Z | projects/power_distribution/src/rear_strobe_blinker.c | 123Logan321/firmware_xiv | 14468d55753ad62f8a63a9289511e72131443042 | [
"MIT"
] | 14 | 2020-06-06T14:43:14.000Z | 2022-03-08T00:48:11.000Z | #include "rear_strobe_blinker.h"
#include "blink_event_generator.h"
#include "pd_events.h"
static BlinkEventGeneratorStorage s_blinker_storage;
StatusCode rear_strobe_blinker_init(RearStrobeBlinkerSettings *settings) {
// Set up the blinker
BlinkEventGeneratorSettings blinker_settings = {
.interval_us = settings->strobe_blink_delay_us,
.event_priority = PD_BPS_STROBE_EVENT_PRIORITY,
.default_state = BLINKER_STATE_OFF, // go back to off when we stop
.callback = NULL,
};
return blink_event_generator_init(&s_blinker_storage, &blinker_settings);
}
StatusCode rear_strobe_blinker_process_event(Event *e) {
if (e->id != PD_STROBE_EVENT) return STATUS_CODE_OK;
bool blinker_on = (e->data != 0); // coalesce nonzero data to on
if (blinker_on) {
return blink_event_generator_start(&s_blinker_storage, PD_GPIO_EVENT_STROBE);
} else {
blink_event_generator_stop(&s_blinker_storage);
return STATUS_CODE_OK;
}
}
| 33 | 81 | 0.77116 |
6e6016d0e1387e507e9765cfa9c120cd1faf12d7 | 405 | c | C | lib/matcalc/pi_newton.c | theoden8/matcalc | ff71e31d5aa854547b1f32280a83486e21a4e6a1 | [
"WTFPL"
] | null | null | null | lib/matcalc/pi_newton.c | theoden8/matcalc | ff71e31d5aa854547b1f32280a83486e21a4e6a1 | [
"WTFPL"
] | null | null | null | lib/matcalc/pi_newton.c | theoden8/matcalc | ff71e31d5aa854547b1f32280a83486e21a4e6a1 | [
"WTFPL"
] | null | null | null | #include "pi_newton.h"
// the newtons formula for pi is
// 1 + 1/3(1 + 2/5(1 + 3/7 + (... )))
void calc_pi_newton(mpfr_t pi, int no_iters, int prec) {
mpfr_t cur;
mpfr_inits2(prec, pi, cur, NULL);
mpfr_set_d(pi, 1.0, MPFR_RNDD);
for(unsigned int i = 0; i < no_iters; ++i) {
// TODO finish
/* mpfr_printf("%d\t%.20RNf\n", i, cur); */
}
mpfr_mul_ui(pi, pi, 4, GMP_RNDU);
mpfr_clear(cur);
}
| 21.315789 | 56 | 0.607407 |
6e864c60f207a597465d64393b2e79a44b832fb1 | 478 | h | C | ios/YelpRecommendation/YelpRecommendation/OldUserFilterViewController.h | raymondwqb/Yelp_Recommendation | bf387bf2579608182a0d7db11eed9e08a28491c5 | [
"MIT"
] | null | null | null | ios/YelpRecommendation/YelpRecommendation/OldUserFilterViewController.h | raymondwqb/Yelp_Recommendation | bf387bf2579608182a0d7db11eed9e08a28491c5 | [
"MIT"
] | null | null | null | ios/YelpRecommendation/YelpRecommendation/OldUserFilterViewController.h | raymondwqb/Yelp_Recommendation | bf387bf2579608182a0d7db11eed9e08a28491c5 | [
"MIT"
] | null | null | null | //
// OldUserFilterViewController.h
// YelpRecommendation
//
// Created by Yi Wu on 12/22/15.
// Copyright © 2015 Qianbo Wang, Yi Wu, Zuyi Wu. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface OldUserFilterViewController : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>
@property (strong, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) NSString *textContent;
@property (weak, nonatomic) IBOutlet UIPickerView *cityfilter;
@end
| 23.9 | 102 | 0.763598 |
dc6410ba0e2bc823f14dca245576b07b2aec32c9 | 881 | c | C | msethax/loader/source/main.c | dona12345/dontools3ds | 54f9c515b49c29f3b17333e3a35d854c3db5838c | [
"BSD-2-Clause"
] | null | null | null | msethax/loader/source/main.c | dona12345/dontools3ds | 54f9c515b49c29f3b17333e3a35d854c3db5838c | [
"BSD-2-Clause"
] | null | null | null | msethax/loader/source/main.c | dona12345/dontools3ds | 54f9c515b49c29f3b17333e3a35d854c3db5838c | [
"BSD-2-Clause"
] | null | null | null | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
void* (*rxTools)() = 0x08000030;
void main()
{
unsigned char* fb1 = (unsigned char*)(0x20184E60);
unsigned char* fb2 = (unsigned char*)(0x201CB370);
unsigned char pure_color = 0x77;
*((unsigned int*)0x080FFFC0) = fb1;
*((unsigned int*)0x080FFFC4) = fb2;
*((unsigned int*)0x080FFFD8) = 0;
unsigned int* buf = 0x20400000;
unsigned int base = 0x67893421;
unsigned int seed = 0x12756342;
for(int i = 0; i < 400*1024/4; i++){
buf[i] ^= base;
base += seed;
}
if(buf[0] != 0xE51FF004) pure_color = 0x00;
unsigned char*src = 0x20400000;
unsigned char*dst = 0x08000000;
for(int i = 0; i < 320*1024; i++){
dst[i] = src[i];
}
for(int i = 0; i < 0x46500; i++){
fb1[i] = pure_color;
fb2[i] = pure_color;
}
*(unsigned int*)0x10000020 = 0;
*(unsigned int*)0x10000020 = 0x340;
rxTools();
}
| 20.97619 | 51 | 0.627696 |
f425a6c7022305f1e96d1a6b1ffd05096ecffb35 | 1,658 | h | C | forks/a_little_smalltalk/src/names.h | zenwerk/littlesmalltalk | 4c9d58891b09bfce8d333b3cf718bbbd349ed246 | [
"BSD-3-Clause"
] | null | null | null | forks/a_little_smalltalk/src/names.h | zenwerk/littlesmalltalk | 4c9d58891b09bfce8d333b3cf718bbbd349ed246 | [
"BSD-3-Clause"
] | null | null | null | forks/a_little_smalltalk/src/names.h | zenwerk/littlesmalltalk | 4c9d58891b09bfce8d333b3cf718bbbd349ed246 | [
"BSD-3-Clause"
] | null | null | null | /*
Little Smalltalk, version 2
Written by Tim Budd, Oregon State University, July 1987
*/
/*
names and sizes of internally object used internally in the system
*/
#ifndef NAMES_H
#define NAMES_H
# define classSize 5
# define nameInClass 1
# define sizeInClass 2
# define methodsInClass 3
# define superClassInClass 4
# define variablesInClass 5
# define methodSize 8
# define textInMethod 1
# define messageInMethod 2
# define bytecodesInMethod 3
# define literalsInMethod 4
# define stackSizeInMethod 5
# define temporarySizeInMethod 6
# define methodClassInMethod 7
# define watchInMethod 8
# define methodStackSize(x) intValue(basicAt(x, stackSizeInMethod))
# define methodTempSize(x) intValue(basicAt(x, temporarySizeInMethod))
# define contextSize 6
# define linkPtrInContext 1
# define methodInContext 2
# define argumentsInContext 3
# define temporariesInContext 4
# define blockSize 6
# define contextInBlock 1
# define argumentCountInBlock 2
# define argumentLocationInBlock 3
# define bytecountPositionInBlock 4
# define processSize 3
# define stackInProcess 1
# define stackTopInProcess 2
# define linkPtrInProcess 3
void nameTableInsert(object dict, int hash, object key, object value);
object hashEachElement(object dict, register int hash, int(*fun)(object));
/* compute hash value of string ---- strHash */
int strHash(const char *str);
/* return key associated with global symbol */
object globalKey(const char *str);
object nameTableLookup(object dict, const char *str);
/* initialize common symbols used by the parser and interpreter */
void initCommonSymbols();
extern object unSyms[12];
extern object binSyms[30];
#endif | 25.507692 | 74 | 0.785887 |
a705de76fb965c638923bac9137bfbab089dee4b | 2,256 | h | C | include/taskpp/detail/devector.h | znone/taskpp | 1c630e232041007cc6497d10f0c30a035663ca91 | [
"Apache-2.0"
] | 4 | 2019-03-14T01:47:53.000Z | 2020-06-24T10:48:54.000Z | include/taskpp/detail/devector.h | znone/taskpp | 1c630e232041007cc6497d10f0c30a035663ca91 | [
"Apache-2.0"
] | null | null | null | include/taskpp/detail/devector.h | znone/taskpp | 1c630e232041007cc6497d10f0c30a035663ca91 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#if defined(_MSC_VER) && _MSC_VER<1900
#define noexcept throw()
#endif //_MSC_VER
namespace taskpp
{
namespace detail
{
template <class T>
class devector
{
typedef std::vector<T> vector_type;
vector_type data_;
std::size_t front_index_;
public:
typedef typename vector_type::size_type size_type;
typedef typename vector_type::reference reference;
typedef typename vector_type::const_reference const_reference;
typedef typename vector_type::iterator iterator;
typedef typename vector_type::const_iterator const_iterator;
devector() : front_index_(0) {}
devector(devector const& x) noexcept
: data_(x.data_),
front_index_(x.front_index_)
{}
devector(devector&& x) noexcept
: data_(std::move(x.data_)),
front_index_(x.front_index_)
{
x.front_index_ = 0;
}
devector& operator=(const devector& x)
{
if (&x != this)
{
data_ = x.data_;
front_index_ = x.front_index_;
}
return *this;
}
devector& operator=(devector&& x)
{
if (&x != this)
{
data_ = x.data_;
front_index_ = x.front_index_;
x.front_index_ = 0;
}
return *this;
}
bool empty() const noexcept
{
return data_.size() == front_index_;
}
size_type size() const noexcept
{
return data_.size() - front_index_;
}
reference front() noexcept
{
return data_[front_index_];
}
const_reference front() const noexcept
{
return data_[front_index_];
}
reference back() noexcept
{
return data_.back();
}
const_reference back() const noexcept
{
return data_.back();
}
void push_back(const T& x)
{
data_.push_back(x);
}
void pop_front()
{
++front_index_;
if (empty()) {
data_.clear();
front_index_ = 0;
}
}
void swap(devector& x)
{
data_.swap(x.data_);
std::swap(front_index_, x.front_index_);
}
iterator begin() { return data_.begin() + front_index_; }
const_iterator begin() const { return data_.begin() + front_index_; }
iterator end() { return data_.end(); }
const_iterator end() const { return data_.end(); }
void insert(iterator where, const_iterator first, const_iterator last)
{
data_.insert(where, first, last);
}
void pop_front_n(size_t n)
{
front_index_+=n;
if (empty()) {
data_.clear();
front_index_ = 0;
}
}
};
}
}
| 16.962406 | 71 | 0.682624 |
736a53357c5af606a46c9dc22c980b5f4b1e4d0d | 11,892 | c | C | main.c | weirdNox/Generic-Grafcet | 18022f87e7a2456e78008f00419c58b39860c6cf | [
"MIT"
] | 2 | 2020-05-05T15:44:29.000Z | 2021-05-19T18:01:07.000Z | main.c | weirdNox/Generic-Grafcet | 18022f87e7a2456e78008f00419c58b39860c6cf | [
"MIT"
] | null | null | null | main.c | weirdNox/Generic-Grafcet | 18022f87e7a2456e78008f00419c58b39860c6cf | [
"MIT"
] | null | null | null | // -------------------------
// Generic Grafcet Framework
// -------------------------
// MIT License:
//
// Copyright 2018 Gonçalo Santos
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <termios.h>
#include <stropts.h>
// Linux (POSIX) implementation of _kbhit().
// Morgan McGuire, morgan@cs.brown.edu
int _kbhit() {
static const int STDIN = 0;
static bool initialized = false;
if (! initialized) {
// Use termios to turn off line buffering
struct termios term;
tcgetattr(STDIN, &term);
term.c_lflag &= ~ICANON;
tcsetattr(STDIN, TCSANOW, &term);
setbuf(stdin, NULL);
initialized = true;
}
int bytesWaiting;
ioctl(STDIN, FIONREAD, &bytesWaiting);
return bytesWaiting;
}
#define clear() printf("\033[H\033[J")
#define green(text) "\x1B[32m" text "\x1B[0m"
#define blue(text) "\x1B[34m" text "\x1B[0m"
#define ArrayCount(arr) ((sizeof(arr))/sizeof(*arr))
#define STATE_OUTPUT_FUNCTION(Name) void Name()
typedef STATE_OUTPUT_FUNCTION(state_output_function);
#define TRANSITION_CONDITION_FUNCTION(Name) bool Name()
typedef TRANSITION_CONDITION_FUNCTION(transition_condition_function);
#define ARR(...) {__VA_ARGS__}
#include "preprocessor_output.h"
// NOTE(nox): The ... in the macros are the place for the Output and Condition, respectively
#define newState(Grafcet, Name_, ...) \
do { \
state_id Id = State_X##Name_; \
Grafcets[Grafcet].States[Grafcets[Grafcet].StateCount++] = Id; \
strncpy(States[Id].Name, #Name_, NAME_LENGTH); \
States[Id].Output = stateAction_X##Name_; \
} while(0)
#define newTransition(Grafcet, Name_, PrevStates, NextStates_, ...) \
do { \
transition_id Id = Transition_##Name_; \
state_id P[] = PrevStates; \
state_id N[] = NextStates_; \
Grafcets[Grafcet].Transitions[Grafcets[Grafcet].TransitionCount++] = Id; \
strncpy(Transitions[Id].Name, #Name_, NAME_LENGTH); \
Transitions[Id].Condition = transitionCondition_##Name_; \
Transitions[Id].PreviousStatesCount = ArrayCount(P); \
for(int I = 0; I < ArrayCount(P); ++I) { Transitions[Id].PreviousStates[I] = P[I]; } \
Transitions[Id].NextStatesCount = ArrayCount(N); \
for(int I = 0; I < ArrayCount(N); ++I) { Transitions[Id].NextStates[I] = N[I]; } \
} while(0)
#define GRAFCET_COUNT 2
#define GRAFCET_MAX_STATES 1024
#define GRAFCET_MAX_TRANSITIONS 1024
#define NAME_LENGTH 1<<4
typedef struct {
bool Active;
char Name[NAME_LENGTH];
uint64_t Timer;
state_output_function *Output;
} state;
typedef struct {
bool Active;
char Name[NAME_LENGTH];
int PreviousStatesCount;
state_id PreviousStates[GRAFCET_MAX_STATES];
int NextStatesCount;
state_id NextStates[GRAFCET_MAX_STATES];
transition_condition_function *Condition;
} transition;
typedef struct {
int StateCount;
state_id States[GRAFCET_MAX_STATES];
int TransitionCount;
transition_id Transitions[GRAFCET_MAX_TRANSITIONS];
bool Frozen;
} grafcet;
static grafcet Grafcets[GRAFCET_COUNT];
static state States[StateCount];
static transition Transitions[TransitionCount];
// NOTE(nox): Inputs and Outputs
#define ioEnumWriter(Name, ...) IO_##Name
typedef struct {
bool Active;
bool Modified;
char Name[25];
char Key;
} input;
#define inputMacro(W) W(QUIT, 'q'), W(M_MAX, 'a'), W(M_MIN, 's'), W(PRATO1, 'd'), W(PRATO2, 'f'), \
W(PARAGEM, 'p'), W(CICLO, 'c')
#define inputStructWriter(Name, Key) { false, false, #Name, Key }
static input Inputs[] = { inputMacro(inputStructWriter) };
typedef enum { inputMacro(ioEnumWriter) } inputLabel;
typedef struct {
bool Active;
char Name[25];
} output;
#define outputStructWriter(Name) { false, #Name }
#define outputMacro(W) W(ESQUERDA), W(BOMBA_V5), W(MOTOR_PA), W(V1), W(V2), W(V3), W(V4), W(V7)
static output Outputs[] = { outputMacro(outputStructWriter) };
typedef enum { outputMacro(ioEnumWriter) } outputLabel;
#define input(Label) Inputs[IO_##Label].Active
#define RE(Label) (input(Label) && Inputs[IO_##Label].Modified)
#define FE(Label) (!input(Label) && Inputs[IO_##Label].Modified)
#define output(Label) Outputs[IO_##Label].Active = true
#define freeze(Id) Grafcets[Id].Frozen = true
#define active(Name) States[State_X##Name].Active
#define timer(Name) States[State_X##Name].Timer
#define OUTPUTS_AND_CONDITIONS
#include "preprocessor_output.h"
#undef OUTPUTS_AND_CONDITIONS
static bool checkTransitionState(transition *Transition) {
bool AllPrevious = true;
for(int PrevIndex = 0; PrevIndex < Transition->PreviousStatesCount; ++PrevIndex) {
if(!States[Transition->PreviousStates[PrevIndex]].Active) {
AllPrevious = false;
break;
}
}
if(AllPrevious) {
return Transition->Condition();
}
return false;
}
int main(int Argc, char *Argv[]) {
// NOTE(nox): Control Grafcet
newState(1, 1, {});
States[State_X1].Active = true;
newTransition(1, 1, ARR(State_X1), ARR(State_X2, State_X4, State_X6), (input(CICLO)));
newState(1, 2, { output(V1); });
newState(1, 3, {});
newTransition(1, 2, ARR(State_X2), ARR(State_X3), (input(PRATO1)));
newState(1, 4, { output(V3); });
newState(1, 5, {});
newTransition(1, 3, ARR(State_X4), ARR(State_X5), (input(PRATO2)));
newState(1, 6, { if(!input(M_MAX)) output(BOMBA_V5); });
newTransition(1, 4, ARR(State_X3, State_X5, State_X6), ARR(State_X7), (input(M_MAX)));
newState(1, 7, { output(ESQUERDA); output(MOTOR_PA); output(V2); output(V4); });
newTransition(1, 5, ARR(State_X7), ARR(State_X8), (timer(7)>=30));
newState(1, 8, { output(ESQUERDA); output(MOTOR_PA); });
newTransition(1, 6, ARR(State_X8), ARR(State_X9), (timer(8)>=40));
newState(1, 9, { output(V7); });
newTransition(1, 7, ARR(State_X9), ARR(State_X1), (input(M_MIN)));
// NOTE(nox): Supervisor Grafcet
newState(0, s1, {});
States[State_Xs1].Active = true;
newTransition(0, s1, ARR(State_Xs1), ARR(State_Xs2), ((active(2) || active(4) || active(6) || active(7)) &&
RE(PARAGEM)));
newState(0, s2, { freeze(1); });
newTransition(0, s2, ARR(State_Xs2), ARR(State_Xs1), (!input(PARAGEM)));
// NOTE(nox): Generic grafcet logic ----------------------------------------
for(;;) {
if(input(QUIT)) {
break;
}
// NOTE(nox): Reset outputs and inputs modification flag
for(int Index = 0; Index < ArrayCount(Outputs); ++Index) {
Outputs[Index].Active = false;
}
for(int Index = 0; Index < ArrayCount(Inputs); ++Index) {
Inputs[Index].Modified = false;
}
// NOTE(nox): Read inputs
while(_kbhit()) {
char C = getchar();
for(int Index = 0; Index < ArrayCount(Inputs); ++Index) {
if(Inputs[Index].Key == C) {
Inputs[Index].Active = !Inputs[Index].Active;
Inputs[Index].Modified = true;
break;
}
}
}
// NOTE(nox): Update timers
for(int Index = 0; Index < StateCount; ++Index) {
state *State = States + Index;
if(State->Active) {
++State->Timer;
}
}
clear();
for(int GrafcetId = 0; GrafcetId < GRAFCET_COUNT; ++GrafcetId) {
grafcet *Grafcet = Grafcets + GrafcetId;
// NOTE(nox): Calculate transitions
for(int Index = 0; Index < Grafcet->TransitionCount; ++Index) {
transition *Transition = Transitions + Grafcet->Transitions[Index];
Transition->Active = Grafcet->Frozen ? false : checkTransitionState(Transition);
}
// NOTE(nox): Deactivate above
for(int Index = 0; Index < Grafcet->TransitionCount; ++Index) {
transition *Transition = Transitions + Grafcet->Transitions[Index];
if(Transition->Active) {
for(int PrevIndex = 0; PrevIndex < Transition->PreviousStatesCount; ++PrevIndex) {
States[Transition->PreviousStates[PrevIndex]].Active = false;
}
}
}
// NOTE(nox): Activate below
for(int Index = 0; Index < Grafcet->TransitionCount; ++Index) {
transition *Transition = Transitions + Grafcet->Transitions[Index];
if(Transition->Active) {
for(int NextIndex = 0; NextIndex < Transition->NextStatesCount; ++NextIndex) {
States[Transition->NextStates[NextIndex]].Active = true;
States[Transition->NextStates[NextIndex]].Timer = 0;
}
}
}
// NOTE(nox): Outputs
for(int Index = 0; Index < Grafcet->StateCount; ++Index) {
state *State = States + Grafcet->States[Index];
if(State->Active) {
State->Output();
}
}
// NOTE(nox): Print debug information
printf("Grafcet %d %s\n", GrafcetId, Grafcet->Frozen ? blue("FROZEN") : "");
for(int Index = 0; Index < Grafcet->StateCount; ++Index) {
if(States[Grafcet->States[Index]].Active) {
printf("%5s: " green("Active") " %.1lfs\n", States[Grafcet->States[Index]].Name,
(double)States[Grafcet->States[Index]].Timer/10);
} else {
printf("%5s: Inactive\n", States[Grafcet->States[Index]].Name);
}
}
puts("");
// NOTE(nox): Disable freeze
Grafcet->Frozen = false;
}
printf("Inputs:\n");
for(int Index = 1; Index < ArrayCount(Inputs); ++Index) {
printf("%10s (%c): %s\n", Inputs[Index].Name, Inputs[Index].Key,
Inputs[Index].Active ? green("Active") : "Inactive");
}
puts("");
printf("Outputs:\n");
for(int Index = 0; Index < ArrayCount(Outputs); ++Index) {
printf("%10s: %s\n", Outputs[Index].Name, Outputs[Index].Active ? green("Active") : "Inactive");
}
puts("\n");
usleep(100000);
}
return 0;
}
| 35.819277 | 111 | 0.590481 |
ad980c6eaa8e2a280346fcd2dd8d416b9cbdbbee | 8,943 | c | C | clibs/libaw/common/aw_thread_poll.c | lichaoqun/QGAWLive | cc4e2ccaa5a60a46e8ffbbd7e5a54f4599dad62f | [
"Apache-2.0"
] | 705 | 2016-11-08T00:57:35.000Z | 2022-03-30T02:35:46.000Z | clibs/libaw/common/aw_thread_poll.c | lichaoqun/QGAWLive | cc4e2ccaa5a60a46e8ffbbd7e5a54f4599dad62f | [
"Apache-2.0"
] | 20 | 2017-02-12T14:08:12.000Z | 2021-08-18T09:48:14.000Z | clibs/libaw/common/aw_thread_poll.c | lichaoqun/QGAWLive | cc4e2ccaa5a60a46e8ffbbd7e5a54f4599dad62f | [
"Apache-2.0"
] | 189 | 2016-11-12T07:47:27.000Z | 2021-12-29T09:54:47.000Z | /*
copyright 2016 wanghongyu.
The project page:https://github.com/hardman/AWLive
My blog page: http://www.jianshu.com/u/1240d2400ca1
*/
#include "aw_thread_poll.h"
#include "aw_alloc.h"
#include "aw_utils.h"
#include "aw_array.h"
#include <unistd.h>
typedef struct aw_thread_poll_task{
aw_thread_func func;
void *param;
}aw_thread_poll_task;
typedef struct aw_thread_poll_element{
int index;
pthread_t *thread;
pthread_mutex_t *mutex;
pthread_cond_t *cond;
aw_thread_poll *poll;
int8_t is_finish;
//传入
aw_thread_poll_task task;
} aw_thread_poll_element;
static aw_thread_poll_element * alloc_aw_thread_poll_element(aw_thread_poll *poll, int index){
aw_thread_poll_element *ele = aw_alloc(sizeof(aw_thread_poll_element));
memset(ele, 0, sizeof(aw_thread_poll_element));
ele->thread = aw_alloc(sizeof(pthread_t));
ele->mutex = aw_alloc(sizeof(pthread_mutex_t));
pthread_mutex_init(ele->mutex, NULL);
ele->cond = aw_alloc(sizeof(pthread_cond_t));
pthread_cond_init(ele->cond, NULL);
ele->poll = poll;
ele->index = index;
return ele;
}
static void free_aw_thread_poll_element(aw_thread_poll_element ** ele_p){
aw_thread_poll_element *ele = *ele_p;
if (ele) {
if (ele->thread) {
aw_free(ele->thread);
}
if (ele->mutex) {
aw_free(ele->mutex);
}
if (ele->cond) {
aw_free(ele->cond);
}
aw_free(ele);
}
*ele_p = NULL;
}
//线程池
typedef struct aw_thread_poll {
uint32_t limit;//几个线程
aw_thread_poll_element **elements;
uint8_t is_running;
//任务列表
aw_array *task_list;
uint32_t task_list_limit;
pthread_mutex_t *task_list_mutex;
//结束回调
aw_thread_finish_cb finish_cb;
}aw_thread_poll;
static void s_inner_thread_poll_running_function(aw_thread_poll_element *th_ele){
// aw_log("[d] thread %d is start..\n", th_ele->index);
while (th_ele && th_ele->poll && th_ele->poll->is_running) {
pthread_mutex_lock(th_ele->mutex);
if (th_ele->task.func) {
// aw_log("[d] thread %d will run task..\n", th_ele->index);
th_ele->task.func(th_ele->task.param);
th_ele->task.func = NULL;
th_ele->task.param = NULL;
// aw_log("[d] thread %d finish run task..\n", th_ele->index);
}else{
pthread_mutex_lock(th_ele->poll->task_list_mutex);
aw_array *task_list = th_ele->poll->task_list;
if (task_list->count > 0) {
aw_thread_poll_task *task = aw_array_element_at_index(task_list, 0)->pointer_value;
aw_array_remove_element_at_index(task_list, 0);
th_ele->task.func = task->func;
th_ele->task.param = task->param;
aw_free(task);
// aw_log("[d]continue-- %d task list count=%ld", th_ele->index, task_list->count);
pthread_mutex_unlock(th_ele->poll->task_list_mutex);
pthread_mutex_unlock(th_ele->mutex);
continue;
}
pthread_mutex_unlock(th_ele->poll->task_list_mutex);
// aw_log("[d] thread %d will waiting..\n", th_ele->index);
pthread_cond_wait(th_ele->cond, th_ele->mutex);
// aw_log("[d] thread %d is waked up..\n", th_ele->index);
}
pthread_mutex_unlock(th_ele->mutex);
}
pthread_mutex_lock(th_ele->mutex);
th_ele->is_finish = 1;
pthread_mutex_unlock(th_ele->mutex);
// aw_log("[d] thread %d is finished..\n", th_ele->index);
}
extern aw_thread_poll *alloc_aw_thread_poll(int limit, int stored_task_list_limit){
aw_thread_poll *th_poll = aw_alloc(sizeof(aw_thread_poll));
memset(th_poll, 0, sizeof(aw_thread_poll));
th_poll->limit = limit;
th_poll->task_list_limit = stored_task_list_limit;
if (!th_poll->task_list_limit) {
th_poll->task_list_limit = 100;
}
//下标
th_poll->elements = aw_alloc(sizeof(aw_thread_poll_element*) * limit);
//任务列表
th_poll->task_list = alloc_aw_array(0);
//列表锁
th_poll->task_list_mutex = aw_alloc(sizeof(pthread_mutex_t));
pthread_mutex_init(th_poll->task_list_mutex, NULL);
th_poll->is_running = 1;
for (int i = 0; i < limit; i++) {
aw_thread_poll_element *element = alloc_aw_thread_poll_element(th_poll, i);
th_poll->elements[i] = element;
//线程
pthread_t *pthread = element->thread;
//调度策略
pthread_attr_t pth_attr;
pthread_attr_init(&pth_attr);
pthread_attr_setschedpolicy(&pth_attr, SCHED_OTHER);
pthread_create(pthread, &pth_attr, (void *)s_inner_thread_poll_running_function, element);
}
return th_poll;
}
static void aw_free_thread_poll_inner(aw_thread_poll *poll){
if (poll) {
if (poll->elements) {
int i = 0;
for (; i < poll->limit; i++) {
aw_thread_poll_element *ele = poll->elements[i];
if (!ele->is_finish) {
pthread_cond_signal(ele->cond);
pthread_join(*ele->thread, NULL);
}
free_aw_thread_poll_element(&ele);
}
aw_free(poll->elements);
poll->elements = NULL;
}
if (poll->task_list) {
free_aw_array(&poll->task_list);
}
if (poll->task_list_mutex) {
aw_free(poll->task_list_mutex);
poll->task_list_mutex = NULL;
}
aw_thread_finish_cb finish_cb = poll->finish_cb;
aw_free(poll);
if (finish_cb) {
finish_cb();
}
}
// aw_log("[d]thread_poll is finished step 2\n");
}
extern void free_aw_thread_poll(aw_thread_poll **poll_p, aw_thread_finish_cb finish_cb){
aw_thread_poll *poll = *poll_p;
if (poll) {
poll->is_running = 0;
poll->finish_cb = finish_cb;
pthread_t finish_th;
pthread_create(&finish_th, NULL, (void *)aw_free_thread_poll_inner, poll);
}else{
if (finish_cb) {
finish_cb();
}
}
// aw_log("[d]thread_poll is finished step 1\n");
}
extern void aw_add_task_to_thread_poll(aw_thread_poll *poll, aw_thread_func func, void *param){
if (poll->is_running) {
aw_thread_poll_element *avaliable_th = NULL;
int i = 0;
for (; i < poll->limit; i++) {
aw_thread_poll_element *th_ele = poll->elements[i];
if (!th_ele->task.func) {
avaliable_th = th_ele;
break;
}
}
if (avaliable_th) {
avaliable_th->task.func = func;
avaliable_th->task.param = param;
pthread_cond_signal(avaliable_th->cond);
}else{
aw_thread_poll_task *task = aw_alloc(sizeof(aw_thread_poll_task));
task->func = func;
task->param = param;
pthread_mutex_lock(poll->task_list_mutex);
if (poll->task_list->count >= poll->task_list_limit) {
aw_thread_poll_task *remove_task = aw_array_element_at_index(poll->task_list, 0)->pointer_value;
aw_array_remove_element_at_index(poll->task_list, 0);
aw_free(remove_task);
aw_log("[w] ---- thread poll stored tasks too much, so remove the first one task");
aw_log("[w] ---- you can set task_list_limit with a larger value, current task_list_limit=%d\n", poll->task_list_limit);
}
aw_array_add_pointer(&poll->task_list, task);
pthread_mutex_unlock(poll->task_list_mutex);
}
}
}
extern int aw_stored_task_count_in_thread_poll(aw_thread_poll *poll){
if (poll && poll->task_list) {
return (int)poll->task_list->count;
}
return 0;
}
static void test_thread_func(int *x){
aw_log("[d] test_thread_func p = %p, x = %d\n", x, *x);
}
static void test_thread_finish_cb(){
aw_log("[d] thread is finished !!!!\n");
// aw_print_alloc_description();
}
extern void test_thread(){
// aw_uninit_debug_alloc();
// aw_init_debug_alloc();
aw_thread_poll *th_poll = alloc_aw_thread_poll(5, 0);
usleep(3*1000000);
int idxes[] = {1,2,3,4,5,6,7,8,9,10};
int i = 0;
for (; i < 10; i++) {
aw_add_task_to_thread_poll(th_poll, (aw_thread_func)test_thread_func, idxes + i);
}
aw_log("[d] start sleep 10 sec...\n");
usleep(10 * 1000000);
aw_log("[d] finish sleep 10 sec...\n");
free_aw_thread_poll(&th_poll, test_thread_finish_cb);
aw_log("[d] main thread finished\n");
}
| 30.731959 | 136 | 0.591971 |
abdb135ef453f829d437ec88b857031db0b901bd | 2,260 | c | C | component/oai-smf/src/ngap/ies/Ngap_DRBsToQosFlowsMappingList.c | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-smf/src/ngap/ies/Ngap_DRBsToQosFlowsMappingList.c | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-smf/src/ngap/ies/Ngap_DRBsToQosFlowsMappingList.c | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NGAP-IEs"
* found in "asn.1/Information Element Definitions.asn1"
* `asn1c -pdu=all -fcompound-names -fno-include-deps -findirect-choice
* -gen-PER -D src`
*/
#include "Ngap_DRBsToQosFlowsMappingList.h"
#include "Ngap_DRBsToQosFlowsMappingItem.h"
static asn_oer_constraints_t
asn_OER_type_Ngap_DRBsToQosFlowsMappingList_constr_1 CC_NOTUSED = {
{0, 0},
-1 /* (SIZE(1..32)) */};
asn_per_constraints_t asn_PER_type_Ngap_DRBsToQosFlowsMappingList_constr_1
CC_NOTUSED = {
{APC_UNCONSTRAINED, -1, -1, 0, 0},
{APC_CONSTRAINED, 5, 5, 1, 32} /* (SIZE(1..32)) */,
0,
0 /* No PER value map */
};
asn_TYPE_member_t asn_MBR_Ngap_DRBsToQosFlowsMappingList_1[] = {
{ATF_POINTER,
0,
0,
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2)),
0,
&asn_DEF_Ngap_DRBsToQosFlowsMappingItem,
0,
{0, 0, 0},
0,
0, /* No default value */
""},
};
static const ber_tlv_tag_t asn_DEF_Ngap_DRBsToQosFlowsMappingList_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))};
asn_SET_OF_specifics_t asn_SPC_Ngap_DRBsToQosFlowsMappingList_specs_1 = {
sizeof(struct Ngap_DRBsToQosFlowsMappingList),
offsetof(struct Ngap_DRBsToQosFlowsMappingList, _asn_ctx),
0, /* XER encoding is XMLDelimitedItemList */
};
asn_TYPE_descriptor_t asn_DEF_Ngap_DRBsToQosFlowsMappingList = {
"DRBsToQosFlowsMappingList",
"DRBsToQosFlowsMappingList",
&asn_OP_SEQUENCE_OF,
asn_DEF_Ngap_DRBsToQosFlowsMappingList_tags_1,
sizeof(asn_DEF_Ngap_DRBsToQosFlowsMappingList_tags_1) /
sizeof(asn_DEF_Ngap_DRBsToQosFlowsMappingList_tags_1[0]), /* 1 */
asn_DEF_Ngap_DRBsToQosFlowsMappingList_tags_1, /* Same as above */
sizeof(asn_DEF_Ngap_DRBsToQosFlowsMappingList_tags_1) /
sizeof(asn_DEF_Ngap_DRBsToQosFlowsMappingList_tags_1[0]), /* 1 */
{&asn_OER_type_Ngap_DRBsToQosFlowsMappingList_constr_1,
&asn_PER_type_Ngap_DRBsToQosFlowsMappingList_constr_1,
SEQUENCE_OF_constraint},
asn_MBR_Ngap_DRBsToQosFlowsMappingList_1,
1, /* Single element */
&asn_SPC_Ngap_DRBsToQosFlowsMappingList_specs_1 /* Additional specs */
};
| 37.666667 | 78 | 0.713274 |
4af627a1fb021606e3b49ed4a7e0f108bbd59db9 | 808 | c | C | src/dos_fseek.c | nataliapc/sdcc_msxdos | 82c4b503c141e2347b5b81c0ed88edd101fa22ff | [
"MIT"
] | null | null | null | src/dos_fseek.c | nataliapc/sdcc_msxdos | 82c4b503c141e2347b5b81c0ed88edd101fa22ff | [
"MIT"
] | null | null | null | src/dos_fseek.c | nataliapc/sdcc_msxdos | 82c4b503c141e2347b5b81c0ed88edd101fa22ff | [
"MIT"
] | null | null | null | #include "dos.h"
#ifdef MSXDOS2
uint32_t fseek (char fp, int32_t offset, char origin) __naked
{
fp;
offset;
origin;
__asm
push ix
ld ix,#4
add ix,sp
ld b,0(ix)
ld l,1(ix)
ld h,2(ix)
ld e,3(ix)
ld d,4(ix)
ld a,5(ix)
ld c,#SEEK
DOSCALL
or a
jr z, seek_noerror$
ld de, #0xffff
ld h, #0xff
ld l, a
seek_noerror$:
pop ix
ret
__endasm;
}
#else //MSXDOS1 / CPM (FCB)
uint32_t fseek (char fp, int32_t offset, char origin)
{
fp;
FCB *fcb = (FCB*)SYSFCB;
if (origin==SEEK_SET) {
fcb->rndRecord = offset;
} else
if (origin==SEEK_CUR) {
fcb->rndRecord += offset;
} else {
//TODO: Support SEEK_END for MSX-DOS 1.x
return 0xffff;
}
return fcb->rndRecord;
}
#endif
| 14.175439 | 61 | 0.548267 |
19cac99331fef5f211d415a416d8fa5d47c34159 | 269 | h | C | Bull-Engine/Window.h | Sersius/Bull-Engine | d97c7ed4725eb9bef776ffbe9e5a13bed200cfd0 | [
"MIT"
] | null | null | null | Bull-Engine/Window.h | Sersius/Bull-Engine | d97c7ed4725eb9bef776ffbe9e5a13bed200cfd0 | [
"MIT"
] | null | null | null | Bull-Engine/Window.h | Sersius/Bull-Engine | d97c7ed4725eb9bef776ffbe9e5a13bed200cfd0 | [
"MIT"
] | null | null | null | #ifndef __WINDOW_H__
#define __WINDOW_H__
#include "Globals.h"
#include "SDL/include/SDL.h"
class Window
{
public:
Window();
virtual ~Window();
virtual void Active();
virtual bool IsActivated();
virtual void Draw() = 0;
public:
bool on = false;
};
#endif | 12.227273 | 28 | 0.687732 |
19366afb88938e42a55ed5e402343c84568138ef | 509 | h | C | include/metal/serial/syscalls.h | cHemingway/test | 7fcbd56ad6fe5368b927ea146363bf3d69cd7617 | [
"Apache-2.0"
] | 24 | 2020-07-24T18:33:58.000Z | 2022-03-23T21:00:19.000Z | include/metal/serial/syscalls.h | cHemingway/test | 7fcbd56ad6fe5368b927ea146363bf3d69cd7617 | [
"Apache-2.0"
] | 4 | 2020-07-27T05:44:26.000Z | 2021-09-02T16:05:47.000Z | include/metal/serial/syscalls.h | cHemingway/test | 7fcbd56ad6fe5368b927ea146363bf3d69cd7617 | [
"Apache-2.0"
] | 1 | 2020-07-25T15:13:20.000Z | 2020-07-25T15:13:20.000Z | /**
* @file metal/serial/syscalls.h
* @date 03.07.2020
* @author Klemens D. Morgenstern
*
*/
#ifndef METAL_TEST_SERIAL_SYSCALLS_H
#define METAL_TEST_SERIAL_SYSCALLS_H
//Allow no access to any file or process, except stdout/stdin
#define METAL_SERIAL_SYSCALLS_MODE_BLOCKED 0
//Only allow writes and leaves them unchecked. This is the default.
#define METAL_SERIAL_SYSCALLS_MODE_UNCHECKED 1
//Use full I/O facilities
#define METAL_SERIAL_SYSCALLS_MODE_FULL 2
#endif //METAL_TEST_SERIAL_SYSCALLS_H
| 24.238095 | 67 | 0.793713 |
f91521f77a6811309dd476b877a31648a17fe4aa | 186 | h | C | firebase/lib/x86_64-ios/firebase.framework/Versions/Current/Headers/functions.h | goodwin332/extension-firebase-analytics | 33ec1023a0c97b2d9780e6c9004a56247096f129 | [
"MIT"
] | null | null | null | firebase/lib/x86_64-ios/firebase.framework/Versions/Current/Headers/functions.h | goodwin332/extension-firebase-analytics | 33ec1023a0c97b2d9780e6c9004a56247096f129 | [
"MIT"
] | null | null | null | firebase/lib/x86_64-ios/firebase.framework/Versions/Current/Headers/functions.h | goodwin332/extension-firebase-analytics | 33ec1023a0c97b2d9780e6c9004a56247096f129 | [
"MIT"
] | null | null | null | // Copyright 2019 Google Inc. All Rights Reserved.
#ifndef FIREBASE_FUNCTIONS_H
#define FIREBASE_FUNCTIONS_H
#include "firebase/firebase/functions.h"
#endif // FIREBASE_FUNCTIONS_H
| 18.6 | 50 | 0.801075 |
c36fd23d1c336f53c95a2fbcc081f65b01da9d82 | 4,566 | c | C | mcc_generated_files/pwm3.c | shesee/IRRepeater | 0f19425bc5d89530acb53a1e1edbcb9cd3099041 | [
"MIT"
] | null | null | null | mcc_generated_files/pwm3.c | shesee/IRRepeater | 0f19425bc5d89530acb53a1e1edbcb9cd3099041 | [
"MIT"
] | null | null | null | mcc_generated_files/pwm3.c | shesee/IRRepeater | 0f19425bc5d89530acb53a1e1edbcb9cd3099041 | [
"MIT"
] | null | null | null | /**
PWM3 Generated Driver File
@Company
Microchip Technology Inc.
@File Name
pwm3.c
@Summary
This is the generated driver implementation file for the PWM3 driver using PIC10 / PIC12 / PIC16 / PIC18 MCUs
@Description
This header file provides implementations for driver APIs for PWM3.
Generation Information :
Product Revision : PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.65.2
Device : PIC12F1572
Driver Version : 2.01
The generated drivers are tested against the following:
Compiler : XC8 1.45 or later
MPLAB : MPLAB X 4.15
*/
/*
(c) 2018 Microchip Technology Inc. and its subsidiaries.
Subject to your compliance with these terms, you may use Microchip software and any
derivatives exclusively with Microchip products. It is your responsibility to comply with third party
license terms applicable to your use of third party software (including open source software) that
may accompany Microchip software.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS
FOR A PARTICULAR PURPOSE.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP
HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO
THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL
CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT
OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS
SOFTWARE.
*/
/**
Section: Included Files
*/
#include <xc.h>
#include "pwm3.h"
/**
Section: PWM3 APIs
*/
void PWM3_Initialize(void)
{
// set the PWM3 to the options selected in the User Interface
//PHIE disabled; DCIE disabled; OFIE disabled; PRIE disabled;
PWM3INTE = 0x00;
//PHIF cleared; OFIF cleared; DCIF cleared; PRIF cleared;
PWM3INTF = 0x00;
//PS No_Prescalar; CS HFINTOSC;
PWM3CLKCON = 0x01;
//LDS reserved; LDT disabled; LDA do_not_load;
PWM3LDCON = 0x00;
//OFM independent_run; OFS reserved; OFO match_incrementing;
PWM3OFCON = 0x00;
//PWM3PHH 0;
PWM3PHH = 0x00;
//PWM3PHL 0;
PWM3PHL = 0x00;
//PWM3DCH 0;
PWM3DCH = 0x00;
//PWM3DCL 139;
PWM3DCL = 0x8B;
//PWM3PRH 1;
PWM3PRH = 0x01;
//PWM3PRL 164;
PWM3PRL = 0xA4;
//PWM3OFH 1;
PWM3OFH = 0x01;
//PWM3OFL 164;
PWM3OFL = 0xA4;
//PWM3TMRH 0;
PWM3TMRH = 0x00;
//PWM3TMRL 0;
PWM3TMRL = 0x00;
//MODE standard_PWM; POL active_hi; OE enabled; EN enabled;
PWM3CON = 0xC0;
}
void PWM3_Start(void)
{
PWM3CONbits.EN = 1;
}
void PWM3_Stop(void)
{
PWM3CONbits.EN = 0;
}
bool PWM3_CheckOutputStatus(void)
{
return (PWM3CONbits.OUT);
}
void PWM3_LoadBufferSet(void)
{
PWM3LDCONbits.LDA = 1;
}
void PWM3_PhaseSet(uint16_t phaseCount)
{
PWM3PHH = (phaseCount>>8); //writing 8 MSBs to PWMPHH register
PWM3PHL = (phaseCount); //writing 8 LSBs to PWMPHL register
}
void PWM3_DutyCycleSet(uint16_t dutyCycleCount)
{
PWM3DCH = (dutyCycleCount>>8); //writing 8 MSBs to PWMDCH register
PWM3DCL = (dutyCycleCount); //writing 8 LSBs to PWMDCL register
}
void PWM3_PeriodSet(uint16_t periodCount)
{
PWM3PRH = (periodCount>>8); //writing 8 MSBs to PWMPRH register
PWM3PRL = (periodCount); //writing 8 LSBs to PWMPRL register
}
void PWM3_OffsetSet(uint16_t offsetCount)
{
PWM3OFH = (offsetCount>>8); //writing 8 MSBs to PWMOFH register
PWM3OFL = (offsetCount); //writing 8 LSBs to PWMOFL register
}
uint16_t PWM3_TimerCountGet(void)
{
return ((uint16_t)((PWM3TMRH<<8) | PWM3TMRL));
}
bool PWM3_IsOffsetMatchOccured(void)
{
return (PWM3INTFbits.OFIF);
}
bool PWM3_IsPhaseMatchOccured(void)
{
return (PWM3INTFbits.PHIF);
}
bool PWM3_IsDutyCycleMatchOccured(void)
{
return (PWM3INTFbits.DCIF);
}
bool PWM3_IsPeriodMatchOccured(void)
{
return (PWM3INTFbits.PRIF);
}
/**
End of File
*/
| 24.417112 | 114 | 0.644328 |
c9363459a337bdc63852aa9ad748db8093f0b9d8 | 5,635 | c | C | third_party/orientsec/orientsec_common/orientsec_grpc_common_init.c | grpc-nebula/grpc-nebula-c | 6d2660869961c904324f3e5db4fb88881400a0d7 | [
"Apache-2.0"
] | 59 | 2019-06-28T03:07:42.000Z | 2022-03-11T23:09:34.000Z | third_party/orientsec/orientsec_common/orientsec_grpc_common_init.c | grpc-nebula/grpc-nebula-c | 6d2660869961c904324f3e5db4fb88881400a0d7 | [
"Apache-2.0"
] | 3 | 2019-12-05T09:59:45.000Z | 2020-09-16T02:16:28.000Z | third_party/orientsec/orientsec_common/orientsec_grpc_common_init.c | grpc-nebula/grpc-nebula-c | 6d2660869961c904324f3e5db4fb88881400a0d7 | [
"Apache-2.0"
] | 29 | 2019-06-12T03:22:18.000Z | 2022-03-03T16:47:28.000Z | /*
* Copyright 2019 Orient Securities Co., Ltd.
* Copyright 2019 BoCloud 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.
*/
/*
* 本文件主要用于系统系统时预初始化操作
* Modified: Jianbin Yang
*/
#include "orientsec_grpc_common_init.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <grpc/support/alloc.h>
#include "orientsec_grpc_common_utils.h"
#include "orientsec_grpc_conf.h"
#include "orientsec_grpc_properties_tools.h"
static long orientsec_grpc_consumer_maxrequest = 0;
//是否生成服务跟踪信息 1 生成 0 不生成
static int g_orientsec_grpc_common_gentrace_enabled = 1;
//是否把生成的信息写kafka 1 写 0 不写(此时gentrace.enabled生效)
static int g_orientsec_grpc_common_writekafka_enabled = 1;
// consumer端依赖服务版本
static char g_orientsec_grpc_common_consumer_service_version[1024] = {0};
//服务的最大缓存数 默认值10
static int g_orientsec_grpc_cache_provider_count;
//服务根目录 默认值/Application/grpc
char* g_orientsec_grpc_common_root_directory;
char* g_orientsec_grpc_private_common_root_directory;
//// 服务分组信息
//#define MAX_CONSUMER_GROUP_LEN 256
// static char g_common_consumer_group_version[MAX_CONSUMER_GROUP_LEN];
//获取根目录参数
char* orientsec_grpc_common_get_root_dir() {
return g_orientsec_grpc_common_root_directory;
}
void common_root_directory_init() {
size_t size = sizeof(char) * 1024;
char* readbuff = (char*)malloc(size);
memset(readbuff, 0, size);
char* private_buf = (char*)gpr_zalloc(size);
orientsec_grpc_properties_get_value(
ORIENTSEC_GRPC_CONF_COMMON_ROOT_DIRECTORY, NULL, readbuff);
if (readbuff == NULL || strlen(readbuff) == 0) {
g_orientsec_grpc_common_root_directory =
ORIENTSEC_GRPC_CONF_COMMON_ROOT_DIRECTORY_DEFAULT;
} else {
g_orientsec_grpc_common_root_directory = readbuff;
}
// obtain private zk center
orientsec_grpc_properties_get_value(ORIENTSEC_GRPC_ZK_PRIVATE_ROOT, NULL,
private_buf);
if (private_buf == NULL || strlen(private_buf) == 0) {
g_orientsec_grpc_private_common_root_directory =
ORIENTSEC_GRPC_CONF_COMMON_ROOT_DIRECTORY_DEFAULT;
} else {
g_orientsec_grpc_private_common_root_directory = private_buf;
}
}
//获取是否生成服务跟踪信息参数
int orientsec_grpc_common_get_gentrace_enabled() {
return g_orientsec_grpc_common_gentrace_enabled;
}
//获取是否生成服务跟踪信息参数
int orientsec_grpc_common_get_writekafka_enabled() {
return g_orientsec_grpc_common_writekafka_enabled;
}
//获取是否生成服务跟踪信息参数
int orientsec_grpc_common_get_writekafka_enabled_set(int enable) {
g_orientsec_grpc_common_writekafka_enabled = enable;
return 0;
}
//获取consumer对服务版本要求
char* orientsec_grpc_consumer_service_version_get() {
return g_orientsec_grpc_common_consumer_service_version;
}
//获取consumer允许缓存的provider数量
int orientsec_grpc_cache_provider_count_get() {
return g_orientsec_grpc_cache_provider_count;
}
// 客户端服务版本读取配置文件初始化
void consumer_service_version_init() {
/* size_t size = sizeof(char) * 1024;
char *readbuff = (char*)malloc(size);*/
// memset(readbuff, 0, size);
orientsec_grpc_properties_get_value(
ORIENTSEC_GRPC_CONF_CONSUMER_SERVICE_VERSION, NULL,
g_orientsec_grpc_common_consumer_service_version);
// add by yang, free the memory for all branch
// free(readbuff);
}
////获取consumer对服务分组要求
// char* orientsec_grpc_consumer_service_group_get() {
// return g_common_consumer_group_version;
//}
//
//// 客户端服务版本读取配置文件初始化
// void consumer_service_group_init() {
// orientsec_grpc_properties_get_value(
// ORIENTSEC_GRPC_CONF_CONSUMER_GROUP, NULL,
// g_common_consumer_group_version);
//
//}
/*
* 初始化通用入口
*/
void orientsec_grpc_common_param_init() {
//读取配置文件
orientsec_grpc_properties_init();
size_t size = sizeof(char) * 1024;
char* readbuff = (char*)malloc(size);
////是否生成服务跟踪信息
// memset(readbuff, 0, size);
// orientsec_grpc_properties_get_value(ORIENTSEC_GRPC_TRACE_GENTRACE_KEY,
// NULL, readbuff); if (readbuff == NULL || strcmp(readbuff, "") == 0 ||
// strcmp(readbuff, "true") == 0) { g_orientsec_grpc_common_gentrace_enabled =
//ORIENTSEC_GRPC_COMMON_YES;
//}
// else {
// g_orientsec_grpc_common_gentrace_enabled = ORIENTSEC_GRPC_COMMON_NO;
//}
////是否把服务跟踪信息发送kafka
// memset(readbuff, 0, size);
// orientsec_grpc_properties_get_value(ORIENTSEC_GRPC_TRACE_WRITEKAFKA_KEY,
// NULL, readbuff); if (readbuff == NULL || strcmp(readbuff, "") == 0 ||
// strcmp(readbuff, "true") == 0) { g_orientsec_grpc_common_writekafka_enabled
//= ORIENTSEC_GRPC_COMMON_YES;
//}
// else {
// g_orientsec_grpc_common_writekafka_enabled = ORIENTSEC_GRPC_COMMON_NO;
//}
memset(readbuff, 0, size);
orientsec_grpc_properties_get_value(ORIENTSEC_GRPC_CACHE_PROVIDER_COUNT, NULL,
readbuff);
if (readbuff == NULL || strcmp(readbuff, "") == 0 ||
orientsec_grpc_common_utils_isdigit(readbuff) != 1) {
g_orientsec_grpc_cache_provider_count = 32; // default value = 32,hard code
} else {
g_orientsec_grpc_cache_provider_count = atoi(readbuff);
}
free(readbuff);
consumer_service_version_init();
common_root_directory_init();
// consumer_service_group_init();
}
| 31.132597 | 81 | 0.756877 |
c7a241cd14ccea7d06ece61054fcc6192b3a2bec | 997 | c | C | util/hash/mblue_hash.c | licett/mblue | 7f6ae7f1e079b2d75a47345cbd5f6ffadd1c9891 | [
"MIT"
] | 7 | 2018-09-20T12:52:19.000Z | 2019-02-14T08:25:19.000Z | util/hash/mblue_hash.c | licett/mblue | 7f6ae7f1e079b2d75a47345cbd5f6ffadd1c9891 | [
"MIT"
] | null | null | null | util/hash/mblue_hash.c | licett/mblue | 7f6ae7f1e079b2d75a47345cbd5f6ffadd1c9891 | [
"MIT"
] | null | null | null | /*
* =====================================================================================
*
* Filename: mblue_hash.c
*
* Description: simple string hash interface
*
* Version: 1.0
* Created: 2017/10/8 10:36:05
* Revision: none
* Compiler: gcc
*
* Author: gzzhu (), gzzhu@leqibike.com
* Organization:
*
* =====================================================================================
*/
#include "mblue_stddefine.h"
#include "mblue_hash.h"
uint32_t sdbm_hash(char *str)
{
uint32_t hash = 0;
while (*str)
{
// equivalent to: hash = 65599*hash + (*str++);
hash = (*str++) + (hash << 6) + (hash << 16) - hash;
}
return (hash & 0x7FFFFFFF);
}
uint32_t sdbm_mem(uint8_t *str, size_t len)
{
uint32_t hash = 0;
while (len--)
{
// equivalent to: hash = 65599*hash + (*str++);
hash = (*str++) + (hash << 6) + (hash << 16) - hash;
}
return (hash & 0x7FFFFFFF);
}
| 22.155556 | 89 | 0.429288 |
68e5d14e1bfaccb254accbe3d98d49b50e072fc5 | 26,166 | h | C | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/SyncServices.framework/Versions/A/Headers/ISyncManager.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | null | null | null | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/SyncServices.framework/Versions/A/Headers/ISyncManager.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | null | null | null | contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/SyncServices.framework/Versions/A/Headers/ISyncManager.h | Amity-Network/amity | 3e57379f01af4ca851079c8e469fbda7c8165b47 | [
"MIT"
] | 1 | 2021-08-13T21:12:07.000Z | 2021-08-13T21:12:07.000Z | /*
* SyncServices -- ISyncManager.h
* Copyright (c) 2003 - 2008 Apple Computer, Inc. All rights reserved.
*/
#import <Foundation/Foundation.h>
#import <SyncServices/ISyncCommon.h>
@class ISyncClient, ISyncRecordSnapshot;
/* ISyncManager is the starting point for clients looking to manage clients and syncs. It
provides methods to register new clients, look up and remove registered clients, and schedule
syncs. */
@interface ISyncManager : NSObject
+ (ISyncManager *) sharedManager NS_DEPRECATED_MAC(10_4, 10_7);
/* Check if the Sync Engine is enabled and available for syncing. */
- (BOOL)isEnabled NS_DEPRECATED_MAC(10_4, 10_7);
/* After calling isEnabled, this method will return an NSError with one of the codes enumerated below. The returned NSError will have
an info dictionary with an entry for the NSLocalizedDescriptionKey. The value of this key will be a string describing the disabled reason
that is suitable for display. The error codes are declared in SyncServicesErrors.h.
ISyncServerDisabledReasonNone, Returned when isEnabled has returned YES.
ISyncServerDisabledReasonByPreference, Returned if syncing has been disabled with a preference
ISyncServerDisabledReasonSharedNetworkHome, Returned if another sync server is running against a network home directory.
ISyncServerDisabledReasonUnresponsive, Returned if isEnabled has timed out messaging to the Sync Server
ISyncServerDisabledReasonUnknown, Returned if the Sync Server fails to respond because of an unexpected error.
*/
- (NSError *)syncDisabledReason NS_DEPRECATED_MAC(10_4, 10_7);
- (ISyncClient *)clientWithIdentifier:(NSString *)clientId NS_DEPRECATED_MAC(10_4, 10_7);
/* Register a new client. You specify here all the details needed to sync the client - supported
entities and relationships, formatters, etc. In return, you get back an ISyncClient to use
and abuse.
The client description file is a plist containing a single dictionary. The dictionary may contain
any of the following keys. For keys which specify a path, a full path name may be specified, but
usually you will just want to specify a path relative to the description file. Unless explicitly
stated, all keys are optional.
Type - a string identifying the type of client. This string must be one of the
following pre-defined values: "app" (an application like iCal or AB), "device" (a phone, Palm or
iPod), "server" (.Mac) or "peer" (a peer-to-peer client). Assume the client is an app if not
explicitly specified.
DisplayName - a string containing the display name for this client.
ImagePath - path to an image of the client. This must be an absolute path except
when the description is taken from a file. Then, it can be a path relative to the description
file.
Entities - a dictionary mapping entity names to an array. The array contains
an array of property names (both attributes and relationships), indentifying the
properties supported by the client on each record type. This field is required.
PullOnlyEntities - an array containing the names of the entities for which the
client will pull changes from the engine but will never push changes to the engine.
PushOnlyEntities - an array containing the names of the entities for which the
client will only push changes to the engine but for which it will never pull changes from
the engine.
NeverFormatsRelationships - This is deprecated on 10.6, see FormatsRelationships.
FormatsRelationships - a Boolean that indicates that this client MIGHT format
a relationship that it pulls. On 10.6 we have changed the default sense for clients
and assume that they DO NOT format relationships.
SyncsWith - a dictionary specifying the kinds of clients this client wants to sync
with. See -setShouldSynchronize:withClientsOfType: for details. The dictionary contains the
following keys:
SyncAlertTypes - an array of the client types this client wants to sync with.
SyncAlertToolPath - the path of a tool the engine will invoke when a client of
the specified type starts syncing. The tool can be passed multiple arguments on
the command line. At a minimum it will be passed "--sync" followed by the
client's client id. It may also be passed "--entitynames" followed by a comma
delimited list of entity names being synced. Any other arguments on the command
line should be ignored. In particular, tools should be prepared to handle options
on the command line that are not followed by a value. Options are always prefixed
by --. Options and values are always delimited by spaces. In 10.6 one no value
option that is sometimes passed to an alert tool is --oneshot.
It is perfectly valid to call this method for a client that has already been registered to update
the registration info. Doing so is not required, however. The engine will periodically stat the
description file to see if it has changed and update the client description automagically. This
saves you from having to manually track changes to the client description. If an upgrade lays down
a new description file, for example, the engine will detect this and automatically pick up the
changes to the client's description.
Changing the client description may result in the engine forcing the client to slow sync on the
next sync. If a client adds support for additional properties in ISyncClientEntities, for
example, the engine must slow-sync the client to guarantee the new keys are synchronized
properly. */
- (ISyncClient *)registerClientWithIdentifier:(NSString *)clientId descriptionFilePath:(NSString *)descriptionFilePath NS_DEPRECATED_MAC(10_4, 10_7);
/* Remove a previously registered client */
- (void)unregisterClient:(ISyncClient *)client NS_DEPRECATED_MAC(10_4, 10_7);
/* Register a schema. You can define new entities and relationships; you can extend an entity with
additional attributes; you can specify a data validator; you can specify a conflict resolver; and
you can provide localized names for your schema types.
A schema is defined by a "Schema.plist" file contained in a .syncschema bundle which may contain additional
images and code which support the plist. The top-level object in the plist is a dictionary which may
contain the following keys. The engine will periodically check this file to see if it has changed.
If the file has changed, the engine will automatically re-parse it to pick up the new schema
definition. This saves you from having to remember to manually re-register your schema in the event
that it has changed.
* Name - a string providing a unique name for this schema. This key is required and
you should never change the schema name. Doing so will orphan the old schema definition and
you will have to manually remove it. We recommend using the reverse-DNS naming scheme,
e.g., "com.apple.Contacts".
* MajorVersion an integer value numbered representing the major version of this schema. Schemas with different major
numbers are used to indicate a major incompatible change. Including version information is optional
but recommended. In future releases this information may be used for validation and to assist with schema migration.
* MinorVersion an integer value number representing the minor version of this schema. Schemas with different minor
numbers are used to indicate compatible schema changes. (Optional)
* BaseName the name of a schema that this schema is extending. (Optional, used with BaseMajorVersion and BaseMinorVersion.)
* BaseMajorVersion an integer value representing the major version of the schema that this schema is extending. (Optional. See BaseName.)
* BaseMinorVersion an integer value representing the minor version of the schema that this schema is extending. (Optional. See BaseName.)
* StrictParsing - a bool that allows opting in / out of the new strict validation of schemas in Leopard. This is a top level key in a schema.
If this value is true, Leopard strict validation will be used.
If this value is false, the same checking as under Tiger will be used.
If this value is not present, it will be based on the version of the SyncServices framework the registering binary linked against.
If it linked against a Leopard framework version, strict validation will be used.
* DataClasses - an array containing various data class descriptions. The data class
description contains the following:
Name - the name of the data class. This key is required. We recommend using the reverse-DNS
naming scheme, e.g., "com.apple.Contacts". The name can be localized using the strings from Schema.strings
in the .syncschema bundle.
ImagePath - the path of an image representing the data class. For most data classes this
will be the same image as would be used for the associated document type. (E.g. Contacts
would use AddressBook's .vcd image.) The path can be an absolute path, but if it is not
then SyncServices will attempt to use it to load an image resource from the .syncschema bundle.
* Entities - the value is an array of record type extension descriptions. Each
description is an NSDictionary describing an extension to an existing record type. A
description may contain the following keys; unless explicitly stated, all of the keys are
optional:
Name - the name of the entity. This key is required. We recommend using the reverse-DNS naming
scheme, e.g., "com.apple.Contacts". The name can be localized using the strings from Schema.strings in
the .syncschema bundle.
ExtensionName - the name of this extension, if you are adding attributes to an
existing entity. The extension name is used to scope
the property and relationship names to prevent collisions. We recommend using
the reverse-DNS naming scheme, e.g. com.apple.AddressBook.ContactsExtensions.
DataClass - the name of the data class this entity belongs to.
ExcludeFromDataChangeAlert - <true/> or <false/>. Defaults to false if omitted. If this flag is set then
a change to this entity will not count towards the number of changed entities for the purpose
of displaying the data change alert.
Attributes - an array containing the description of all attributes in the extension.
Each attribute description is a dictionary containing the following sub-keys.
Name - the name of the attribute. The name can be localized using the strings from Schema.strings in
the .syncschema bundle. The key for the localized name of an attribute is "$entity/$attribute_name",
for example the key for the attribute with the Name "title" in the entity with the name
"com.apple.things.Thing" would be "com.apple.things.Thing/title".
Type - the type of the attribute. Must be one of the valid attribute
types, such as string, number, etc. On 10.6 set is also a supported type.
ExcludeFromDataChangeAlert - <true/> or <false/>. Defaults to false if omitted. If this flag is set then
a change to this attribute will not count towards the number of changed attributes for the purpose
of displaying the data change alert.
AutomaticConflictResolutionPolicy - A dictionary with one or two entries with the keys
"PreferredClientTypes" and "PreferredRecord". The use of this keyword can help prevent conflicts.
The value for the PreferredClientType entry is an array comprised of the client type strings e.g.,
"app", "device", "server" and "peer". The value for the PreferredRecord key is one of "Truth", "Client", or
"LastModified". This property is per attribute and cannot be declared as a property of the
Entity. One of the more common uses is to specify that the last modified value should alway be
chosen. In this case, the PreferredClientTypes entry should be omitted. If both keys are specified,
then they must be consistent with each other. In other words, if a client specifies a value for
PreferredClientTypes of [app] and a PreferredRecord of LastModified, then the client that pushed the
conflicting change that last modified the attribute must be of type app or a conflict will be
generated.
Relationships - an array containing the description of all relationships in the
extension. Each relationship description is a dictionary containing the following keys.
Name - this is the name of the relationship. This key is required. The name can be localized using the
strings from Schema.strings in the .syncschema bundle. The key for the localized name of a relationship is
"$entity/$relationship_name", for example the key for the relationship with the Name "children" in the entity with
the name "com.apple.things.Thing" would be "com.apple.things.Thing/children".
Target - an array containing the names of the target entities. Generally, a
relationship has a single target. If the relative ordering between different
entities must be maintained, you may specify multiple entities in the target.
DeleteRule - cascade or nullify. Defaults to "nullify".
Ordinality - one or many. Defaults to "one".
Ordering - none, weak or strong. Defaults to "none".
Required - yes or no. Defaults to "no".
InverseRelationships - an array or pairs specifying this relationship's inverse
relationships. Each pair is a dictionary containing the following keys:
EntityName - the name of the entity.
RelationshipName - the name of the inverse relationship on that entity.
ExcludeFromDataChangeAlert - <true/> or <false/>. Defaults to false if omitted. If this flag is set then
a change to this relationship will not count towards the number of changed relationships for the purpose
of displaying the data change alert.
IdentityProperties - an array specifying the set of property names that are used to match a new
record from a Sync client with an existing record. If the target of a one to one relationship
is to be used, the name of the relationship is specified.
CompoundIdentityProperties - an array of array of property names. If a schema specifies both this
and the IdentityProperties key, this key is preferred. When a record is pushed, a match is
searched by using the identity keys declared in each of the sub-arraya in the order that they
appear. This means that the arrays should not have property names in common. For example, the
Contacts schema now declares its identity keys as [[first name, middle name, last name],
[company name]]. This allows a contact pushed without a company name to match a record that
was previously pushed with the same first and last name along with a company name.
PropertyDependencies - an array specifying the set of dependencies between the
properties. A dependent property is one which must be pushed to a client if any of its
dependencies are changed. Each entry in the array is itself an array of strings, specifying
the names of the co-dependent properties. Entries may only include attribute names. Relationship
names are disallowed.
Parent - the name of a relationship back to the parent for this entity. A parent is an enclosing
entity type which is used to bill changes for data change alerts and to house child records in the
conflict manager display. As an example, a contact is the parent of a phone number. If there is a
change to a phone number (or if a phone number is added or deleted), that will count as a change
to the parent contact, rather than a change to the phone number. If there is a conflict on a
phone number, it will appear as if the parent contact is in conflict, not the phone number. Not
all contained objects have a parent - for example although a bookmark is contained in a folder,
the folder is not considered the parent of the bookmark. The parent is used when a record is really
a "part" of an enclosing record, such as the phone number which is a "part" of a contact.
* Comment - used to insert optional comments to document the schema.
* ManagedObjectModels - an array containing paths to one or more CoreData managed object models (.mom files).
Relative paths are resolved against the .syncschema bundle's Resources directory. As a special case,
you can specify a path like "../../../foo.mom" to load a model that lives outside the schema bundle
(eg. in the application's Resources directory).
This registers every entity, attribute and relationship in the managed object model with Sync Services.
(Entity extensions cannot be specified in a model file.) Information specific to Sync Services is specified
in the entity or property's 'User Info' dictionary:
Entity User Info:
"com.apple.syncservices.SyncName" - the value is a string specifying the name the entity will be
registered as with Sync Services. Clients must use this name when refering to this entity.
The "sync" name may be different from the entity's name: Sync Services uses a global name space
for entities and to avoid collisions, we recommend a reverse-DNS naming scheme,
eg. "com.apple.contacts.Contact". Names with '.'s in them don't work too well with CoreData,
so this key lets you specify a globally unique name for the entity.
This key is optional. If it's not specified, Sync Services tries to construct a unique name for
the entity: if the entity name has a '.' in it, we use that directly; otherwise, we catenate the
entity's data class name with the entity's name, separated by a '.' eg. a "Contact" entity in
the "com.apple.contacts" data class would be registered with Sync Services as "com.apple.contacts.Contact"
"com.apple.syncservices.DataClass" - the value is a string specifying the name of the entity's data class.
This key is required.
"com.apple.syncservices.Parent" - the value is a string specifying the name of a relationship
back to the parent for this entity. A parent is an enclosing entity type which is used to bill changes for
data change alerts and to house child records in the conflict manager display. As an example, a contact is
the parent of a phone number. If there is a change to a phone number (or if a phone number is added or deleted),
that will count as a change to the parent contact, rather than a change to the phone number. If there is a
conflict on a phone number, it will appear as if the parent contact is in conflict, not the phone number.
Not all contained objects have a parent - for example although a bookmark is contained in a folder,
the folder is not considered the parent of the bookmark. The parent is used when a record is really
a "part" of an enclosing record, such as the phone number which is a "part" of a contact.
"com.apple.syncservices.Syncable" - "YES" or "NO". Defaults to "YES" if omitted. If this flag is set to "NO"
then the entity will not be parsed and thus not synchronized.
"com.apple.syncservices.ExcludeFromDataChangeAlert" - "YES" or "NO". Defaults to "NO" if omitted.
If this flag is set to "YES" then a change to this entity will not count towards the number of changed
entities for the purpose of displaying the data change alert.
"com.apple.syncservices.IdentityProperties" - an array of array of strings (no, that's not a typo) specifying
the properties that are used to match a new record from a sync client with an existing record. Properties
are identified by name, eg "((property1, property2, property3))". At this time, only the first array of strings
is used and any subsequent arrays are quietly ignored.
Attribute and Relationship User Info:
"com.apple.syncservices.Syncable" - "YES" or "NO". Defaults to "YES" if omitted. If this flag is set to "NO"
then the attribute / relationship will not be parsed and thus not synchronized.
"com.apple.syncservices.ExcludeFromDataChangeAlert" - "YES" or "NO". Defaults to "NO" if omitted. If this flag
is set to "YES" then a change to this attribute / relationship will not count towards the number of changed
entities for the purpose of displaying the data change alert.
It is perfectly valid to call this method for a schema that has already been registered. It is the
recommended way to update a schema. Certains kinds of changes may result in a slow sync of all
clients synchronizing the constituent entities and relationships, however. It depends on whether
there is any overlap between the property and relationship descriptions which have changed with the
properties and relationships supported by the client. Changing a schema has serious implications for
the clients synchronizing it - changes should not be undertaken lightly. */
- (BOOL)registerSchemaWithBundlePath:(NSString *)bundlePath NS_DEPRECATED_MAC(10_4, 10_7);
- (void)unregisterSchemaWithName:(NSString *)schemaName NS_DEPRECATED_MAC(10_4, 10_7);
/* This API is for sync clients that will only sync when another client, not of type application, is syncing
* the same entities. This is NOT the preferred way that clients should sync their changes. However, for
* various reasons, sometimes it is the only viable option. This API has been introduced in In 10.6, because
* some clients, such as MobileMe, may no longer sync if they determine they have no changes to push or pull.
* This API allows clients to indicate that they have changes to sync without the overhead of creating a sync
* session. Clients that use this API, will always be alerted to sync whenever a client they sync with
* requests a sync session, even if the requesting client would otherwise have no changes to push or
* pull. Clients that trickle sync or push their changes periodically on their own should not call this
* method.
*/
- (void)clientWithIdentifier:(NSString *)clientId needsSyncing:(BOOL)flag NS_DEPRECATED_MAC(10_6, 10_7);
/* Return a snapshot of the records in the Truth. The Truth stores a copy of all synchronized records
and contains the amalgamation of all properties from all clients.
The snapshot is an immutable copy of the records, taken at the time you request it. If the Truth is
subsequently modified, the changes will not be reflected in the snapshot. You can always ask for a
new shapshot if you want an up-to-date copy.
Do not use this method if you are syncing and want a snapshot of the Truth that is consistent with the
sync session. Another client may have mutated the Truth after the engine prepared your changes but
before you ask for the snapshot. If that happens, the records in this snapshot will not match the
state in the session. Use the method on ISyncSession instead. */
- (ISyncRecordSnapshot *)snapshotOfRecordsInTruthWithEntityNames:(NSArray /* NSString */ *)entityNames usingIdentifiersForClient:(ISyncClient *)client NS_DEPRECATED_MAC(10_4, 10_7);
/* Clients that register sync alert handlers may use the following three methods to manage the request modes
of the connections that are sent alerts by the sync server. (These request modes are simply the runloop modes
of the runloop that is servicing the connection's sync alerts.) The API mirrors that of NSConnection. For
example, a client that registers a sync alert handler in a process that might present a modal dialog to the
user should add the appropriate request mode of the loop, so alerts can be handled in a timely manner even
when the application is blocked for user input. */
- (void)addRequestMode:(NSString *)mode NS_DEPRECATED_MAC(10_4, 10_7);
- (void)removeRequestMode:(NSString *)mode NS_DEPRECATED_MAC(10_4, 10_7);
- (NSArray *)requestModes NS_DEPRECATED_MAC(10_4, 10_7);
@end
/* Distributed notification and task specific notification posted by the server when availability/enablement changes.
If isEnabled returns NO, and a client wants to sync when syncing becomes enabled again, the client should register
for this notification.
This notification is sent both in the case where syncing is enabled, and when it is disabled.
When this notification is sent, the object of the notification is an NSString with the value @"YES"
if syncing is enabled, and @"NO" if disabled. After receiving this notification, the client should
still call -isEnabled to be absolutely sure of the state of syncing.
For clients that use an ISyncManager they should register with the NSNotificationCenter not the NSDistributedNotificationCenter.
*/
SYNCSERVICES_EXPORT NSString * const ISyncAvailabilityChangedNotification NS_DEPRECATED_MAC(10_4, 10_7);
/* Exception raised when communication to the server is lost. The reason is a string aggregating
the name, reason, and user info from the originating exception.
*/
SYNCSERVICES_EXPORT NSString * const ISyncServerUnavailableException NS_DEPRECATED_MAC(10_4, 10_7);
| 68.677165 | 181 | 0.732668 |
22d9845b251c919ec5795e5686242c50acd8fb28 | 5,558 | c | C | shared/lcd/lcd_io.c | kwasmich/ATmega328_OTA | 3582e925819a401c0c5f5882170c2e01295ef999 | [
"MIT"
] | null | null | null | shared/lcd/lcd_io.c | kwasmich/ATmega328_OTA | 3582e925819a401c0c5f5882170c2e01295ef999 | [
"MIT"
] | null | null | null | shared/lcd/lcd_io.c | kwasmich/ATmega328_OTA | 3582e925819a401c0c5f5882170c2e01295ef999 | [
"MIT"
] | null | null | null | //
// lcd_io.c
// MegaOTA
//
// Created by Michael Kwasnicki on 06.04.20.
// Copyright © 2020 Michael Kwasnicki. All rights reserved.
//
#include "lcd_io.h"
#include "lcd_command.h"
#include "config.h"
#include "macros.h"
#include <avr/io.h>
#include <util/delay.h>
#define LCD_COLUMNS 16
#define LCD_LINES 2
#define LCD_LINE_WIDTH 40
#define LCD_CTRL_DDR DDRC
#define LCD_CTRL_PORT PORTC
#define LCD_RS_PIN PC0
#define LCD_RW_PIN PC0 // R/W is not used here
#define LCD_E_PIN PC1
#define LCD_DATA_DDR DDRC
#define LCD_DATA_PORT PORTC
#define LCD_DB0_PIN
#define LCD_DB1_PIN
#define LCD_DB2_PIN
#define LCD_DB3_PIN
#define LCD_DB4_PIN PC2
#define LCD_DB5_PIN PC3
#define LCD_DB6_PIN PC4
#define LCD_DB7_PIN PC5
#define LCD_T_SHORT 43 // µs
#define LCD_T_LONG 1539 // µs
#if defined(LCD_INTERFACE_4_BIT) || defined(LCD_INTERFACE_8_BIT)
#else
# error LCD interface not defined
#endif
#ifdef LCD_INTERFACE_4_BIT
static void write4(uint8_t data) {
BIT_SET(LCD_CTRL_PORT, _BV(LCD_E_PIN));
if (data & 0x01) BIT_SET(LCD_DATA_PORT, _BV(LCD_DB4_PIN));
else BIT_CLR(LCD_DATA_PORT, _BV(LCD_DB4_PIN));
if (data & 0x02) BIT_SET(LCD_DATA_PORT, _BV(LCD_DB5_PIN));
else BIT_CLR(LCD_DATA_PORT, _BV(LCD_DB5_PIN));
if (data & 0x04) BIT_SET(LCD_DATA_PORT, _BV(LCD_DB6_PIN));
else BIT_CLR(LCD_DATA_PORT, _BV(LCD_DB6_PIN));
if (data & 0x08) BIT_SET(LCD_DATA_PORT, _BV(LCD_DB7_PIN));
else BIT_CLR(LCD_DATA_PORT, _BV(LCD_DB7_PIN));
BIT_CLR(LCD_CTRL_PORT, _BV(LCD_E_PIN));
_delay_us(LCD_T_SHORT);
}
#endif
#ifdef LCD_INTERFACE_8_BIT
#error TDOD
static void write8(uint8_t data) {
BIT_SET(LCD_CTRL_PORT, _BV(LCD_E_PIN));
if (data & 0x01) BIT_SET(LCD_DATA_PORT, _BV(LCD_DB4_PIN));
else BIT_CLR(LCD_DATA_PORT, _BV(LCD_DB4_PIN));
if (data & 0x02) BIT_SET(LCD_DATA_PORT, _BV(LCD_DB5_PIN));
else BIT_CLR(LCD_DATA_PORT, _BV(LCD_DB5_PIN));
if (data & 0x04) BIT_SET(LCD_DATA_PORT, _BV(LCD_DB6_PIN));
else BIT_CLR(LCD_DATA_PORT, _BV(LCD_DB6_PIN));
if (data & 0x08) BIT_SET(LCD_DATA_PORT, _BV(LCD_DB7_PIN));
else BIT_CLR(LCD_DATA_PORT, _BV(LCD_DB7_PIN));
BIT_CLR(LCD_CTRL_PORT, _BV(LCD_E_PIN));
_delay_us(LCD_T_SHORT);
}
#endif
static void write(uint8_t data) {
#ifdef LCD_INTERFACE_4_BIT
write4(data >> 4);
write4(data & 0x0F);
#endif
#ifdef LCD_INTERFACE_8_BIT
write8(data);
#endif
}
void lcd_io_send_command(uint8_t cmd) {
BIT_CLR(LCD_CTRL_PORT, _BV(LCD_RS_PIN));
write(cmd);
}
void lcd_io_send_data(uint8_t data) {
BIT_SET(LCD_CTRL_PORT, _BV(LCD_RS_PIN));
write(data);
}
void lcd_io_clear_display() {
lcd_io_send_command(CLEAR_DISPLAY);
_delay_us(LCD_T_LONG);
}
void lcd_io_return_home() {
lcd_io_send_command(RETURN_HOME);
_delay_us(LCD_T_LONG);
}
void lcd_io_init() {
BIT_CLR(LCD_CTRL_PORT, _BV3(LCD_RS_PIN, LCD_RW_PIN, LCD_E_PIN)); // pull control lines low
BIT_SET(LCD_CTRL_DDR, _BV3(LCD_RS_PIN, LCD_RW_PIN, LCD_E_PIN)); // control lines are output
#ifdef LCD_INTERFACE_4_BIT
BIT_SET(LCD_DATA_PORT, _BV4(LCD_DB4_PIN, LCD_DB5_PIN, LCD_DB6_PIN, LCD_DB7_PIN)); // pull data lines low
BIT_SET(LCD_DATA_DDR, _BV4(LCD_DB4_PIN, LCD_DB5_PIN, LCD_DB6_PIN, LCD_DB7_PIN)); // data lines are output in most case
write4(0x3);
// _delay_ms(5); // > 4.1 ms
write4(0x3);
// _delay_us(101); // > 100 µs
write4(0x3);
// _delay_us(39);
write4(0x2);
// _delay_us(39);
lcd_io_send_command(FUNCTION_SET | FUNCTION_SET_4BIT | FUNCTION_SET_2LINE | FUNCTION_SET_5x8);
#endif
lcd_io_send_command(DISPLAY_CTRL | DISPLAY_CTRL_DISPLAY | DISPLAY_CTRL_BLINK);
lcd_io_clear_display();
lcd_io_send_command(ENTRY_MODE | ENTRY_MODE_LTR);
}
////// puts("0123456789ABCDEFGHIJKLMNOPQRSTabcdefghijjihgfedcbaTSRQPONMLKJIHGFEDCBA9876543210");
////
//// const char x[] = "0123456789ABCDEFGHIJKLMNOPQRSTabcdefghijjihgfedcbaTSRQPONMLKJIHGFEDCBA98765432100123456789ABCDEFGHIJKLMNOPQRSTabcdefghijjihgfedcbaTSRQPONMLKJIHGFEDCBA9876543210";
////
//// for (uint8_t s = 0; s < 80; s++) {
//// lcd_io_line(0);
////
//// for (uint8_t c = 0; c < 80; c++) {
//// send_data(x[(c + (s%40)) % 80]);
//// }
////
//// //_delay_ms(200);
//// }
//
//// send_command(ENTRY_MODE | ENTRY_MODE_RTL);
//// send_command(CURSOR_SHIFT | CURSOR_SHIFT_CURSOR | CURSOR_SHIFT_LEFT);
////
//// puts("0123456789");
//
//// _delay_ms(250);
////
//// for (uint8_t i = 0; i < 80; i++) {
//// send_command(CURSOR_SHIFT | CURSOR_SHIFT_SCREEN | CURSOR_SHIFT_LEFT);
//// _delay_ms(350);
//// }
//
// return;
//
//
//// send_data('H');
//// send_data('e');
//// send_data('l');
//// send_data('l');
//// send_data('o');
//
// _delay_ms(1000);
//
// //lcd_io_clear_display();
// lcd_io_line(0);
//
// lcd_io_send_data('W');
// lcd_io_send_data('o');
// lcd_io_send_data('r');
// lcd_io_send_data('l');
// lcd_io_send_data('d');
//
// _delay_ms(1000);
// lcd_io_return_home();
////
//// for (uint16_t i = 0; i < 256; i++) {
////// if (i % 16 == 0) {
////// _delay_ms(1000);
////// lcd_io_clear_display();
////// }
////
//// send_data(i);
//// _delay_ms(100);
//// }
void lcd_io_deinit() {
}
| 25.263636 | 189 | 0.640878 |
02d3d2099c025a69e91ca39389eb730e50d49d1f | 302 | h | C | resistor-color/resistor_color.h | pcrandall/exercism-c | 322df4057ba4c27b935630953d4a0fbd82cf0f39 | [
"MIT"
] | null | null | null | resistor-color/resistor_color.h | pcrandall/exercism-c | 322df4057ba4c27b935630953d4a0fbd82cf0f39 | [
"MIT"
] | null | null | null | resistor-color/resistor_color.h | pcrandall/exercism-c | 322df4057ba4c27b935630953d4a0fbd82cf0f39 | [
"MIT"
] | null | null | null | #include <stdio.h>
#ifndef RESISTOR_COLOR_H
#define RESISTOR_COLOR_H
typedef enum bandssss {
BLACK,
BROWN,
RED,
ORANGE,
YELLOW,
GREEN,
BLUE,
VIOLET,
GREY,
WHITE,
} resistor_band_t;
int color_code(resistor_band_t bandssss);
resistor_band_t *colors();
#endif
| 12.583333 | 41 | 0.668874 |
24ada8a117c0a4756c89b21c6e494fc09459c16f | 1,444 | h | C | components/SIpcObject/ShareMemBuffer.h | denphon/soui | 455909ede62a37ded1c1737c65c7cfbc29eae9bd | [
"MIT"
] | 1 | 2019-04-22T07:53:10.000Z | 2019-04-22T07:53:10.000Z | components/SIpcObject/ShareMemBuffer.h | denphon/soui | 455909ede62a37ded1c1737c65c7cfbc29eae9bd | [
"MIT"
] | null | null | null | components/SIpcObject/ShareMemBuffer.h | denphon/soui | 455909ede62a37ded1c1737c65c7cfbc29eae9bd | [
"MIT"
] | 1 | 2019-04-22T06:25:01.000Z | 2019-04-22T06:25:01.000Z | // MemMapFile.h: interface for the CShareMemBuffer class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(_SHAREMEMBUFFER_H__015AC2F8_C982_43A8_916D_EEA49B31428B__INCLUDED_)
#define _SHAREMEMBUFFER_H__015AC2F8_C982_43A8_916D_EEA49B31428B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <interface/sipcobj-i.h>
namespace SOUI
{
class CShareMemBuffer : public IShareBuffer
{
public:
CShareMemBuffer();
virtual ~CShareMemBuffer();
BOOL OpenMemFile(LPCTSTR pszName,DWORD dwMaximumSize, void * pSecurityAttr= NULL);
void Close();
DWORD GetBufferSize() const { return *(DWORD*)m_pBuffer; }
DWORD &GetBufferSizeRef() const { return *(DWORD*)m_pBuffer; }
DWORD GetUsedSize() const { return *(DWORD*)(m_pBuffer+sizeof(DWORD)); }
DWORD &GetUsedSizeRef() const { return *(DWORD*)(m_pBuffer + sizeof(DWORD)); }
BYTE * GetBuffer() {return m_pBuffer+ sizeof(DWORD)*2;}
const BYTE * GetBuffer() const{return m_pBuffer+ sizeof(DWORD)*2;}
public:
void StartWrite() {
DWORD & dwWritePos = GetUsedSizeRef();
dwWritePos = 0;
}
void StartRead() {
m_dwReadPos = 0;
}
int Write(const void * pBuf, UINT nLen);
int Read(void *pBuf, UINT nLen);
protected:
HANDLE m_hMap;
DWORD m_dwReadPos;
BYTE *m_pBuffer;
};
}
#endif // !defined(_SHAREMEMBUFFER_H__015AC2F8_C982_43A8_916D_EEA49B31428B__INCLUDED_)
| 24.896552 | 87 | 0.679363 |
d7e659113e51e3d0f65397647d83048540592b98 | 381 | h | C | ZZYValueSendDemo/ZZYValueSendDemo/AppDelegate.h | ZYVIP/ZZYPassValueDemo | 1944e9a1b51c3324cd73756f80b9901b1e84b102 | [
"MIT"
] | 4 | 2016-08-01T13:24:13.000Z | 2019-04-17T09:45:41.000Z | ZZYValueSendDemo/ZZYValueSendDemo/AppDelegate.h | ZYVIP/ZZYPassValueDemo | 1944e9a1b51c3324cd73756f80b9901b1e84b102 | [
"MIT"
] | null | null | null | ZZYValueSendDemo/ZZYValueSendDemo/AppDelegate.h | ZYVIP/ZZYPassValueDemo | 1944e9a1b51c3324cd73756f80b9901b1e84b102 | [
"MIT"
] | null | null | null | //
// AppDelegate.h
// ZZYValueSendDemo
//
// Created by admin on 16/7/27.
// Copyright © 2016年 断剑. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
//AppDelegate属性
@property (nonatomic, copy) NSString * string;
@property (nonatomic, strong) UIColor * color;
@end
| 19.05 | 60 | 0.71916 |
a4a18b011a47df5a22b47df44f2f559c9990752e | 519 | h | C | tile/lang/parser.h | redoclag/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 4,535 | 2017-10-20T05:03:57.000Z | 2022-03-30T15:42:33.000Z | tile/lang/parser.h | HOZHENWAI/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 984 | 2017-10-20T17:16:09.000Z | 2022-03-30T05:43:18.000Z | tile/lang/parser.h | HOZHENWAI/plaidml | 46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314 | [
"Apache-2.0"
] | 492 | 2017-10-20T18:22:32.000Z | 2022-03-30T09:00:05.000Z | #pragma once
#include <string>
#include "tile/lang/ops.h"
namespace vertexai {
namespace tile {
namespace lang {
class Parser final {
public:
Program Parse(const std::string& code, const std::string& id = "") const;
Program ParseExpr(const std::string& code, int64_t start_tmp = 0) const;
math::Polynomial<math::Rational> ParsePolynomial(const std::string& poly) const;
Contraction ParseContraction(const std::string& contract) const;
};
} // namespace lang
} // namespace tile
} // namespace vertexai
| 23.590909 | 82 | 0.722543 |
62cd61d0c2ce6602ac279dfcee39571d21d772e0 | 9,101 | h | C | legacy/btmux-exile/trunk/src/hcode/btech/btechstats.h | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-07-09T17:37:42.000Z | 2020-07-09T17:37:42.000Z | legacy/btmux-exile/trunk/src/hcode/btech/btechstats.h | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | legacy/btmux-exile/trunk/src/hcode/btech/btechstats.h | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-11-07T00:02:47.000Z | 2020-11-07T00:02:47.000Z | /* Function declarations / skill list for btechstats.c */
#ifndef BTECHSTATS_H
#define BTECHSTATS_H
#include "db.h"
#include "externs.h"
#include "interface.h"
#include "config.h"
#include "powers.h"
#include "btechstats_global.h"
#ifdef BTECHSTATS_C
char *btech_charvaluetype_names[] =
{ "Char_value", "Char_skill", "Char_advantage", "Char_attribute" };
char *btech_charskillflag_names[] =
{ "Athletic", "Mental", "Physical", "Social" };
#endif
#define EE_NUMBER 11
#ifdef BTECHSTATS
struct char_value {
char *name;
char type;
int flag;
int xpthreshold;
} char_values[] = {
{
"XP", CHAR_VALUE, 0, 0}, {
"MaxXP", CHAR_VALUE, 0, 0}, {
"Type", CHAR_VALUE, 0, 0}, {
"Level", CHAR_VALUE, 0, 0}, {
"Package", CHAR_VALUE, 0, 0}, {
"Lives", CHAR_VALUE, 0, 0}, {
"Bruise", CHAR_VALUE, 0, 0}, {
"Lethal", CHAR_VALUE, 0, 0}, {
"Unused1", CHAR_VALUE, 0, 0},
/* Advantages */
{
"Ambidextrous", CHAR_ADVANTAGE, CHAR_ADV_BOOL, 0}, {
"Exceptional_Attribute", CHAR_ADVANTAGE, CHAR_ADV_EXCEPT, 0}, {
"Extra_Edge", CHAR_ADVANTAGE, CHAR_ADV_VALUE, 0}, {
"Sixth_Sense", CHAR_ADVANTAGE, CHAR_ADV_BOOL, 0}, {
"Toughness", CHAR_ADVANTAGE, CHAR_ADV_BOOL, 0}, {
"Wealth", CHAR_ADVANTAGE, CHAR_ADV_BOOL, 0},
/* Attributes */
{
"Build", CHAR_ATTRIBUTE, 0, 0}, {
"Reflexes", CHAR_ATTRIBUTE, 0, 0}, {
"Intuition", CHAR_ATTRIBUTE, 0, 0}, {
"Learn", CHAR_ATTRIBUTE, 0, 0}, {
"Charisma", CHAR_ATTRIBUTE, 0, 0},
/* Skills themselves */
{
"Acrobatics", CHAR_SKILL, SK_XP | CHAR_ATHLETIC, 50}, {
"Administration", CHAR_SKILL, SK_XP | CHAR_MENTAL, 50}, {
"Alternate_Identity", CHAR_SKILL, SK_XP | CHAR_MENTAL, 50}, {
"Appraisal", CHAR_SKILL, SK_XP | CHAR_MENTAL, 50}, {
"Archery", CHAR_SKILL, SK_XP | CHAR_ATHLETIC, 50}, {
"Blade", CHAR_SKILL, SK_XP | CHAR_ATHLETIC | CAREER_MISC, 50}, {
"Bureaucracy", CHAR_SKILL, SK_XP | CHAR_SOCIAL | CAREER_MISC, 50}, {
"Climbing", CHAR_SKILL, SK_XP | CHAR_ATHLETIC, 50}, {
"Comm-Conventional", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECH, 150}, {
"Comm-Hyperpulse", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECH, 50}, {
"Computer", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECH, 50}, {
"Cryptography", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECH, 50}, {
"Demolitions", CHAR_SKILL, SK_XP | CHAR_MENTAL, 50}, {
"Disguise", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_RECON, 50}, {
#if NEW_STATS
"Piloting-Tracked", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_CAVALRY, 3000}, {
#else
"Drive", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_CAVALRY, 3000}, {
#endif
"Engineering", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECH, 50}, {
"Escape_Artist", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_RECON, 50}, {
"Forgery", CHAR_SKILL, SK_XP | CHAR_MENTAL, 50}, {
"Gambling", CHAR_SKILL, SK_XP | CHAR_MENTAL, 50}, {
#if NEW_STATS
"Gunnery-Laser", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_GUNNER, 7500}, {
"Gunnery-Missile", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_GUNNER, 7500}, {
"Gunnery-Autocannon", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_GUNNER, 7500}, {
"Gunnery-Artillery", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_ARTILLERY , 5000}, {
"Gunnery-Spotting", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_CAVALRY, 1500}, {
"Piloting-Hover", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_CAVALRY, 3000}, {
"Piloting-Wheeled", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_CAVALRY, 3000}, {
#else
"Gunnery-Aerospace", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_AERO, 1000}, {
"Gunnery-Artillery", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_ARTILLERY, 500}, {
"Gunnery-Battlemech", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_BMECH, 1600}, {
"Gunnery-BSuit", CHAR_SKILL, SK_XP | CHAR_PHYSICAL| CAREER_BSUIT, 500}, {
"Gunnery-Conventional", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_CAVALRY, 1600}, {
"Gunnery-Spacecraft", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_DROPSHIP, 50}, {
"Gunnery-Spotting", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_ARTILLERY, 5}, {
#endif
"Impersonation", CHAR_SKILL, SK_XP | CHAR_SOCIAL, 50}, {
"Interrogation", CHAR_SKILL, SK_XP | CHAR_SOCIAL | CAREER_RECON, 50}, {
"Jump_Pack", CHAR_SKILL, SK_XP | CHAR_ATHLETIC, 50}, {
"Leadership", CHAR_SKILL, SK_XP | CHAR_SOCIAL | CAREER_ACADMISC, 50}, {
"Medtech", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_MISC, 300}, {
"Navigation", CHAR_SKILL, SK_XP | CHAR_MENTAL, 25}, {
"Negotiation", CHAR_SKILL, SK_XP | CHAR_SOCIAL, 25}, {
"Perception", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_RECON, 150}, {
#if NEW_STATS
"Piloting-Quad", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_BMECH, 3000}, {
"Piloting-Biped", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_BMECH, 3000}, {
"Piloting-BSuit", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_BSUIT, 3000}, {
"Piloting-Spacecraft", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_DROPSHIP, 3000}, {
#else
"Piloting-Aerospace", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_AERO, 2500}, {
"Piloting-Battlemech", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_BMECH, 3000}, {
"Piloting-BSuit", CHAR_SKILL, SK_XP | CHAR_PHYSICAL, 3000}, {
"Piloting-Spacecraft", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_DROPSHIP, 50}, {
#endif
"Protocol", CHAR_SKILL, SK_XP | CHAR_SOCIAL, 50}, {
"Quickdraw", CHAR_SKILL, SK_XP | CHAR_PHYSICAL, 50}, {
"Research", CHAR_SKILL, SK_XP |CHAR_MENTAL | CAREER_TECH, 100}, {
"Running", CHAR_SKILL, SK_XP | CHAR_ATHLETIC, 100}, {
"Scrounge", CHAR_SKILL, SK_XP | CHAR_SOCIAL | CAREER_TECH, 50}, {
"Security_Systems", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_RECON, 50}, {
"Seduction", CHAR_SKILL, SK_XP | CHAR_SOCIAL, 50}, {
"Small_Arms", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_MISC, 50}, {
"Stealth", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_RECON, 50}, {
"Strategy", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_ACADMISC, 50}, {
"Streetwise", CHAR_SKILL, SK_XP | CHAR_SOCIAL, 50}, {
"Support_Weapons", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_MISC, 50}, {
"Survival", CHAR_SKILL, SK_XP | CHAR_MENTAL, 50}, {
"Swimming", CHAR_SKILL, SK_XP | CHAR_ATHLETIC, 50}, {
"Tactics", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_ACADMISC, 50}, {
"Technician-Aerospace", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECHVEH, 50}, {
"Technician-BSuit", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECHBS, 200}, {
"Technician-Battlemech", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECHMECH, 600}, {
"Technician-Electronics", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECH, 50}, {
"Technician-Mechanic", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECHVEH, 400}, {
"Technician-Weapons", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECH, 300}, {
"Throwing_Weapons", CHAR_SKILL, SK_XP | CHAR_PHYSICAL, 50}, {
"Tinker", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_TECH, 50}, {
"Tracking", CHAR_SKILL, SK_XP | CHAR_MENTAL | CAREER_RECON, 50}, {
"Training", CHAR_SKILL, SK_XP | CHAR_SOCIAL, 50}, {
"Unarmed_Combat", CHAR_SKILL, SK_XP | CHAR_ATHLETIC | CAREER_MISC, 50}, {
"Dodge_Maneuver", CHAR_ADVANTAGE, SK_XP | CHAR_ADV_BOOL, 0}, {
"Maneuvering_Ace", CHAR_ADVANTAGE, SK_XP | CHAR_ADV_BOOL, 0}, {
"Melee_Specialist", CHAR_ADVANTAGE, SK_XP | CHAR_ADV_BOOL, 0}, {
"Pain_Resistance", CHAR_ADVANTAGE, SK_XP | CHAR_ADV_BOOL, 0}, {
"Speed_Demon", CHAR_ADVANTAGE, SK_XP | CHAR_ADV_BOOL, 0}
#if NEW_STATS
, {
"Piloting-Aerospace", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_AERO, 3000}, {
"Piloting-Naval", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_CAVALRY, 3000}, {
"Gunnery-Flamer", CHAR_SKILL, SK_XP | CHAR_PHYSICAL | CAREER_GUNNER , 3000}, {
"Tech_Aptitude", CHAR_ADVANTAGE, CHAR_ADV_BOOL, 0}
#endif
};
#define NUM_CHARVALUES sizeof(char_values)/sizeof(struct char_value)
char *char_values_short[NUM_CHARVALUES];
/*************************************************************************/
char *char_levels[] = { "Green", "Regular", "Veteran",
"Elite", "Historical"
};
#define NUM_CHARLEVELS 5
char *char_types[] = { "Inner_Sphere", "Clan_MechWarrior",
"Clan_Aerospace", "Clan_Elemental",
"Clan_Freebirth", "Clan_Other"
};
#define NUM_CHARTYPES 6
char *char_packages[] = { "None",
"Primary_Clan_Warrior", "Secondary_Clan_Warrior",
"Secondar_Clan_Pilot", "Clan_Elemental",
"Basic_Academy", "Advanced_Academy",
"Basic_University", "Advanced_University"
};
#define NUM_CHARPACKAGES 9
/*
Okay.. XP is gained as follows:
- If last xp-gain use is >= 60 sec away, add xp.
- Must be online
*/
typedef struct {
dbref dbref;
unsigned char values[NUM_CHARVALUES];
time_t last_use[NUM_CHARVALUES];
int xp[NUM_CHARVALUES];
} PSTATS;
#endif
#include "p.btechstats.h"
#endif /* BTECHSTATS_H */
| 44.612745 | 90 | 0.662565 |
91f7ca3da62be683e1ea848267eca104331f5d26 | 1,928 | h | C | src/vehicle.h | ek8203/CarND-Path-Planning-Project | d15b46a5659dcfd5732b28c2c11e5e52e9873a60 | [
"MIT"
] | null | null | null | src/vehicle.h | ek8203/CarND-Path-Planning-Project | d15b46a5659dcfd5732b28c2c11e5e52e9873a60 | [
"MIT"
] | null | null | null | src/vehicle.h | ek8203/CarND-Path-Planning-Project | d15b46a5659dcfd5732b28c2c11e5e52e9873a60 | [
"MIT"
] | null | null | null | /*
* vehicle.h
*
* Created on: May 6, 2018
* Author: nmkekrop
*/
#ifndef VEHICLE_H_
#define VEHICLE_H_
#include <iostream>
#include <random>
#include <vector>
#include <map>
#include <string>
using namespace std;
class Vehicle {
public:
map<string, int> lane_direction = {{"PLCL", -1}, {"LCL", -1}, {"LCR", 1}, {"PLCR", 1}};
double preferred_buffer = 30; // impacts "keep lane" behavior.
int lane = 1;
double s;
double v;
double a;
double target_speed = 49.5; // in m/s
int lanes_available = 3;
double max_acceleration = 0.224; // max difference in speed control per iteration to avoid jerk
int goal_lane = 1;
string state = "CS";
int id;
bool too_close = false;
double max_lane_v = 49.5;
/**
* Constructor
*/
Vehicle();
Vehicle(int id, int lane, float s, float v, float a, string state="CS");
/**
* Destructor
*/
virtual ~Vehicle();
vector<Vehicle> choose_next_state(map<int, vector<Vehicle>> predictions);
vector<string> successor_states();
vector<Vehicle> generate_trajectory(string state, map<int, vector<Vehicle>> predictions);
vector<float> get_kinematics(map<int, vector<Vehicle>> predictions, int lane);
vector<Vehicle> constant_speed_trajectory();
vector<Vehicle> keep_lane_trajectory(map<int, vector<Vehicle>> predictions);
vector<Vehicle> lane_change_trajectory(string state, map<int, vector<Vehicle>> predictions);
vector<Vehicle> prep_lane_change_trajectory(string state, map<int, vector<Vehicle>> predictions);
double position_at(int prev_size, double dt);
bool get_vehicle_behind(map<int, vector<Vehicle>> predictions, int lane, Vehicle & rVehicle);
bool get_vehicle_ahead(map<int, vector<Vehicle>> predictions, int lane, Vehicle & rVehicle);
vector<Vehicle> generate_predictions(int horizon=2);
void realize_next_state(vector<Vehicle> trajectory);
void display();
};
#endif /* VEHICLE_H_ */
| 20.956522 | 99 | 0.700207 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.